From b18355df8b25669283cfecea34e9fa0daef4e1b8 Mon Sep 17 00:00:00 2001 From: effect-bot <129879685+effect-bot@users.noreply.github.com> Date: Wed, 4 Nov 2026 00:36:48 +0100 Subject: [PATCH] Add Yaml.parseAll and return Result from Yaml.parse (#10271) --- .changeset/yaml-document-streams.md | 7 + packages/effect/src/encoding/Yaml.ts | 289 +++++++++++++++------ packages/effect/test/encoding/Yaml.test.ts | 103 +++++++- 3 files changed, 313 insertions(+), 86 deletions(-) create mode 100644 .changeset/yaml-document-streams.md diff --git a/.changeset/yaml-document-streams.md b/.changeset/yaml-document-streams.md new file mode 100644 index 0000000000..7b90254679 --- /dev/null +++ b/.changeset/yaml-document-streams.md @@ -0,0 +1,7 @@ +--- +"effect": minor +--- + +Add `Yaml.parseAll` for YAML document streams, with anchors scoped to each document and support for the `%YAML 1.2` directive. + +`Yaml.parse` now fails on input it used to misread instead of skipping or dropping it: `%YAML` versions other than 1.2, `%TAG` and other directives, a directive without a following `---`, and plain scalars starting with `%`. Input with more than one document still fails, with a message pointing to `Yaml.parseAll`. diff --git a/packages/effect/src/encoding/Yaml.ts b/packages/effect/src/encoding/Yaml.ts index e02d1e315f..5e932a0f53 100644 --- a/packages/effect/src/encoding/Yaml.ts +++ b/packages/effect/src/encoding/Yaml.ts @@ -2,16 +2,17 @@ * Parses YAML configuration files. * * Supports YAML 1.2 block and flow collections, indentless sequence values, - * multiline plain and quoted scalars, block scalars, anchors, aliases, and - * YAML 1.1 merge keys (`<<`). + * multiline plain and quoted scalars, block scalars, anchors, aliases, YAML 1.1 + * merge keys (`<<`), document streams, and the `%YAML 1.2` directive. Parsing + * returns a `Result` that fails with an `EncodingError`. * * Unlike YAML 1.2, the closing bracket of a multiline flow collection may sit * at its parent's indentation. * * Unsupported: compact nested block sequences (`- - value` on one line), - * multiline quoted scalars in flow collections, explicit complex keys, - * tag/directive processing, recursive aliases, and document streams. Mapping - * keys are JavaScript strings. + * multiline quoted scalars in flow collections, explicit complex keys, tags, + * `%TAG` and other directives, YAML versions other than 1.2, and recursive + * aliases. Mapping keys are JavaScript strings. * * @stability unstable * @since 4.0.0 @@ -141,6 +142,14 @@ const mappingSeparator = (input: string): number => findIndicator(input, ":") const isSequenceEntry = (text: string): boolean => text === "-" || text.startsWith("- ") +// YAML 1.2.2 §9.1: document markers start at column zero and are followed by whitespace. +const isDocumentMarker = (line: Line): boolean => line.indent === 0 && /^(?:---|\.\.\.)(?:[ \t]|$)/.test(line.raw) + +const isDocumentStart = (line: Line): boolean => isDocumentMarker(line) && line.raw.startsWith("---") + +// YAML 1.2.2 §5.3: `%` is the directive indicator and cannot start a plain scalar. +const directiveIndicatorError = "Plain scalars cannot start with '%'" + const foldLineBreak = (blankLines: number): string => blankLines === 0 ? " " : "\n".repeat(blankLines) // Folds the line breaks of a multiline plain flow scalar. @@ -296,7 +305,9 @@ class FlowParser { this.anchors.set(name, value) return value } - return parseScalar(foldFlowLines(this.readUntil(/[,\]}]/)).trim()) + const text = foldFlowLines(this.readUntil(/[,\]}]/)).trim() + if (text.startsWith("%")) this.fail(directiveIndicatorError) + return parseScalar(text) } private parseSequence(): Array { @@ -360,7 +371,9 @@ class FlowParser { if (character === "\"" || character === "'") { return parseKey(this.readQuoted(character)) } - return foldFlowLines(this.readUntil(/:/)).trim() + const key = foldFlowLines(this.readUntil(/:/)).trim() + if (key.startsWith("%")) this.fail(directiveIndicatorError) + return key } private readQuoted(quote: string): string { @@ -400,31 +413,135 @@ class FlowParser { } } -class YamlParser { - private readonly lines: ReadonlyArray - private index = 0 - private documentStarted = false - private readonly anchors = new Map() +const makeLine = (raw: string, number: number): Line => { + const indentation = /^( *)/.exec(raw)![1].length + return { + raw, + text: stripComment(raw.slice(indentation)), + indent: indentation, + number, + // Rejected where the line is read as structure; block scalar content may hold tabs. + tabIndent: raw[indentation] === "\t" + } +} - constructor(lines: ReadonlyArray) { +// YAML separates tokens with spaces and tabs only, unlike `String.prototype.trimEnd`. +const trimSeparation = (text: string): string => text.replace(/[ \t]+$/, "") + +// Removes the comment from a marker or directive line, keeping characters before +// it that are not YAML separation so they can be rejected. +const boundaryContent = (raw: string): string => { + const index = findIndicator(raw, "#") + return trimSeparation(index === -1 ? raw : raw.slice(0, index)) +} + +class YamlParser { + private readonly lines: Array + private index = 0 + // Lines from this index on belong to the next document, so document content + // never reads past a document marker. + private documentEnd: number + // Anchors are scoped to one document. + private anchors = new Map() + + constructor(lines: Array) { this.lines = lines + this.documentEnd = lines.length } - parse(): unknown { - this.skipIgnored() - if (this.index >= this.lines.length) return null - this.documentStarted = true - const value = this.parseNode(this.lines[this.index].indent) - this.skipIgnored() - if (this.index < this.lines.length) { - this.fail(this.lines[this.index], "Unexpected content") + private lineAt(index: number): Line | undefined { + return index < this.documentEnd ? this.lines[index] : undefined + } + + // YAML 1.2.2 §9.2. `limit` stops with an error before a document past it starts. + parseStream(limit = Number.POSITIVE_INFINITY): Array { + const documents: Array = [] + // True at the start of the stream and after a document end marker, where directives and bare documents may start. + let prefix = true + while (true) { + this.skipIgnored() + const line = this.lines[this.index] + if (line === undefined) return documents + // YAML 1.2.2 §9.1.1: a byte order mark may start any document prefix. + if (prefix && line.raw.startsWith("\uFEFF")) { + this.lines[this.index] = makeLine(line.raw.slice(1), line.number) + continue + } + if (isDocumentMarker(line) && !isDocumentStart(line)) { + if (boundaryContent(line.raw) !== "...") this.fail(line, "Unexpected content after document end marker") + this.index++ + prefix = true + continue + } + if (!prefix && !isDocumentStart(line)) this.fail(line, "Unexpected content") + if (documents.length >= limit) { + this.fail(line, "Expected a single YAML document, use parseAll to parse a document stream") + } + if (prefix && line.indent === 0 && line.text.startsWith("%")) this.parseDirectives() + this.anchors = new Map() + documents.push(this.parseDocument()) + prefix = false } + } + + // YAML 1.2.2 §6.8: only `%YAML 1.2` is supported, and directives must be followed by `---`. + private parseDirectives(): void { + let version = false + while (true) { + this.skipIgnored() + const line = this.lines[this.index] + if (line === undefined || line.indent !== 0 || !line.text.startsWith("%")) break + const [name, ...parameters] = boundaryContent(line.raw.slice(1)).split(/[ \t]+/) + if (name === "YAML") { + if (version) this.fail(line, "Duplicate %YAML directive") + if (parameters.length !== 1 || parameters[0] !== "1.2") { + this.fail(line, `Unsupported YAML version '${parameters.join(" ")}', only 1.2 is supported`) + } + version = true + } else { + this.fail(line, `Unsupported YAML directive '%${name}'`) + } + this.index++ + } + const next = this.lines[this.index] + if (next === undefined || !isDocumentStart(next)) { + this.fail(next ?? this.lines[this.index - 1], "Expected '---' after YAML directives") + } + } + + private parseDocument(): unknown { + const start = this.lines[this.index] + if (isDocumentStart(start)) this.index++ + // Scanning forward from the current line keeps a stream of many documents linear. + let end = this.index + while (end < this.lines.length && !isDocumentMarker(this.lines[end])) end++ + this.documentEnd = end + const value = this.parseDocumentContent(start) + this.documentEnd = this.lines.length return value } + private parseDocumentContent(start: Line): unknown { + if (isDocumentStart(start)) { + // Strip the comment after the marker, so quotes and flow openers are read as token starts. + const content = stripComment(start.raw.slice(3).replace(/^[ \t]+/, "")) + if (content.length > 0) { + // Block collections start on the line after the marker. + if (isSequenceEntry(content) || mappingSeparator(content) !== -1) { + this.fail(start, "Block collections cannot start on the document start line") + } + return this.parseNodeValue(content, -1) + } + } + this.skipIgnored() + const line = this.lineAt(this.index) + if (line === undefined) return null + return this.parseNode(line.indent) + } + private parseNode(indent: number, parentIndent = indent - 1): unknown { this.skipIgnored() - const line = this.lines[this.index] + const line = this.lineAt(this.index) if (line === undefined) return null if (line.indent !== indent) this.fail(line, `Expected indentation of ${indent} spaces`) if (isSequenceEntry(line.text)) return this.parseSequence(indent) @@ -436,7 +553,7 @@ class YamlParser { private parseMapping(indent: number, mapping = new MappingBuilder()): YamlRecord { while (true) { this.skipIgnored() - const line = this.lines[this.index] + const line = this.lineAt(this.index) if (line === undefined || line.indent < indent) return mapping.output if (line.indent > indent) this.fail(line, `Unexpected indentation of ${line.indent} spaces`) const separator = mappingSeparator(line.text) @@ -454,6 +571,7 @@ class YamlParser { line: Line ): void { const rawKey = text.slice(0, separator).trim() + if (rawKey.startsWith("%")) this.fail(line, directiveIndicatorError) const rawValue = text.slice(separator + 1).trimStart() const value = this.parseNodeValue(rawValue, indent, true) const fail = (message: string) => this.fail(line, message) @@ -465,7 +583,7 @@ class YamlParser { const output: Array = [] while (true) { this.skipIgnored() - const line = this.lines[this.index] + const line = this.lineAt(this.index) if (line === undefined || line.indent < indent) return output if (line.indent > indent) this.fail(line, `Unexpected indentation of ${line.indent} spaces`) if (!isSequenceEntry(line.text)) return output @@ -499,7 +617,7 @@ class YamlParser { const text = value.trimEnd() if (text.length === 0) { this.skipIgnored() - const next = this.lines[this.index] + const next = this.lineAt(this.index) if (next === undefined) return null if (next.indent > parentIndent) return this.parseNode(next.indent, parentIndent) if (allowIndentless && next.indent === parentIndent && isSequenceEntry(next.text)) { @@ -521,8 +639,8 @@ class YamlParser { private parseFlowValue(text: string, parentIndent: number): unknown { return new FlowParser(text, this.anchors, (depth) => { - const next = this.lines[this.index] - if (next === undefined || (next.indent === 0 && /^(?:---|\.\.\.)(?:\s|$)/.test(next.text))) return undefined + const next = this.lineAt(this.index) + if (next === undefined) return undefined // Continuation lines are more indented than the parent; a closing bracket may sit at its indentation. const content = next.text.trim().length > 0 if (content && next.indent < parentIndent) return undefined @@ -536,18 +654,19 @@ class YamlParser { private parsePlainValue(value: string, parentIndent: number): unknown { const first = this.lines[this.index - 1] if (/:(?:\s|$)/.test(value)) this.fail(first, "Invalid colon in plain scalar") + if (value.startsWith("%")) this.fail(first, directiveIndicatorError) let output = value let terminated = findIndicator(first.raw, "#") !== -1 while (!terminated) { const blankLines = this.skipBlankLines() - const next = this.lines[this.index] + const next = this.lineAt(this.index) if (next === undefined || next.indent <= parentIndent) break this.rejectTabIndent(next) // Quotes in plain continuations are literal. const content = next.raw.slice(next.indent) const comment = content.search(/(?:^|[ \t])#/) const text = (comment === -1 ? content : content.slice(0, comment)).trimEnd() - if (text.length === 0 || (next.indent === 0 && /^(?:---|\.\.\.)(?:\s|$)/.test(text))) break + if (text.length === 0) break if (/:(?:\s|$)/.test(text)) this.fail(next, "Invalid colon in plain scalar") this.rejectTabIndentedBlankLines(blankLines, parentIndent) output += foldLineBreak(blankLines) + text @@ -577,7 +696,7 @@ class YamlParser { this.rejectTabIndentedBlankLines(blankLines, parentIndent) output += trimFoldedEnd(line, quote) + foldLineBreak(blankLines) } - const next = this.lines[this.index++] + const next = this.lineAt(this.index++) if (next === undefined) throw new SyntaxError("Unterminated quoted YAML scalar") this.rejectTabIndent(next) if (next.raw.trim().length > 0 && next.indent <= parentIndent) { @@ -596,7 +715,7 @@ class YamlParser { let contentIndent = Number.isNaN(explicitIndent) ? undefined : parentIndent + explicitIndent let hasContent = false - while (end < this.lines.length) { + while (end < this.documentEnd) { const line = this.lines[end] // Only spaces make a line empty; a tab after the indentation is content. if (/[^ ]/.test(line.raw)) { @@ -668,26 +787,15 @@ class YamlParser { private skipBlankLines(): number { const start = this.index - while (this.index < this.lines.length && this.lines[this.index].raw.trim().length === 0) this.index++ + while (this.lineAt(this.index)?.raw.trim().length === 0) this.index++ return this.index - start } private skipIgnored(): void { - while (this.index < this.lines.length) { + while (this.index < this.documentEnd) { const line = this.lines[this.index] - const text = line.text.trimEnd() - if (text.length === 0 || text.startsWith("%")) { + if (line.text.trimEnd().length === 0) { this.index++ - } else if (line.indent === 0 && text === "---") { - if (this.documentStarted) this.fail(line, "Multiple YAML documents are not supported") - this.documentStarted = true - this.index++ - } else if (line.indent === 0 && text === "...") { - this.index++ - while (this.index < this.lines.length && this.lines[this.index].text.trimEnd().length === 0) this.index++ - if (this.index < this.lines.length) { - this.fail(this.lines[this.index], "Multiple YAML documents are not supported") - } } else { this.rejectTabIndent(line) return @@ -700,33 +808,36 @@ class YamlParser { } } -const parseDocument = (input: string): unknown => { - const source = input.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n") - const lines = source.split("\n").map((raw, index): Line => { - const indentation = /^( *)/.exec(raw)![1].length - return { - raw, - text: stripComment(raw.slice(indentation)), - indent: indentation, - number: index + 1, - // Rejected where the line is read as structure; block scalar content may hold tabs. - tabIndent: raw[indentation] === "\t" - } - }) - return new YamlParser(lines).parse() +const decode = (input: string, f: (parser: YamlParser) => A): Result.Result => { + try { + const lines = input.replace(/\r\n?/g, "\n").split("\n").map((raw, index) => makeLine(raw, index + 1)) + return Result.succeed(f(new YamlParser(lines))) + } catch (e) { + return Result.fail( + new EncodingError({ + module: "Yaml", + kind: "Decode", + input, + message: e instanceof Error ? e.message : "Invalid input" + }) + ) + } } /** - * Parses one YAML document into JavaScript values. + * Parses a single YAML document into JavaScript values. * * **Details** * * Returns `Result.succeed` with the parsed value, or `Result.fail` with an * `EncodingError` when the input is not valid YAML or uses an unsupported - * feature. + * feature. Empty input, or input holding only comments, parses to `null`. + * Input holding more than one document fails; use {@link parseAll} for + * document streams. * * The core YAML 1.2 scalar schema is used, so booleans, nulls, and numbers are - * decoded while date-like values remain strings. + * decoded while date-like values remain strings. Numbers use JavaScript number + * semantics, so integers beyond `Number.MAX_SAFE_INTEGER` lose precision. * * YAML 1.1 merge keys are always enabled. An unquoted `<<` key merges a * mapping, or a sequence of mappings, into the enclosing mapping. Explicit @@ -742,23 +853,49 @@ const parseDocument = (input: string): unknown => { * * Yaml.parse("port: 8080") // => Result.succeed({ port: 8080 }) * Result.isFailure(Yaml.parse("port: [8080")) // => true + * Result.isFailure(Yaml.parse("a: 1\n---\nb: 2")) // => true + * ``` + * + * @see {@link parseAll} for parsing a stream of documents + * + * @stability unstable + * @category decoding + * @since 4.0.0 + */ +export const parse = (input: string): Result.Result => + decode(input, (parser) => parser.parseStream(1)[0] ?? null) + +/** + * Parses a YAML stream into one JavaScript value per document. + * + * **Details** + * + * Returns `Result.succeed` with the parsed documents, or `Result.fail` with an + * `EncodingError` when any document is invalid. Documents are separated by + * `---` and `...` markers at the start of a line. An empty document parses to + * `null`, and input holding no documents parses to an empty array. Anchors + * are scoped to the document that defines them. + * + * A document may be preceded by a `%YAML 1.2` directive, which must be + * followed by `---`. Other YAML versions and other directives, including + * `%TAG`, fail. + * + * Each document is parsed like {@link parse}. + * + * **Example** (Parsing a document stream) + * + * ```ts import.meta.vitest + * import { Result } from "effect" + * import { Yaml } from "effect/encoding" + * + * Yaml.parseAll("a: 1\n---\nb: 2\n") // => Result.succeed([{ a: 1 }, { b: 2 }]) + * Yaml.parseAll("") // => Result.succeed([]) + * Result.isFailure(Yaml.parseAll("%YAML 1.1\n---\na: yes\n")) // => true * ``` * * @stability unstable * @category decoding * @since 4.0.0 */ -export const parse = (input: string): Result.Result => { - try { - return Result.succeed(parseDocument(input)) - } catch (e) { - return Result.fail( - new EncodingError({ - module: "Yaml", - kind: "Decode", - input, - message: e instanceof Error ? e.message : "Invalid input" - }) - ) - } -} +export const parseAll = (input: string): Result.Result, EncodingError> => + decode(input, (parser) => parser.parseStream()) diff --git a/packages/effect/test/encoding/Yaml.test.ts b/packages/effect/test/encoding/Yaml.test.ts index e77e304212..da38cf8fd8 100644 --- a/packages/effect/test/encoding/Yaml.test.ts +++ b/packages/effect/test/encoding/Yaml.test.ts @@ -4,8 +4,10 @@ import * as Yaml from "effect/encoding/Yaml" const parse = (input: string): unknown => Result.getOrThrow(Yaml.parse(input)) -const failureMessage = (input: string): string => { - const error = Result.getOrThrow(Result.flip(Yaml.parse(input))) +const parseAll = (input: string): unknown => Result.getOrThrow(Yaml.parseAll(input)) + +const failureMessage = (input: string, decode: typeof Yaml.parse | typeof Yaml.parseAll = Yaml.parse): string => { + const error = Result.getOrThrow(Result.flip(decode(input))) assert.strictEqual(error.kind, "Decode") assert.strictEqual(error.module, "Yaml") assert.strictEqual(error.input, input) @@ -464,15 +466,94 @@ development: assert.deepStrictEqual(parse(`metadata:\n a:\n ${marker}${suffix}\n`), { metadata: { a: marker } }) }) + // YAML 1.2.2 §9.2: a stream holds any number of documents. Expected values were checked with yaml 2.9.1. + it.each( + [ + ["mappings", "a: 1\n---\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["sequences", "- one\n---\n- two\n", [["one"], ["two"]]], + ["plain scalars", "one\n---\ntwo\n", ["one", "two"]], + ["explicit initial marker", "---\na: 1\n--- # second document\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["empty first document", "---\n---\nb: 2\n", [null, { b: 2 }]], + ["empty trailing document", "a: 1\n---\n", [{ a: 1 }, null]], + ["end marker before a start marker", "a: 1\n...\n---\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["bare document after an end marker", "a: 1\n...\nb: 2\n", [{ a: 1 }, { b: 2 }]], + ["content on start marker lines", "--- a\n--- [1, 2]\n--- &x {b: 1}\n", ["a", [1, 2], { b: 1 }]], + ["start marker content after a mapping", "a: 1\n--- {b: 2}\n--- \"x: y\"\n", [{ a: 1 }, { b: 2 }, "x: y"]], + ["an anchored empty document", "--- &a\n--- b\n", [null, "b"]], + [ + "quoted hashes on start marker lines", + "--- \"a # b\"\n--- 'a # b'\n--- [\"a # b\"]\n", + ["a # b", "a # b", ["a # b"]] + ], + [ + "separation whitespace after markers and directives", + "a: 1\n... \t\n%YAML\t1.2 \n---\nb: 2\n", + [{ a: 1 }, { b: 2 }] + ], + ["byte order marks in document prefixes", "1\n...\n\uFEFF---\n2\n...\n\uFEFF%YAML 1.2\n---\n3\n", [1, 2, 3]] + ] as const + )("parses a stream of %s with parseAll and rejects it in parse", (_, source, expected) => { + assert.deepStrictEqual(parseAll(source), expected) + assert.match(failureMessage(source), /parseAll/) + }) + it.each([ - ["mappings", "a: 1\n---\nb: 2\n"], - ["sequences", "- one\n---\n- two\n"], - ["plain scalars", "one\n---\ntwo\n"], - ["explicit initial marker", "---\na: 1\n--- # second document\nb: 2\n"], - ["empty first document", "---\n---\nb: 2\n"], - ["empty trailing document", "a: 1\n---\n"] - ])("rejects a document stream containing %s", (_, source) => { + ["empty input", ""], + ["comment-only input", "# comment\n\n"] + ])("parses %s as an empty stream", (_, source) => { + assert.deepStrictEqual(parseAll(source), []) + }) + + // yaml 2.9.1 reports an extra empty document for example 9.3; the expected values follow the spec. + it.each( + [ + [ + "2.7", + "# Ranking of 1998 home runs\n---\n- Mark McGwire\n- Sammy Sosa\n- Ken Griffey\n\n# Team ranking\n---\n- Chicago Cubs\n- St Louis Cardinals\n", + [["Mark McGwire", "Sammy Sosa", "Ken Griffey"], ["Chicago Cubs", "St Louis Cardinals"]] + ], + [ + "2.8", + "---\ntime: 20:03:20\nplayer: Sammy Sosa\naction: strike (miss)\n...\n---\ntime: 20:03:47\nplayer: Sammy Sosa\naction: grand slam\n...\n", + [ + { time: "20:03:20", player: "Sammy Sosa", action: "strike (miss)" }, + { time: "20:03:47", player: "Sammy Sosa", action: "grand slam" } + ] + ], + ["9.2", "%YAML 1.2\n---\nDocument\n... # Suffix\n", ["Document"]], + [ + "9.3", + "Bare\ndocument\n...\n# No document\n...\n|\n%!PS-Adobe-2.0 # Not the first line\n", + ["Bare document", "%!PS-Adobe-2.0 # Not the first line\n"] + ], + ["9.4", "---\n{ matches\n% : 20 }\n...\n---\n# Empty\n...\n", [{ "matches %": 20 }, null]], + ["9.5", "%YAML 1.2\n--- |\n%!PS-Adobe-2.0\n...\n%YAML 1.2\n---\n# Empty\n...\n", ["%!PS-Adobe-2.0\n", null]], + ["9.6", "Document\n---\n# Empty\n...\n%YAML 1.2\n---\nmatches %: 20\n", ["Document", null, { "matches %": 20 }]] + ] as const + )("parses YAML 1.2.2 example %s with parseAll", (_, source, expected) => { + assert.deepStrictEqual(parseAll(source), expected) + }) + + it("scopes anchors to their document", () => { + assert.deepStrictEqual(parseAll("a: &x 1\nb: *x\n---\nc: &x 2\nd: *x\n"), [{ a: 1, b: 1 }, { c: 2, d: 2 }]) + assert.match(failureMessage("a: &x 1\n---\nb: *x\n", Yaml.parseAll), /alias/) + }) + + // YAML 1.2.2 §§6.8 and 9.2: only %YAML 1.2 is processed, and directives must precede a start marker. + it.each([ + ["a directive without a start marker", "%YAML 1.2\na: 1\n"], + ["a directive after a bare document", "a: 1\n%YAML 1.2\n---\nb: 2\n"], + ["an unsupported YAML version", "%YAML 1.1\n---\na: yes\n"], + ["a YAML directive with extra parameters", "%YAML 1.2 x\n---\na\n"], + ["a TAG directive", "%TAG !e! tag:example.com,2000:\n---\na: 1\n"], + ["an indented plain scalar starting with %", "a:\n %foo\nb: 1\n"], + ["content after an end marker following a mapping", "a: 1\n... trailing: 2\n"], + ["a non-separation character after an end marker", "a: 1\n... \u00A0\n"], + ["a non-separation character before an end marker comment", "a: 1\n... \u00A0 # tail\n"], + ["an unsupported YAML version after a byte order mark", "1\n...\n\uFEFF%YAML 1.1\n---\na: yes\n"] + ])("rejects %s", (_, source) => { failureMessage(source) + failureMessage(source, Yaml.parseAll) }) it.each( @@ -480,7 +561,9 @@ development: ["mapping", "# before\n--- # start\na: 1\n... # end\n# after\n", { a: 1 }], ["sequence", "---\n- one\n- two\n...\n", ["one", "two"]], ["plain scalar", "---\none\n...\n", "one"], - ["empty document", "---\n...\n", null] + ["empty document", "---\n...\n", null], + ["anchored empty document", "--- &a\n...\n", null], + ["%YAML 1.2 directive", "%YAML 1.2\n---\nDocument\n... # Suffix\n", "Document"] ] as const )("preserves single-document markers around a %s", (_, source, expected) => { assert.deepStrictEqual(parse(source), expected)