yaml
- Version 2.5.0
- Published
- 676 kB
- No dependencies
- ISC license
Install
npm i yaml
yarn add yaml
pnpm add yaml
Overview
JavaScript parser and stringifier for YAML
Index
Functions
Classes
Interfaces
Type Aliases
Namespaces
Functions
function isAlias
isAlias: (node: any) => node is Alias;
function isCollection
isCollection: <K = unknown, V = unknown>( node: any) => node is YAMLMap<K, V> | YAMLSeq<V>;
function isDocument
isDocument: <T extends Node<unknown> = Node<unknown>>( node: any) => node is Document<T, true>;
function isMap
isMap: <K = unknown, V = unknown>(node: any) => node is YAMLMap<K, V>;
function isNode
isNode: <T = unknown>(node: any) => node is Node<T>;
function isPair
isPair: <K = unknown, V = unknown>(node: any) => node is Pair<K, V>;
function isScalar
isScalar: <T = unknown>(node: any) => node is Scalar<T>;
function isSeq
isSeq: <T = unknown>(node: any) => node is YAMLSeq<T>;
function parse
parse: { ( src: string, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions ): any; ( src: string, reviver: Reviver, options?: ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions ): any;};
Parse an input string into JavaScript.
Only supports input consisting of a single YAML document; for multi-document support you should use
YAML.parseAllDocuments
. May throw on error, and may log warnings usingconsole.warn
.Parameter str
A string with YAML formatting.
Parameter reviver
A reviver function, as in
JSON.parse()
Returns
The value will match the type of the root value of the parsed YAML document, so Maps become objects, Sequences arrays, and scalars result in nulls, booleans, numbers and strings.
function parseAllDocuments
parseAllDocuments: < Contents extends Node<unknown> = ParsedNode, Strict extends boolean = true>( source: string, options?: ParseOptions & DocumentOptions & SchemaOptions) => | Array< Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict> > | EmptyStream;
Parse the input as a stream of YAML documents.
Documents should be separated from each other by
...
or---
marker lines.Returns
If an empty
docs
array is returned, it will be of type EmptyStream and contain additional stream information. In TypeScript, you should use'empty' in docs
as a type guard for it.
function parseDocument
parseDocument: < Contents extends Node<unknown> = ParsedNode, Strict extends boolean = true>( source: string, options?: ParseOptions & DocumentOptions & SchemaOptions) => Contents extends ParsedNode ? Document.Parsed<Contents, Strict> : Document<Contents, Strict>;
Parse an input string into a single YAML.Document
function stringify
stringify: { ( value: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions ): string; ( value: any, replacer?: Replacer, options?: | string | number | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions & ToStringOptions) ): string;};
Stringify a value as a YAML document.
Parameter replacer
A replacer array or function, as in
JSON.stringify()
Returns
Will always include
\n
as the last character, as is expected of YAML documents.
function visit
visit: typeof visit;
Apply a visitor to an AST node or document.
Walks through the tree (depth-first) starting from
node
, calling avisitor
function with three arguments: -key
: For sequence values and mapPair
, the node's index in the collection. Within aPair
,'key'
or'value'
, correspondingly.null
for the root node. -node
: The current node. -path
: The ancestry of the current node.The return value of the visitor may be used to control the traversal: -
undefined
(default): Do nothing and continue -visit.SKIP
: Do not visit the children of this node, continue with next sibling -visit.BREAK
: Terminate traversal completely -visit.REMOVE
: Remove the current node, then continue with the next one -Node
: Replace the current node, then continue by visiting it -number
: While iterating the items of a sequence or map, set the index of the next step. This is useful especially if the index of the current node has changed.If
visitor
is a single function, it will be called with all values encountered in the tree, including e.g.null
values. Alternatively, separate visitor functions may be defined for eachMap
,Pair
,Seq
,Alias
andScalar
node. To define the same visitor function for more than one node type, use theCollection
(map and seq),Value
(map, seq & scalar) andNode
(alias, map, seq & scalar) targets. Of all these, only the most specific defined one will be used for each node.
function visitAsync
visitAsync: typeof visitAsync;
Apply an async visitor to an AST node or document.
Walks through the tree (depth-first) starting from
node
, calling avisitor
function with three arguments: -key
: For sequence values and mapPair
, the node's index in the collection. Within aPair
,'key'
or'value'
, correspondingly.null
for the root node. -node
: The current node. -path
: The ancestry of the current node.The return value of the visitor may be used to control the traversal: -
Promise
: Must resolve to one of the following values -undefined
(default): Do nothing and continue -visit.SKIP
: Do not visit the children of this node, continue with next sibling -visit.BREAK
: Terminate traversal completely -visit.REMOVE
: Remove the current node, then continue with the next one -Node
: Replace the current node, then continue by visiting it -number
: While iterating the items of a sequence or map, set the index of the next step. This is useful especially if the index of the current node has changed.If
visitor
is a single function, it will be called with all values encountered in the tree, including e.g.null
values. Alternatively, separate visitor functions may be defined for eachMap
,Pair
,Seq
,Alias
andScalar
node. To define the same visitor function for more than one node type, use theCollection
(map and seq),Value
(map, seq & scalar) andNode
(alias, map, seq & scalar) targets. Of all these, only the most specific defined one will be used for each node.
Classes
class Alias
class Alias extends NodeBase {}
constructor
constructor(source: string);
property anchor
anchor?: never;
property source
source: string;
method resolve
resolve: (doc: Document) => Scalar | YAMLMap | YAMLSeq | undefined;
Resolve the value of this alias within
doc
, finding the last instance of thesource
anchor before this node.
method toJSON
toJSON: (_arg?: unknown, ctx?: ToJSContext) => {} | null;
method toString
toString: ( ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void) => string;
class Composer
class Composer< Contents extends ParsedNode = ParsedNode, Strict extends boolean = true> {}
Compose a stream of CST nodes into a stream of YAML Documents.
import { Composer, Parser } from 'yaml'const src: string = ...const tokens = new Parser().parse(src)const docs = new Composer().compose(tokens)
constructor
constructor(options?: ParseOptions & DocumentOptions & SchemaOptions);
method compose
compose: ( tokens: Iterable<Token>, forceDoc?: boolean, endOffset?: number) => Generator<Document.Parsed<Contents, Strict>, void, unknown>;
Compose tokens into documents.
Parameter forceDoc
If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
Parameter endOffset
Should be set if
forceDoc
is also set, to set the document range end and to indicate errors correctly.
method end
end: ( forceDoc?: boolean, endOffset?: number) => Generator<Document.Parsed<Contents, Strict>, void, unknown>;
Call at end of input to yield any remaining document.
Parameter forceDoc
If the stream contains no document, still emit a final document including any comments and directives that would be applied to a subsequent document.
Parameter endOffset
Should be set if
forceDoc
is also set, to set the document range end and to indicate errors correctly.
method next
next: ( token: Token) => Generator<Document.Parsed<Contents, Strict>, void, unknown>;
Advance the composer by one CST token.
method streamInfo
streamInfo: () => { comment: string; directives: Directives; errors: YAMLParseError[]; warnings: YAMLWarning[];};
Current stream status information.
Mostly useful at the end of input for an empty stream.
class Document
class Document<Contents extends Node = Node, Strict extends boolean = true> {}
constructor
constructor( value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions);
Parameter value
The initial value for the document, which will be wrapped in a Node container.
constructor
constructor( value: any, replacer: Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions);
property [NODE_TYPE]
readonly [NODE_TYPE]: Symbol;
property comment
comment: string;
A comment immediately after this Document
property commentBefore
commentBefore: string;
A comment before this Document
property contents
contents: Node<unknown>;
The document contents.
property directives
directives: Directives;
property errors
errors: YAMLError[];
Errors encountered during parsing.
property options
options: Required< Omit< ParseOptions & DocumentOptions, '_directives' | 'lineCounter' | 'version' >>;
property range
range?: Range;
The
[start, value-end, node-end]
character offsets for the part of the source parsed into this document (undefined if not parsed). Thevalue-end
andnode-end
positions are themselves not included in their respective ranges.
property schema
schema: Schema;
The schema used with the document. Use
setSchema()
to change.
property warnings
warnings: YAMLWarning[];
Warnings encountered during parsing.
method add
add: (value: any) => void;
Adds a value to the document.
method addIn
addIn: (path: Iterable<unknown>, value: unknown) => void;
Adds a value to the document.
method clone
clone: () => Document<Contents, Strict>;
Create a deep copy of this Document and its contents.
Custom Node values that inherit from
Object
still refer to their original instances.
method createAlias
createAlias: ( node: Strict extends true ? Scalar | YAMLMap | YAMLSeq : Node, name?: string) => Alias;
Create a new
Alias
node, ensuring that the targetnode
has the required anchor.If
node
already has an anchor,name
is ignored. Otherwise, thenode.anchor
value will be set toname
, or if an anchor with that name is already present in the document,name
will be used as a prefix for a new unique anchor. Ifname
is undefined, the generated anchor will use 'a' as a prefix.
method createNode
createNode: { <T = unknown>(value: T, options?: CreateNodeOptions): NodeType<T>; <T = unknown>( value: T, replacer: CreateNodeOptions | Replacer, options?: CreateNodeOptions ): NodeType<T>;};
Convert any value into a
Node
using the current schema, recursively turning objects into collections.
method createPair
createPair: < K extends Node<unknown> = Node<unknown>, V extends Node<unknown> = Node<unknown>>( key: unknown, value: unknown, options?: CreateNodeOptions) => Pair<K, V>;
Convert a key and a value into a
Pair
using the current schema, recursively wrapping all values asScalar
orCollection
nodes.
method delete
delete: (key: unknown) => boolean;
Removes a value from the document.
Returns
true
if the item was found and removed.
method deleteIn
deleteIn: (path: Iterable<unknown> | null) => boolean;
Removes a value from the document.
Returns
true
if the item was found and removed.
method get
get: (key: unknown, keepScalar?: boolean) => Strict extends true ? unknown : any;
Returns item at
key
, orundefined
if not found. By default unwraps scalar values from their surrounding node; to disable setkeepScalar
totrue
(collections are always returned intact).
method getIn
getIn: ( path: Iterable<unknown> | null, keepScalar?: boolean) => Strict extends true ? unknown : any;
Returns item at
path
, orundefined
if not found. By default unwraps scalar values from their surrounding node; to disable setkeepScalar
totrue
(collections are always returned intact).
method has
has: (key: unknown) => boolean;
Checks if the document includes a value with the key
key
.
method hasIn
hasIn: (path: Iterable<unknown> | null) => boolean;
Checks if the document includes a value at
path
.
method set
set: (key: any, value: unknown) => void;
Sets a value in this document. For
!!set
,value
needs to be a boolean to add/remove the item from the set.
method setIn
setIn: (path: Iterable<unknown> | null, value: unknown) => void;
Sets a value in this document. For
!!set
,value
needs to be a boolean to add/remove the item from the set.
method setSchema
setSchema: ( version: '1.1' | '1.2' | 'next' | null, options?: SchemaOptions) => void;
Change the YAML version and schema used by the document. A
null
version disables support for directives, explicit tags, anchors, and aliases. It also requires theschema
option to be given as aSchema
instance value.Overrides all previously set schema options.
method toJS
toJS: (opt?: ToJSOptions & { [ignored: string]: unknown }) => any;
A plain JavaScript representation of the document
contents
.
method toJSON
toJSON: (jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']) => any;
A JSON representation of the document
contents
.Parameter jsonArg
Used by
JSON.stringify
to indicate the array index or property name.
method toString
toString: (options?: ToStringOptions) => string;
A YAML representation of the document.
class Lexer
class Lexer {}
Splits an input string into lexical tokens, i.e. smaller strings that are easily identifiable by
tokens.tokenType()
.Lexing starts always in a "stream" context. Incomplete input may be buffered until a complete token can be emitted.
In addition to slices of the original input, the following control characters may also be emitted:
-
\x02
(Start of Text): A document starts with the next token -\x18
(Cancel): Unexpected end of flow-mode (indicates an error) -\x1f
(Unit Separator): Next token is a scalar value -\u{FEFF}
(Byte order mark): Emitted separately outside documents
method lex
lex: (source: string, incomplete?: boolean) => Generator<string, void, unknown>;
Generate YAML tokens from the
source
string. Ifincomplete
, a part of the last line may be left as a buffer for the next call.Returns
A generator of lexical tokens
class LineCounter
class LineCounter {}
Tracks newlines during parsing in order to provide an efficient API for determining the one-indexed
{ line, col }
position for any offset within the input.
property addNewLine
addNewLine: (offset: number) => number;
Should be called in ascending order. Otherwise, call
lineCounter.lineStarts.sort()
before callinglinePos()
.
property linePos
linePos: (offset: number) => { line: number; col: number };
Performs a binary search and returns the 1-indexed { line, col } position of
offset
. Ifline === 0
,addNewLine
has never been called oroffset
is before the first known newline.
property lineStarts
lineStarts: number[];
class Pair
class Pair<K = unknown, V = unknown> {}
constructor
constructor(key: {}, value?: {});
property [NODE_TYPE]
readonly [NODE_TYPE]: Symbol;
property key
key: {};
Always Node or null when parsed, but can be set to anything.
property srcToken
srcToken?: CollectionItem;
The CST token that was composed into this pair.
property value
value: {};
Always Node or null when parsed, but can be set to anything.
method clone
clone: (schema?: Schema) => Pair<K, V>;
method toJSON
toJSON: (_?: unknown, ctx?: ToJSContext) => ReturnType<typeof addPairToJSMap>;
method toString
toString: ( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string;
class Parser
class Parser {}
A YAML concrete syntax tree (CST) parser
const src: string = ...for (const token of new Parser().parse(src)) {// token: Token}To use the parser with a user-provided lexer:
function* parse(source: string, lexer: Lexer) {const parser = new Parser()for (const lexeme of lexer.lex(source))yield* parser.next(lexeme)yield* parser.end()}const src: string = ...const lexer = new Lexer()for (const token of parse(src, lexer)) {// token: Token}
constructor
constructor(onNewLine?: (offset: number) => void);
Parameter onNewLine
If defined, called separately with the start position of each new line (in
parse()
, including the start of input).
property offset
offset: number;
Current offset since the start of parsing
property stack
stack: Token[];
Top indicates the node that's currently being built
method end
end: () => Generator<Token, void, unknown>;
Call at end of input to push out any remaining constructions
method next
next: (source: string) => Generator<Token, void, unknown>;
Advance the parser by the
source
of one lexical token.
method parse
parse: (source: string, incomplete?: boolean) => Generator<Token, void, unknown>;
Parse
source
as a YAML stream. Ifincomplete
, a part of the last line may be left as a buffer for the next call.Errors are not thrown, but yielded as
{ type: 'error', message }
tokens.Returns
A generator of tokens representing each directive, document, and other structure.
class Scalar
class Scalar<T = unknown> extends NodeBase {}
constructor
constructor(value: {});
property anchor
anchor?: string;
An optional anchor on this node. Used by alias nodes.
property BLOCK_FOLDED
static readonly BLOCK_FOLDED: string;
property BLOCK_LITERAL
static readonly BLOCK_LITERAL: string;
property format
format?: string;
By default (undefined), numbers use decimal notation. The YAML 1.2 core schema only supports 'HEX' and 'OCT'. The YAML 1.1 schema also supports 'BIN' and 'TIME'
property minFractionDigits
minFractionDigits?: number;
If
value
is a number, use this value when stringifying this node.
property PLAIN
static readonly PLAIN: string;
property QUOTE_DOUBLE
static readonly QUOTE_DOUBLE: string;
property QUOTE_SINGLE
static readonly QUOTE_SINGLE: string;
property source
source?: string;
Set during parsing to the source string value
property type
type?: Scalar.Type;
The scalar style used for the node's string representation
property value
value: {};
method toJSON
toJSON: (arg?: any, ctx?: ToJSContext) => any;
method toString
toString: () => string;
class Schema
class Schema {}
constructor
constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults,}: SchemaOptions);
property [MAP]
readonly [MAP]: CollectionTag;
property [SCALAR]
readonly [SCALAR]: ScalarTag;
property [SEQ]
readonly [SEQ]: CollectionTag;
property compat
compat: (CollectionTag | ScalarTag)[];
property knownTags
knownTags: Record<string, CollectionTag | ScalarTag>;
property merge
merge: boolean;
property name
name: string;
property sortMapEntries
sortMapEntries: (a: Pair, b: Pair) => number;
property tags
tags: (CollectionTag | ScalarTag)[];
property toStringOptions
toStringOptions: Readonly<ToStringOptions>;
method clone
clone: () => Schema;
class YAMLError
class YAMLError extends Error {}
constructor
constructor( name: 'YAMLParseError' | 'YAMLWarning', pos: [number, number], code: ErrorCode, message: string);
property code
code: ErrorCode;
property linePos
linePos?: [LinePos] | [LinePos, LinePos];
property message
message: string;
property name
name: 'YAMLParseError' | 'YAMLWarning';
property pos
pos: [number, number];
class YAMLMap
class YAMLMap<K = unknown, V = unknown> extends Collection {}
constructor
constructor(schema?: Schema);
property items
items: Pair<K, V>[];
property tagName
static readonly tagName: string;
method add
add: (pair: Pair<K, V> | { key: K; value: V }, overwrite?: boolean) => void;
Adds a value to the collection.
Parameter overwrite
If not set
true
, using a key that is already in the collection will throw. Otherwise, overwrites the previous value.
method delete
delete: (key: unknown) => boolean;
method from
static from: ( schema: Schema, obj: unknown, ctx: CreateNodeContext) => YAMLMap<unknown, unknown>;
A generic collection parsing method that can be extended to other node classes that inherit from YAMLMap
method get
get: { (key: unknown, keepScalar: true): Scalar<V> | undefined; (key: unknown, keepScalar?: false): V; (key: unknown, keepScalar?: boolean): V | Scalar<V>;};
method has
has: (key: unknown) => boolean;
method set
set: (key: K, value: V) => void;
method toJSON
toJSON: <T extends MapLike = Map<unknown, unknown>>( _?: unknown, ctx?: ToJSContext, Type?: { new (): T }) => any;
Parameter ctx
Conversion context, originally set in Document#toJS()
Parameter Type
If set, forces the returned collection type
Returns
Instance of Type, Map, or Object
method toString
toString: ( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string;
class YAMLOMap
class YAMLOMap extends YAMLSeq {}
constructor
constructor();
property add
add: ( pair: import('../../index.js').Pair<any, any> | { key: any; value: any }, overwrite?: boolean) => void;
property delete
delete: (key: unknown) => boolean;
property get
get: { (key: unknown, keepScalar: true): | import('../../index.js').Scalar<any> | undefined; (key: unknown, keepScalar?: false): any; (key: unknown, keepScalar?: boolean): any;};
property has
has: (key: unknown) => boolean;
property set
set: (key: any, value: any) => void;
property tag
static tag: string;
method from
static from: ( schema: Schema, iterable: unknown, ctx: CreateNodeContext) => YAMLOMap;
method toJSON
toJSON: (_?: unknown, ctx?: ToJSContext) => unknown[];
If
ctx
is given, the return type is actuallyMap<unknown, unknown>
, but TypeScript won't allow widening the signature of a child method.
class YAMLParseError
class YAMLParseError extends YAMLError {}
constructor
constructor(pos: [number, number], code: ErrorCode, message: string);
class YAMLSeq
class YAMLSeq<T = unknown> extends Collection {}
constructor
constructor(schema?: Schema);
property items
items: T[];
property tagName
static readonly tagName: string;
method add
add: (value: T) => void;
method delete
delete: (key: unknown) => boolean;
Removes a value from the collection.
key
must contain a representation of an integer for this to succeed. It may be wrapped in aScalar
.Returns
true
if the item was found and removed.
method from
static from: ( schema: Schema, obj: unknown, ctx: CreateNodeContext) => YAMLSeq<unknown>;
method get
get: { (key: unknown, keepScalar: true): Scalar<T> | undefined; (key: unknown, keepScalar?: false): T; (key: unknown, keepScalar?: boolean): T | Scalar<T>;};
Returns item at
key
, orundefined
if not found. By default unwraps scalar values from their surrounding node; to disable setkeepScalar
totrue
(collections are always returned intact).key
must contain a representation of an integer for this to succeed. It may be wrapped in aScalar
.
method has
has: (key: unknown) => boolean;
Checks if the collection includes a value with the key
key
.key
must contain a representation of an integer for this to succeed. It may be wrapped in aScalar
.
method set
set: (key: unknown, value: T) => void;
Sets a value in this collection. For
!!set
,value
needs to be a boolean to add/remove the item from the set.If
key
does not contain a representation of an integer, this will throw. It may be wrapped in aScalar
.
method toJSON
toJSON: (_?: unknown, ctx?: ToJSContext) => unknown[];
method toString
toString: ( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string;
class YAMLSet
class YAMLSet<T = unknown> extends YAMLMap<T, Scalar<null> | null> {}
constructor
constructor(schema?: Schema);
property tag
static tag: string;
method add
add: ( key: | T | Pair<T, Scalar<null> | null> | { key: T; value: Scalar<null> | null }) => void;
method from
static from: ( schema: Schema, iterable: unknown, ctx: CreateNodeContext) => YAMLSet<unknown>;
method get
get: (key: unknown, keepPair?: boolean) => any;
If
keepPair
istrue
, returns the Pair matchingkey
. Otherwise, returns the value of that Pair's key.
method set
set: { (key: T, value: boolean): void; (key: T, value: null): void };
Deprecated
Will throw;
value
must be boolean
method toJSON
toJSON: (_?: unknown, ctx?: ToJSContext) => any;
method toString
toString: ( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string;
class YAMLWarning
class YAMLWarning extends YAMLError {}
constructor
constructor(pos: [number, number], code: ErrorCode, message: string);
Interfaces
interface CollectionTag
interface CollectionTag extends TagBase {}
property collection
collection: 'map' | 'seq';
The source collection type supported by this tag.
property nodeClass
nodeClass?: { new (schema?: Schema): Node; from?: (schema: Schema, obj: unknown, ctx: CreateNodeContext) => Node;};
The
Node
child class that implements this tag. If set, used to select this tag when stringifying.If the class provides a static
from
method, then that will be used if the tag object doesn't have acreateNode
method.
property resolve
resolve?: ( value: YAMLMap.Parsed | YAMLSeq.Parsed, onError: (message: string) => void, options: ParseOptions) => unknown;
Turns a value into an AST node. If returning a non-
Node
value, the output will be wrapped as aScalar
.Note: this is required if nodeClass is not provided.
property stringify
stringify?: never;
property test
test?: never;
interface EmptyStream
interface EmptyStream extends Array<Document.Parsed>, ReturnType<Composer['streamInfo']> {}
property empty
empty: true;
interface ScalarTag
interface ScalarTag extends TagBase {}
property collection
collection?: never;
property nodeClass
nodeClass?: never;
property stringify
stringify?: ( item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void) => string;
Optional function stringifying a Scalar node. If your data includes a suitable
.toString()
method, you can probably leave this undefined and use the default stringifier.Parameter item
The node being stringified.
Parameter ctx
Contains the stringifying context variables.
Parameter onComment
Callback to signal that the stringifier includes the item's comment in its output.
Parameter onChompKeep
Callback to signal that the output uses a block scalar type with the
+
chomping indicator.
property test
test?: RegExp;
Together with
default
allows for values to be stringified without an explicit tag and detected using a regular expression. For most cases, it's unlikely that you'll actually want to use these, even if you first think you do.
method resolve
resolve: ( value: string, onError: (message: string) => void, options: ParseOptions) => unknown;
Turns a value into an AST node. If returning a non-
Node
value, the output will be wrapped as aScalar
.
Type Aliases
type asyncVisitor
type asyncVisitor = | asyncVisitorFn<unknown> | { Alias?: asyncVisitorFn<Alias>; Collection?: asyncVisitorFn<YAMLMap | YAMLSeq>; Map?: asyncVisitorFn<YAMLMap>; Node?: asyncVisitorFn<Alias | Scalar | YAMLMap | YAMLSeq>; Pair?: asyncVisitorFn<Pair>; Scalar?: asyncVisitorFn<Scalar>; Seq?: asyncVisitorFn<YAMLSeq>; Value?: asyncVisitorFn<Scalar | YAMLMap | YAMLSeq>; };
type asyncVisitorFn
type asyncVisitorFn<T> = ( key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => | void | symbol | number | Node | Pair | Promise<void | symbol | number | Node | Pair>;
type CreateNodeOptions
type CreateNodeOptions = { /** * During node construction, use anchors and aliases to keep strictly equal * non-null objects as equivalent in YAML. * * Default: `true` */ aliasDuplicateObjects?: boolean; /** * Default prefix for anchors. * * Default: `'a'`, resulting in anchors `a1`, `a2`, etc. */ anchorPrefix?: string; /** Force the top-level collection node to use flow style. */ flow?: boolean; /** * Keep `undefined` object values when creating mappings, rather than * discarding them. * * Default: `false` */ keepUndefined?: boolean | null; onTagObj?: (tagObj: ScalarTag | CollectionTag) => void; /** * Specify the top-level collection type, e.g. `"!!omap"`. Note that this * requires the corresponding tag to be available in this document's schema. */ tag?: string;};
type DocumentOptions
type DocumentOptions = { /** * @internal * Used internally by Composer. If set and includes an explicit version, * that overrides the `version` option. */ _directives?: Directives; /** * Control the logging level during parsing * * Default: `'warn'` */ logLevel?: LogLevelId; /** * The YAML version used by documents without a `%YAML` directive. * * Default: `"1.2"` */ version?: '1.1' | '1.2' | 'next';};
type ErrorCode
type ErrorCode = | 'ALIAS_PROPS' | 'BAD_ALIAS' | 'BAD_DIRECTIVE' | 'BAD_DQ_ESCAPE' | 'BAD_INDENT' | 'BAD_PROP_ORDER' | 'BAD_SCALAR_START' | 'BLOCK_AS_IMPLICIT_KEY' | 'BLOCK_IN_FLOW' | 'DUPLICATE_KEY' | 'IMPOSSIBLE' | 'KEY_OVER_1024_CHARS' | 'MISSING_CHAR' | 'MULTILINE_IMPLICIT_KEY' | 'MULTIPLE_ANCHORS' | 'MULTIPLE_DOCS' | 'MULTIPLE_TAGS' | 'TAB_AS_INDENT' | 'TAG_RESOLVE_FAILED' | 'UNEXPECTED_TOKEN' | 'BAD_COLLECTION_TYPE';
type Node
type Node<T = unknown> = Alias | Scalar<T> | YAMLMap<unknown, T> | YAMLSeq<T>;
type ParsedNode
type ParsedNode = Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed;
type ParseOptions
type ParseOptions = { /** * Whether integers should be parsed into BigInt rather than number values. * * Default: `false` * * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/BigInt */ intAsBigInt?: boolean; /** * Include a `srcToken` value on each parsed `Node`, containing the CST token * that was composed into this node. * * Default: `false` */ keepSourceTokens?: boolean; /** * If set, newlines will be tracked, to allow for `lineCounter.linePos(offset)` * to provide the `{ line, col }` positions within the input. */ lineCounter?: LineCounter; /** * Include line/col position & node type directly in parse errors. * * Default: `true` */ prettyErrors?: boolean; /** * Detect and report errors that are required by the YAML 1.2 spec, * but are caused by unambiguous content. * * Default: `true` */ strict?: boolean; /** * YAML requires map keys to be unique. By default, this is checked by * comparing scalar values with `===`; deep equality is not checked for * aliases or collections. If merge keys are enabled by the schema, * multiple `<<` keys are allowed. * * Set `false` to disable, or provide your own comparator function to * customise. The comparator will be passed two `ParsedNode` values, and * is expected to return a `boolean` indicating their equality. * * Default: `true` */ uniqueKeys?: boolean | ((a: ParsedNode, b: ParsedNode) => boolean);};
type Range
type Range = [number, number, number];
type SchemaOptions
type SchemaOptions = { /** * When parsing, warn about compatibility issues with the given schema. * When stringifying, use scalar styles that are parsed correctly * by the `compat` schema as well as the actual schema. * * Default: `null` */ compat?: string | Tags | null; /** * Array of additional tags to include in the schema, or a function that may * modify the schema's base tag array. */ customTags?: Tags | ((tags: Tags) => Tags) | null; /** * Enable support for `<<` merge keys. * * Default: `false` for YAML 1.2, `true` for earlier versions */ merge?: boolean; /** * When using the `'core'` schema, support parsing values with these * explicit YAML 1.1 tags: * * `!!binary`, `!!omap`, `!!pairs`, `!!set`, `!!timestamp`. * * Default `true` */ resolveKnownTags?: boolean; /** * The base schema to use. * * The core library has built-in support for the following: * - `'failsafe'`: A minimal schema that parses all scalars as strings * - `'core'`: The YAML 1.2 core schema * - `'json'`: The YAML 1.2 JSON schema, with minimal rules for JSON compatibility * - `'yaml-1.1'`: The YAML 1.1 schema * * If using another (custom) schema, the `customTags` array needs to * fully define the schema's tags. * * Default: `'core'` for YAML 1.2, `'yaml-1.1'` for earlier versions */ schema?: string | Schema; /** * When adding to or stringifying a map, sort the entries. * If `true`, sort by comparing key values with `<`. * Does not affect item order when parsing. * * Default: `false` */ sortMapEntries?: boolean | ((a: Pair, b: Pair) => number); /** * Override default values for `toString()` options. */ toStringDefaults?: ToStringOptions;};
type TagId
type TagId = keyof typeof tagsByName;
type Tags
type Tags = Array<ScalarTag | CollectionTag | TagId>;
type ToJSOptions
type ToJSOptions = { /** * Use Map rather than Object to represent mappings. * * Default: `false` */ mapAsMap?: boolean; /** * Prevent exponential entity expansion attacks by limiting data aliasing count; * set to `-1` to disable checks; `0` disallows all alias nodes. * * Default: `100` */ maxAliasCount?: number; /** * If defined, called with the resolved `value` and reference `count` for * each anchor in the document. */ onAnchor?: (value: unknown, count: number) => void; /** * Optional function that may filter or modify the output JS value * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#using_the_reviver_parameter */ reviver?: Reviver;};
type ToStringOptions
type ToStringOptions = { /** * Use block quote styles for scalar values where applicable. * Set to `false` to disable block quotes completely. * * Default: `true` */ blockQuote?: boolean | 'folded' | 'literal'; /** * Enforce `'block'` or `'flow'` style on maps and sequences. * Empty collections will always be stringified as `{}` or `[]`. * * Default: `'any'`, allowing each node to set its style separately * with its `flow: boolean` (default `false`) property. */ collectionStyle?: 'any' | 'block' | 'flow'; /** * Comment stringifier. * Output should be valid for the current schema. * * By default, empty comment lines are left empty, * lines consisting of a single space are replaced by `#`, * and all other lines are prefixed with a `#`. */ commentString?: (comment: string) => string; /** * The default type of string literal used to stringify implicit key values. * Output may use other types if required to fully represent the value. * * If `null`, the value of `defaultStringType` is used. * * Default: `null` */ defaultKeyType?: Scalar.Type | null; /** * The default type of string literal used to stringify values in general. * Output may use other types if required to fully represent the value. * * Default: `'PLAIN'` */ defaultStringType?: Scalar.Type; /** * Include directives in the output. * * - If `true`, at least the document-start marker `---` is always included. * This does not force the `%YAML` directive to be included. To do that, * set `doc.directives.yaml.explicit = true`. * - If `false`, no directives or marker is ever included. If using the `%TAG` * directive, you are expected to include it manually in the stream before * its use. * - If `null`, directives and marker may be included if required. * * Default: `null` */ directives?: boolean | null; /** * Restrict double-quoted strings to use JSON-compatible syntax. * * Default: `false` */ doubleQuotedAsJSON?: boolean; /** * Minimum length for double-quoted strings to use multiple lines to * represent the value. Ignored if `doubleQuotedAsJSON` is set. * * Default: `40` */ doubleQuotedMinMultiLineLength?: number; /** * String representation for `false`. * With the core schema, use `'false'`, `'False'`, or `'FALSE'`. * * Default: `'false'` */ falseStr?: string; /** * When true, a single space of padding will be added inside the delimiters * of non-empty single-line flow collections. * * Default: `true` */ flowCollectionPadding?: boolean; /** * The number of spaces to use when indenting code. * * Default: `2` */ indent?: number; /** * Whether block sequences should be indented. * * Default: `true` */ indentSeq?: boolean; /** * Maximum line width (set to `0` to disable folding). * * This is a soft limit, as only double-quoted semantics allow for inserting * a line break in the middle of a word, as well as being influenced by the * `minContentWidth` option. * * Default: `80` */ lineWidth?: number; /** * Minimum line width for highly-indented content (set to `0` to disable). * * Default: `20` */ minContentWidth?: number; /** * String representation for `null`. * With the core schema, use `'null'`, `'Null'`, `'NULL'`, `'~'`, or an empty * string `''`. * * Default: `'null'` */ nullStr?: string; /** * Require keys to be scalars and to use implicit rather than explicit notation. * * Default: `false` */ simpleKeys?: boolean; /** * Use 'single quote' rather than "double quote" where applicable. * Set to `false` to disable single quotes completely. * * Default: `null` */ singleQuote?: boolean | null; /** * String representation for `true`. * With the core schema, use `'true'`, `'True'`, or `'TRUE'`. * * Default: `'true'` */ trueStr?: string; /** * The anchor used by an alias must be defined before the alias node. As it's * possible for the document to be modified manually, the order may be * verified during stringification. * * Default: `'true'` */ verifyAliasOrder?: boolean;};
type visitor
type visitor = | visitorFn<unknown> | { Alias?: visitorFn<Alias>; Collection?: visitorFn<YAMLMap | YAMLSeq>; Map?: visitorFn<YAMLMap>; Node?: visitorFn<Alias | Scalar | YAMLMap | YAMLSeq>; Pair?: visitorFn<Pair>; Scalar?: visitorFn<Scalar>; Seq?: visitorFn<YAMLSeq>; Value?: visitorFn<Scalar | YAMLMap | YAMLSeq>; };
type visitorFn
type visitorFn<T> = ( key: number | 'key' | 'value' | null, node: T, path: readonly (Document | Node | Pair)[]) => void | symbol | number | Node | Pair;
Namespaces
namespace Alias
namespace Alias {}
namespace CST
module 'dist/parse/cst.d.ts' {}
The byte order mark
variable BOM
const BOM: string;
The byte order mark
variable DOCUMENT
const DOCUMENT: string;
Start of doc-mode
variable FLOW_END
const FLOW_END: string;
Unexpected end of flow-mode
variable SCALAR
const SCALAR: string;
Next token is a scalar value
function createScalarToken
createScalarToken: ( value: string, context: { end?: SourceToken[]; implicitKey?: boolean; indent: number; inFlow?: boolean; offset?: number; type?: Scalar.Type; }) => BlockScalar | FlowScalar;
Create a new scalar token with
value
Values that represent an actual string but may be parsed as a different type should use a
type
other than'PLAIN'
, as this function does not support any schema operations and won't check for such conflicts.Parameter value
The string representation of the value, which will have its content properly indented.
Parameter
context.end Comments and whitespace after the end of the value, or after the block scalar header. If undefined, a newline will be added.
Parameter
context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
Parameter
context.indent The indent level of the token.
Parameter
context.inFlow Is this scalar within a flow collection? This may affect the resolved type of the token's value.
Parameter
context.offset The offset position of the token.
Parameter
context.type The preferred type of the scalar token. If undefined, the previous type of the
token
will be used, defaulting to'PLAIN'
.
function isCollection
isCollection: ( token: Token | null | undefined) => token is BlockMap | BlockSequence | FlowCollection;
Returns
true
iftoken
is a flow or block collection
function isScalar
isScalar: (token: Token | null | undefined) => token is FlowScalar | BlockScalar;
Returns
true
iftoken
is a flow or block scalar; not an alias
function prettyToken
prettyToken: (token: string) => string;
Get a printable representation of a lexer token
function resolveAsScalar
resolveAsScalar: { ( token: FlowScalar | BlockScalar, strict?: boolean, onError?: (offset: number, code: ErrorCode, message: string) => void ): { value: string; type: Scalar.Type | null; comment: string; range: Range }; ( token: Token, strict?: boolean, onError?: (offset: number, code: ErrorCode, message: string) => void ): { value: string; type: Scalar.Type; comment: string; range: Range };};
If
token
is a CST flow or block scalar, determine its string value and a few other attributes. Otherwise, returnnull
.
function setScalarValue
setScalarValue: ( token: Token, value: string, context?: { afterKey?: boolean; implicitKey?: boolean; inFlow?: boolean; type?: Scalar.Type; }) => void;
Set the value of
token
to the given stringvalue
, overwriting any previous contents and type that it may have.Best efforts are made to retain any comments previously associated with the
token
, though all contents within a collection'sitems
will be overwritten.Values that represent an actual string but may be parsed as a different type should use a
type
other than'PLAIN'
, as this function does not support any schema operations and won't check for such conflicts.Parameter token
Any token. If it does not include an
indent
value, the value will be stringified as if it were an implicit key.Parameter value
The string representation of the value, which will have its content properly indented.
Parameter
context.afterKey In most cases, values after a key should have an additional level of indentation.
Parameter
context.implicitKey Being within an implicit key may affect the resolved type of the token's value.
Parameter
context.inFlow Being within a flow collection may affect the resolved type of the token's value.
Parameter
context.type The preferred type of the scalar token. If undefined, the previous type of the
token
will be used, defaulting to'PLAIN'
.
function stringify
stringify: (cst: Token | CollectionItem) => string;
Stringify a CST document, token, or collection item
Fair warning: This applies no validation whatsoever, and simply concatenates the sources in their logical order.
function tokenType
tokenType: (source: string) => TokenType | null;
Identify the type of a lexer token. May return
null
for unknown tokens.
function visit
visit: typeof visit;
Apply a visitor to a CST document or item.
Walks through the tree (depth-first) starting from the root, calling a
visitor
function with two arguments when entering each item: -item
: The current item, which included the following members: -start: SourceToken[]
– Source tokens before the key or value, possibly including its anchor or tag. -key?: Token | null
– Set for pair values. May then benull
, if the key before the:
separator is empty. -sep?: SourceToken[]
– Source tokens between the key and the value, which should include the:
map value indicator ifvalue
is set. -value?: Token
– The value of a sequence item, or of a map pair. -path
: The steps from the root to the current node, as an array of['key' | 'value', number]
tuples.The return value of the visitor may be used to control the traversal: -
undefined
(default): Do nothing and continue -visit.SKIP
: Do not visit the children of this token, continue with next sibling -visit.BREAK
: Terminate traversal completely -visit.REMOVE
: Remove the current item, then continue with the next one -number
: Set the index of the next step. This is useful especially if the index of the current token has changed. -function
: Define the next visitor for this item. After the original visitor is called on item entry, next visitors are called after handling a non-emptykey
and when exiting the item.
interface BlockMap
interface BlockMap {}
property indent
indent: number;
property items
items: Array< | { start: SourceToken[]; explicitKey?: true; key?: never; sep?: never; value?: never; } | { start: SourceToken[]; explicitKey?: true; key: Token | null; sep: SourceToken[]; value?: Token; }>;
property offset
offset: number;
property type
type: 'block-map';
interface BlockScalar
interface BlockScalar {}
interface BlockSequence
interface BlockSequence {}
interface Directive
interface Directive {}
interface Document
interface Document {}
interface DocumentEnd
interface DocumentEnd {}
interface ErrorToken
interface ErrorToken {}
interface FlowCollection
interface FlowCollection {}
interface FlowScalar
interface FlowScalar {}
interface SourceToken
interface SourceToken {}
property indent
indent: number;
property offset
offset: number;
property source
source: string;
property type
type: | 'byte-order-mark' | 'doc-mode' | 'doc-start' | 'space' | 'comment' | 'newline' | 'directive-line' | 'anchor' | 'tag' | 'seq-item-ind' | 'explicit-key-ind' | 'map-value-ind' | 'flow-map-start' | 'flow-map-end' | 'flow-seq-start' | 'flow-seq-end' | 'flow-error-end' | 'comma' | 'block-scalar-header';
type CollectionItem
type CollectionItem = { start: SourceToken[]; key?: Token | null; sep?: SourceToken[]; value?: Token;};
type Token
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection;
type TokenType
type TokenType = SourceToken['type'] | DocumentEnd['type'] | FlowScalar['type'];
type Visitor
type Visitor = ( item: CollectionItem, path: VisitPath) => number | symbol | Visitor | void;
type VisitPath
type VisitPath = readonly ['key' | 'value', number][];
namespace CST.visit
namespace CST.visit {}
variable BREAK
var BREAK: Symbol;
variable REMOVE
var REMOVE: Symbol;
variable SKIP
var SKIP: Symbol;
function itemAtPath
itemAtPath: ( cst: Document | CollectionItem, path: VisitPath) => CollectionItem | undefined;
function parentCollection
parentCollection: ( cst: Document | CollectionItem, path: VisitPath) => | import('./cst.js').BlockMap | import('./cst.js').BlockSequence | import('./cst.js').FlowCollection;
namespace Document
namespace Document {}
interface Parsed
interface Parsed< Contents extends ParsedNode = ParsedNode, Strict extends boolean = true> extends Document<Contents, Strict> {}
@ts-ignore The typing of directives fails in TS <= 4.2
property directives
directives: Directives;
property range
range: Range;
namespace Scalar
namespace Scalar {}
interface Parsed
interface Parsed extends Scalar {}
type BLOCK_FOLDED
type BLOCK_FOLDED = 'BLOCK_FOLDED';
type BLOCK_LITERAL
type BLOCK_LITERAL = 'BLOCK_LITERAL';
type PLAIN
type PLAIN = 'PLAIN';
type QUOTE_DOUBLE
type QUOTE_DOUBLE = 'QUOTE_DOUBLE';
type QUOTE_SINGLE
type QUOTE_SINGLE = 'QUOTE_SINGLE';
type Type
type Type = BLOCK_FOLDED | BLOCK_LITERAL | PLAIN | QUOTE_DOUBLE | QUOTE_SINGLE;
namespace visit
namespace visit {}
namespace visitAsync
namespace visitAsync {}
namespace YAMLMap
namespace YAMLMap {}
Package Files (26)
- dist/compose/composer.d.ts
- dist/doc/Document.d.ts
- dist/errors.d.ts
- dist/index.d.ts
- dist/nodes/Alias.d.ts
- dist/nodes/Node.d.ts
- dist/nodes/Pair.d.ts
- dist/nodes/Scalar.d.ts
- dist/nodes/YAMLMap.d.ts
- dist/nodes/YAMLSeq.d.ts
- dist/nodes/identity.d.ts
- dist/options.d.ts
- dist/parse/cst-scalar.d.ts
- dist/parse/cst-stringify.d.ts
- dist/parse/cst-visit.d.ts
- dist/parse/cst.d.ts
- dist/parse/lexer.d.ts
- dist/parse/line-counter.d.ts
- dist/parse/parser.d.ts
- dist/public-api.d.ts
- dist/schema/Schema.d.ts
- dist/schema/tags.d.ts
- dist/schema/types.d.ts
- dist/schema/yaml-1.1/omap.d.ts
- dist/schema/yaml-1.1/set.d.ts
- dist/visit.d.ts
Dependencies (0)
No dependencies.
Dev Dependencies (23)
- @babel/core
- @babel/plugin-transform-class-properties
- @babel/plugin-transform-nullish-coalescing-operator
- @babel/plugin-transform-typescript
- @babel/preset-env
- @rollup/plugin-babel
- @rollup/plugin-replace
- @rollup/plugin-typescript
- @types/jest
- @types/node
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- babel-jest
- cross-env
- eslint
- eslint-config-prettier
- fast-check
- jest
- jest-ts-webcompat-resolver
- prettier
- rollup
- tslib
- typescript
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/yaml
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/yaml)
- HTML<a href="https://www.jsdocs.io/package/yaml"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5397 ms. - Missing or incorrect documentation? Open an issue for this package.