eemeli / yaml

YAML parser and stringifier for JavaScript
https://eemeli.org/yaml
ISC License
1.28k stars 112 forks source link

Missing error on parsed document for unresolved alias #497

Open stefreak opened 1 year ago

stefreak commented 1 year ago

Describe the bug When parsing a document like this:

foo: *bar

The errors array on the parsed document is empty, and toJS will throw ReferenceError: Unresolved alias

To Reproduce

> const yaml = await import("yaml")
undefined
> const docs = yaml.parseAllDocuments("foo: *bar")
undefined
> docs.length
1
> docs[0].errors
[]
> docs[0].toJS()
Uncaught ReferenceError: Unresolved alias (the anchor must be set before the alias): bar
    at Alias.toJSON (/Users/steffen/work/github/garden/core/node_modules/yaml/dist/nodes/Alias.js:42:19)
    at Object.toJS (/Users/steffen/work/github/garden/core/node_modules/yaml/dist/nodes/toJS.js:22:26)
    at Object.addPairToJSMap (/Users/steffen/work/github/garden/core/node_modules/yaml/dist/nodes/addPairToJSMap.js:32:34)
    at YAMLMap.toJSON (/Users/steffen/work/github/garden/core/node_modules/yaml/dist/nodes/YAMLMap.js:124:28)
    at Object.toJS (/Users/steffen/work/github/garden/core/node_modules/yaml/dist/nodes/toJS.js:22:26)
    at Document.toJS (/Users/steffen/work/github/garden/core/node_modules/yaml/dist/doc/Document.js:301:26)
>

Expected behaviour I expect an error on the document after calling yaml.parseAllDocuments.

> docs[0].errors.length
1

Versions (please complete the following information):

eemeli commented 1 year ago

That's a fair concern. A method for discovering unresolved aliases should be provided, and a parsing option to include errors for them.

eemeli commented 1 week ago

Pondering now whether something actually needs to be added, as this works, and provides an opportunity to take whatever locally appropriate action when encountering an unresolvable alias.

import { parseDocument, visit } from 'yaml'

const doc = parseDocument('foo: *bar');
visit(doc, {
  Alias(key, node) {
    if (!node.resolve(doc)) throw new Error(`Unresolved alias: ${node}`)
  }
});