id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
0
function combineFuncs(a: TestType, b: TestType): TestType { return (elem: AnyNode) => a(elem) || b(elem); }
type TestType = (elem: AnyNode) => boolean;
1
function compileTest(options: TestElementOpts): TestType | null { const funcs = Object.keys(options).map((key) => { const value = options[key]; return Object.prototype.hasOwnProperty.call(Checks, key) ? Checks[key](value) : getAttribCheck(key, value); }); return funcs.length === 0 ? null : funcs.reduce(combineFuncs); }
interface TestElementOpts { tag_name?: string | ((name: string) => boolean); tag_type?: string | ((name: string) => boolean); tag_contains?: string | ((data?: string) => boolean); [attributeName: string]: | undefined | string | ((attributeValue: string) => boolean); }
2
function testElement(options: TestElementOpts, node: AnyNode): boolean { const test = compileTest(options); return test ? test(node) : true; }
interface TestElementOpts { tag_name?: string | ((name: string) => boolean); tag_type?: string | ((name: string) => boolean); tag_contains?: string | ((data?: string) => boolean); [attributeName: string]: | undefined | string | ((attributeValue: string) => boolean); }
3
function getElements( options: TestElementOpts, nodes: AnyNode | AnyNode[], recurse: boolean, limit = Infinity ): AnyNode[] { const test = compileTest(options); return test ? filter(test, nodes, recurse, limit) : []; }
interface TestElementOpts { tag_name?: string | ((name: string) => boolean); tag_type?: string | ((name: string) => boolean); tag_contains?: string | ((data?: string) => boolean); [attributeName: string]: | undefined | string | ((attributeValue: string) => boolean); }
4
function anchorExists(doc: Document, anchor: string): boolean { let found = false visit(doc, { Value(_key: unknown, node: Node) { if (node.anchor === anchor) { found = true return visit.BREAK } } }) return found }
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
5
function anchorExists(doc: Document, anchor: string): boolean { let found = false visit(doc, { Value(_key: unknown, node: Node) { if (node.anchor === anchor) { found = true return visit.BREAK } } }) return found }
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directives /** Errors encountered during parsing. */ errors: YAMLError[] = [] options: Required< Omit< ParseOptions & DocumentOptions, '_directives' | 'lineCounter' | 'version' > > /** * The `[start, value-end, node-end]` character offsets for the part of the * source parsed into this document (undefined if not parsed). The `value-end` * and `node-end` positions are themselves not included in their respective * ranges. */ declare range?: Range // TS can't figure out that setSchema() will set this, or throw /** The schema used with the document. Use `setSchema()` to change. */ declare schema: Schema /** Warnings encountered during parsing. */ warnings: YAMLWarning[] = [] /** * @param value - The initial value for the document, which will be wrapped * in a Node container. */ constructor( value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value: any, replacer: null | Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value?: unknown, replacer?: | Replacer | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions) | null, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) { Object.defineProperty(this, NODE_TYPE, { value: DOC }) let _replacer: Replacer | null = null if (typeof replacer === 'function' || Array.isArray(replacer)) { _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const opt = Object.assign( { intAsBigInt: false, keepSourceTokens: false, logLevel: 'warn', prettyErrors: true, strict: true, uniqueKeys: true, version: '1.2' }, options ) this.options = opt let { version } = opt if (options?._directives) { this.directives = options._directives.atDocument() if (this.directives.yaml.explicit) version = this.directives.yaml.version } else this.directives = new Directives({ version }) this.setSchema(version, options) if (value === undefined) this.contents = null else { this.contents = this.createNode(value, _replacer, options) as unknown as T } } /** * Create a deep copy of this Document and its contents. * * Custom Node values that inherit from `Object` still refer to their original instances. */ clone(): Document<T> { const copy: Document<T> = Object.create(Document.prototype, { [NODE_TYPE]: { value: DOC } }) copy.commentBefore = this.commentBefore copy.comment = this.comment copy.errors = this.errors.slice() copy.warnings = this.warnings.slice() copy.options = Object.assign({}, this.options) if (this.directives) copy.directives = this.directives.clone() copy.schema = this.schema.clone() copy.contents = isNode(this.contents) ? (this.contents.clone(copy.schema) as unknown as T) : this.contents if (this.range) copy.range = this.range.slice() as Document['range'] return copy } /** Adds a value to the document. */ add(value: any) { if (assertCollection(this.contents)) this.contents.add(value) } /** Adds a value to the document. */ addIn(path: Iterable<unknown>, value: unknown) { if (assertCollection(this.contents)) this.contents.addIn(path, value) } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. * * If `node` already has an anchor, `name` is ignored. * Otherwise, the `node.anchor` value will be set to `name`, * 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. * If `name` is undefined, the generated anchor will use 'a' as a prefix. */ createAlias(node: Scalar | YAMLMap | YAMLSeq, name?: string): Alias { if (!node.anchor) { const prev = anchorNames(this) node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name } return new Alias(node.anchor) } /** * Convert any value into a `Node` using the current schema, recursively * turning objects into collections. */ createNode<T = unknown>(value: T, options?: CreateNodeOptions): NodeType<T> createNode<T = unknown>( value: T, replacer: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): NodeType<T> createNode( value: unknown, replacer?: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): Node { let _replacer: Replacer | undefined = undefined if (typeof replacer === 'function') { value = replacer.call({ '': value }, '', value) _replacer = replacer } else if (Array.isArray(replacer)) { const keyToStr = (v: unknown) => typeof v === 'number' || v instanceof String || v instanceof Number const asStr = replacer.filter(keyToStr).map(String) if (asStr.length > 0) replacer = replacer.concat(asStr) _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {} const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( this, // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing anchorPrefix || 'a' ) const ctx: CreateNodeContext = { aliasDuplicateObjects: aliasDuplicateObjects ?? true, keepUndefined: keepUndefined ?? false, onAnchor, onTagObj, replacer: _replacer, schema: this.schema, sourceObjects } const node = createNode(value, tag, ctx) if (flow && isCollection(node)) node.flow = true setAnchors() return node } /** * Convert a key and a value into a `Pair` using the current schema, * recursively wrapping all values as `Scalar` or `Collection` nodes. */ createPair<K extends Node = Node, V extends Node = Node>( key: unknown, value: unknown, options: CreateNodeOptions = {} ) { const k = this.createNode(key, null, options) as K const v = this.createNode(value, null, options) as V return new Pair(k, v) } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ delete(key: unknown): boolean { return assertCollection(this.contents) ? this.contents.delete(key) : false } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ deleteIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) { if (this.contents == null) return false this.contents = null return true } return assertCollection(this.contents) ? this.contents.deleteIn(path) : false } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ get(key: unknown, keepScalar?: boolean): unknown { return isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined } /** * Returns item at `path`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path: Iterable<unknown> | null, keepScalar?: boolean): unknown { if (isEmptyPath(path)) return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : undefined } /** * Checks if the document includes a value with the key `key`. */ has(key: unknown): boolean { return isCollection(this.contents) ? this.contents.has(key) : false } /** * Checks if the document includes a value at `path`. */ hasIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) return this.contents !== undefined return isCollection(this.contents) ? this.contents.hasIn(path) : false } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ set(key: any, value: unknown): void { if (this.contents == null) { this.contents = collectionFromPath( this.schema, [key], value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.set(key, value) } } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path: Iterable<unknown> | null, value: unknown): void { if (isEmptyPath(path)) this.contents = value as T else if (this.contents == null) { this.contents = collectionFromPath( this.schema, Array.from(path), value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.setIn(path, value) } } /** * 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 the `schema` option to be given as a `Schema` instance value. * * Overrides all previously set schema options. */ setSchema( version: '1.1' | '1.2' | 'next' | null, options: SchemaOptions = {} ) { if (typeof version === 'number') version = String(version) as '1.1' | '1.2' let opt: (SchemaOptions & { schema: string }) | null switch (version) { case '1.1': if (this.directives) this.directives.yaml.version = '1.1' else this.directives = new Directives({ version: '1.1' }) opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' } break case '1.2': case 'next': if (this.directives) this.directives.yaml.version = version else this.directives = new Directives({ version }) opt = { merge: false, resolveKnownTags: true, schema: 'core' } break case null: if (this.directives) delete this.directives opt = null break default: { const sv = JSON.stringify(version) throw new Error( `Expected '1.1', '1.2' or null as first argument, but found: ${sv}` ) } } // Not using `instanceof Schema` to allow for duck typing if (options.schema instanceof Object) this.schema = options.schema else if (opt) this.schema = new Schema(Object.assign(opt, options)) else throw new Error( `With a null YAML version, the { schema: Schema } option is required` ) } /** A plain JavaScript representation of the document `contents`. */ toJS(opt?: ToJSOptions & { [ignored: string]: unknown }): any // json & jsonArg are only used from toJSON() toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver }: ToJSOptions & { json?: boolean; jsonArg?: string | null } = {}): any { const ctx: ToJSContext = { anchors: new Map(), doc: this, keep: !json, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100, stringify } const res = toJS(this.contents, jsonArg ?? '', ctx) if (typeof onAnchor === 'function') for (const { count, res } of ctx.anchors.values()) onAnchor(res, count) return typeof reviver === 'function' ? applyReviver(reviver, { '': res }, '', res) : res } /** * A JSON representation of the document `contents`. * * @param jsonArg Used by `JSON.stringify` to indicate the array index or * property name. */ toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any { return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }) } /** A YAML representation of the document. */ toString(options: ToStringOptions = {}): string { if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified') if ( 'indent' in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0) ) { const s = JSON.stringify(options.indent) throw new Error(`"indent" option must be a positive integer, not ${s}`) } return stringifyDocument(this, options) } }
6
(error: YAMLError) => { if (error.pos[0] === -1) return error.linePos = error.pos.map(pos => lc.linePos(pos)) as | [LinePos] | [LinePos, LinePos] const { line, col } = error.linePos[0] error.message += ` at line ${line}, column ${col}` let ci = col - 1 let lineStr = src .substring(lc.lineStarts[line - 1], lc.lineStarts[line]) .replace(/[\n\r]+$/, '') // Trim to max 80 chars, keeping col position near the middle if (ci >= 60 && lineStr.length > 80) { const trimStart = Math.min(ci - 39, lineStr.length - 79) lineStr = '…' + lineStr.substring(trimStart) ci -= trimStart - 1 } if (lineStr.length > 80) lineStr = lineStr.substring(0, 79) + '…' // Include previous line in context if pointing at line start if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) { // Regexp won't match if start is trimmed let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]) if (prev.length > 80) prev = prev.substring(0, 79) + '…\n' lineStr = prev + lineStr } if (/[^ ]/.test(lineStr)) { let count = 1 const end = error.linePos[1] if (end && end.line === line && end.col > col) { count = Math.min(end.col - col, 80 - ci) } const pointer = ' '.repeat(ci) + '^'.repeat(count) error.message += `:\n\n${lineStr}\n${pointer}\n` } }
class YAMLError extends Error { name: 'YAMLParseError' | 'YAMLWarning' code: ErrorCode message: string pos: [number, number] linePos?: [LinePos] | [LinePos, LinePos] constructor( name: YAMLError['name'], pos: [number, number], code: ErrorCode, message: string ) { super() this.name = name this.code = code this.message = message this.pos = pos } }
7
function parseOptions(options: ParseOptions) { const prettyErrors = options.prettyErrors !== false const lineCounter = options.lineCounter || (prettyErrors && new LineCounter()) || null return { lineCounter, prettyErrors } }
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) }
8
function debug(logLevel: LogLevelId, ...messages: any[]) { if (logLevel === 'debug') console.log(...messages) }
type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'
9
function warn(logLevel: LogLevelId, warning: string | Error) { if (logLevel === 'debug' || logLevel === 'warn') { if (typeof process !== 'undefined' && process.emitWarning) process.emitWarning(warning) else console.warn(warning) } }
type LogLevelId = 'silent' | 'error' | 'warn' | 'debug'
10
(a: ParsedNode, b: ParsedNode) => boolean
type ParsedNode = | Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed
11
(tags: Tags) => Tags
type Tags = Array<ScalarTag | CollectionTag | TagId>
12
(a: Pair, b: Pair) => number
class Pair<K = unknown, V = unknown> { declare readonly [NODE_TYPE]: symbol /** Always Node or null when parsed, but can be set to anything. */ key: K /** Always Node or null when parsed, but can be set to anything. */ value: V | null /** The CST token that was composed into this pair. */ declare srcToken?: CollectionItem constructor(key: K, value: V | null = null) { Object.defineProperty(this, NODE_TYPE, { value: PAIR }) this.key = key this.value = value } clone(schema?: Schema): Pair<K, V> { let { key, value } = this if (isNode(key)) key = key.clone(schema) as unknown as K if (isNode(value)) value = value.clone(schema) as unknown as V return new Pair(key, value) } toJSON(_?: unknown, ctx?: ToJSContext): ReturnType<typeof addPairToJSMap> { const pair = ctx?.mapAsMap ? new Map() : {} return addPairToJSMap(ctx, pair, this) } toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string { return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this) } }
13
function stringifyToken(token: Token) { switch (token.type) { case 'block-scalar': { let res = '' for (const tok of token.props) res += stringifyToken(tok) return res + token.source } case 'block-map': case 'block-seq': { let res = '' for (const item of token.items) res += stringifyItem(item) return res } case 'flow-collection': { let res = token.start.source for (const item of token.items) res += stringifyItem(item) for (const st of token.end) res += st.source return res } case 'document': { let res = stringifyItem(token) if (token.end) for (const st of token.end) res += st.source return res } default: { let res = token.source if ('end' in token && token.end) for (const st of token.end) res += st.source return res } } }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
14
function stringifyItem({ start, key, sep, value }: CollectionItem) { let res = '' for (const st of start) res += st.source if (key) res += stringifyToken(key) if (sep) for (const st of sep) res += st.source if (value) res += stringifyToken(value) return res }
type CollectionItem = { start: SourceToken[] key?: Token | null sep?: SourceToken[] value?: Token }
15
function getPrevProps(parent: Token) { switch (parent.type) { case 'document': return parent.start case 'block-map': { const it = parent.items[parent.items.length - 1] return it.sep ?? it.start } case 'block-seq': return parent.items[parent.items.length - 1].start /* istanbul ignore next should not happen */ default: return [] } }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
16
function fixFlowSeqItems(fc: FlowCollection) { if (fc.start.type === 'flow-seq-start') { for (const it of fc.items) { if ( it.sep && !it.value && !includesToken(it.start, 'explicit-key-ind') && !includesToken(it.sep, 'map-value-ind') ) { if (it.key) it.value = it.key delete it.key if (isFlowToken(it.value)) { if (it.value.end) Array.prototype.push.apply(it.value.end, it.sep) else it.value.end = it.sep } else Array.prototype.push.apply(it.start, it.sep) delete it.sep } } } }
interface FlowCollection { type: 'flow-collection' offset: number indent: number start: SourceToken items: CollectionItem[] end: SourceToken[] }
17
private *pop(error?: Token): Generator<Token, void> { const token = error ?? this.stack.pop() /* istanbul ignore if should not happen */ if (!token) { const message = 'Tried to pop an empty stack' yield { type: 'error', offset: this.offset, source: '', message } } else if (this.stack.length === 0) { yield token } else { const top = this.peek(1) if (token.type === 'block-scalar') { // Block scalars use their parent rather than header indent token.indent = 'indent' in top ? top.indent : 0 } else if (token.type === 'flow-collection' && top.type === 'document') { // Ignore all indent for top-level flow collections token.indent = 0 } if (token.type === 'flow-collection') fixFlowSeqItems(token) switch (top.type) { case 'document': top.value = token break case 'block-scalar': top.props.push(token) // error break case 'block-map': { const it = top.items[top.items.length - 1] if (it.value) { top.items.push({ start: [], key: token, sep: [] }) this.onKeyLine = true return } else if (it.sep) { it.value = token } else { Object.assign(it, { key: token, sep: [] }) this.onKeyLine = !includesToken(it.start, 'explicit-key-ind') return } break } case 'block-seq': { const it = top.items[top.items.length - 1] if (it.value) top.items.push({ start: [], value: token }) else it.value = token break } case 'flow-collection': { const it = top.items[top.items.length - 1] if (!it || it.value) top.items.push({ start: [], key: token, sep: [] }) else if (it.sep) it.value = token else Object.assign(it, { key: token, sep: [] }) return } /* istanbul ignore next should not happen */ default: yield* this.pop() yield* this.pop(token) } if ( (top.type === 'document' || top.type === 'block-map' || top.type === 'block-seq') && (token.type === 'block-map' || token.type === 'block-seq') ) { const last = token.items[token.items.length - 1] if ( last && !last.sep && !last.value && last.start.length > 0 && findNonEmptyIndex(last.start) === -1 && (token.indent === 0 || last.start.every( st => st.type !== 'comment' || st.indent < token.indent )) ) { if (top.type === 'document') top.end = last.start else top.items.push({ start: last.start }) token.items.splice(-1, 1) } } } }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
18
private *document(doc: Document): Generator<Token, void> { if (doc.value) return yield* this.lineEnd(doc) switch (this.type) { case 'doc-start': { if (findNonEmptyIndex(doc.start) !== -1) { yield* this.pop() yield* this.step() } else doc.start.push(this.sourceToken) return } case 'anchor': case 'tag': case 'space': case 'comment': case 'newline': doc.start.push(this.sourceToken) return } const bv = this.startBlockValue(doc) if (bv) this.stack.push(bv) else { yield { type: 'error', offset: this.offset, message: `Unexpected ${this.type} token in YAML document`, source: this.source } } }
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
19
private *document(doc: Document): Generator<Token, void> { if (doc.value) return yield* this.lineEnd(doc) switch (this.type) { case 'doc-start': { if (findNonEmptyIndex(doc.start) !== -1) { yield* this.pop() yield* this.step() } else doc.start.push(this.sourceToken) return } case 'anchor': case 'tag': case 'space': case 'comment': case 'newline': doc.start.push(this.sourceToken) return } const bv = this.startBlockValue(doc) if (bv) this.stack.push(bv) else { yield { type: 'error', offset: this.offset, message: `Unexpected ${this.type} token in YAML document`, source: this.source } } }
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directives /** Errors encountered during parsing. */ errors: YAMLError[] = [] options: Required< Omit< ParseOptions & DocumentOptions, '_directives' | 'lineCounter' | 'version' > > /** * The `[start, value-end, node-end]` character offsets for the part of the * source parsed into this document (undefined if not parsed). The `value-end` * and `node-end` positions are themselves not included in their respective * ranges. */ declare range?: Range // TS can't figure out that setSchema() will set this, or throw /** The schema used with the document. Use `setSchema()` to change. */ declare schema: Schema /** Warnings encountered during parsing. */ warnings: YAMLWarning[] = [] /** * @param value - The initial value for the document, which will be wrapped * in a Node container. */ constructor( value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value: any, replacer: null | Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value?: unknown, replacer?: | Replacer | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions) | null, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) { Object.defineProperty(this, NODE_TYPE, { value: DOC }) let _replacer: Replacer | null = null if (typeof replacer === 'function' || Array.isArray(replacer)) { _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const opt = Object.assign( { intAsBigInt: false, keepSourceTokens: false, logLevel: 'warn', prettyErrors: true, strict: true, uniqueKeys: true, version: '1.2' }, options ) this.options = opt let { version } = opt if (options?._directives) { this.directives = options._directives.atDocument() if (this.directives.yaml.explicit) version = this.directives.yaml.version } else this.directives = new Directives({ version }) this.setSchema(version, options) if (value === undefined) this.contents = null else { this.contents = this.createNode(value, _replacer, options) as unknown as T } } /** * Create a deep copy of this Document and its contents. * * Custom Node values that inherit from `Object` still refer to their original instances. */ clone(): Document<T> { const copy: Document<T> = Object.create(Document.prototype, { [NODE_TYPE]: { value: DOC } }) copy.commentBefore = this.commentBefore copy.comment = this.comment copy.errors = this.errors.slice() copy.warnings = this.warnings.slice() copy.options = Object.assign({}, this.options) if (this.directives) copy.directives = this.directives.clone() copy.schema = this.schema.clone() copy.contents = isNode(this.contents) ? (this.contents.clone(copy.schema) as unknown as T) : this.contents if (this.range) copy.range = this.range.slice() as Document['range'] return copy } /** Adds a value to the document. */ add(value: any) { if (assertCollection(this.contents)) this.contents.add(value) } /** Adds a value to the document. */ addIn(path: Iterable<unknown>, value: unknown) { if (assertCollection(this.contents)) this.contents.addIn(path, value) } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. * * If `node` already has an anchor, `name` is ignored. * Otherwise, the `node.anchor` value will be set to `name`, * 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. * If `name` is undefined, the generated anchor will use 'a' as a prefix. */ createAlias(node: Scalar | YAMLMap | YAMLSeq, name?: string): Alias { if (!node.anchor) { const prev = anchorNames(this) node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name } return new Alias(node.anchor) } /** * Convert any value into a `Node` using the current schema, recursively * turning objects into collections. */ createNode<T = unknown>(value: T, options?: CreateNodeOptions): NodeType<T> createNode<T = unknown>( value: T, replacer: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): NodeType<T> createNode( value: unknown, replacer?: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): Node { let _replacer: Replacer | undefined = undefined if (typeof replacer === 'function') { value = replacer.call({ '': value }, '', value) _replacer = replacer } else if (Array.isArray(replacer)) { const keyToStr = (v: unknown) => typeof v === 'number' || v instanceof String || v instanceof Number const asStr = replacer.filter(keyToStr).map(String) if (asStr.length > 0) replacer = replacer.concat(asStr) _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {} const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( this, // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing anchorPrefix || 'a' ) const ctx: CreateNodeContext = { aliasDuplicateObjects: aliasDuplicateObjects ?? true, keepUndefined: keepUndefined ?? false, onAnchor, onTagObj, replacer: _replacer, schema: this.schema, sourceObjects } const node = createNode(value, tag, ctx) if (flow && isCollection(node)) node.flow = true setAnchors() return node } /** * Convert a key and a value into a `Pair` using the current schema, * recursively wrapping all values as `Scalar` or `Collection` nodes. */ createPair<K extends Node = Node, V extends Node = Node>( key: unknown, value: unknown, options: CreateNodeOptions = {} ) { const k = this.createNode(key, null, options) as K const v = this.createNode(value, null, options) as V return new Pair(k, v) } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ delete(key: unknown): boolean { return assertCollection(this.contents) ? this.contents.delete(key) : false } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ deleteIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) { if (this.contents == null) return false this.contents = null return true } return assertCollection(this.contents) ? this.contents.deleteIn(path) : false } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ get(key: unknown, keepScalar?: boolean): unknown { return isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined } /** * Returns item at `path`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path: Iterable<unknown> | null, keepScalar?: boolean): unknown { if (isEmptyPath(path)) return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : undefined } /** * Checks if the document includes a value with the key `key`. */ has(key: unknown): boolean { return isCollection(this.contents) ? this.contents.has(key) : false } /** * Checks if the document includes a value at `path`. */ hasIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) return this.contents !== undefined return isCollection(this.contents) ? this.contents.hasIn(path) : false } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ set(key: any, value: unknown): void { if (this.contents == null) { this.contents = collectionFromPath( this.schema, [key], value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.set(key, value) } } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path: Iterable<unknown> | null, value: unknown): void { if (isEmptyPath(path)) this.contents = value as T else if (this.contents == null) { this.contents = collectionFromPath( this.schema, Array.from(path), value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.setIn(path, value) } } /** * 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 the `schema` option to be given as a `Schema` instance value. * * Overrides all previously set schema options. */ setSchema( version: '1.1' | '1.2' | 'next' | null, options: SchemaOptions = {} ) { if (typeof version === 'number') version = String(version) as '1.1' | '1.2' let opt: (SchemaOptions & { schema: string }) | null switch (version) { case '1.1': if (this.directives) this.directives.yaml.version = '1.1' else this.directives = new Directives({ version: '1.1' }) opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' } break case '1.2': case 'next': if (this.directives) this.directives.yaml.version = version else this.directives = new Directives({ version }) opt = { merge: false, resolveKnownTags: true, schema: 'core' } break case null: if (this.directives) delete this.directives opt = null break default: { const sv = JSON.stringify(version) throw new Error( `Expected '1.1', '1.2' or null as first argument, but found: ${sv}` ) } } // Not using `instanceof Schema` to allow for duck typing if (options.schema instanceof Object) this.schema = options.schema else if (opt) this.schema = new Schema(Object.assign(opt, options)) else throw new Error( `With a null YAML version, the { schema: Schema } option is required` ) } /** A plain JavaScript representation of the document `contents`. */ toJS(opt?: ToJSOptions & { [ignored: string]: unknown }): any // json & jsonArg are only used from toJSON() toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver }: ToJSOptions & { json?: boolean; jsonArg?: string | null } = {}): any { const ctx: ToJSContext = { anchors: new Map(), doc: this, keep: !json, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100, stringify } const res = toJS(this.contents, jsonArg ?? '', ctx) if (typeof onAnchor === 'function') for (const { count, res } of ctx.anchors.values()) onAnchor(res, count) return typeof reviver === 'function' ? applyReviver(reviver, { '': res }, '', res) : res } /** * A JSON representation of the document `contents`. * * @param jsonArg Used by `JSON.stringify` to indicate the array index or * property name. */ toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any { return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }) } /** A YAML representation of the document. */ toString(options: ToStringOptions = {}): string { if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified') if ( 'indent' in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0) ) { const s = JSON.stringify(options.indent) throw new Error(`"indent" option must be a positive integer, not ${s}`) } return stringifyDocument(this, options) } }
20
private *scalar(scalar: FlowScalar) { if (this.type === 'map-value-ind') { const prev = getPrevProps(this.peek(2)) const start = getFirstKeyStartProps(prev) let sep: SourceToken[] if (scalar.end) { sep = scalar.end sep.push(this.sourceToken) delete scalar.end } else sep = [this.sourceToken] const map: BlockMap = { type: 'block-map', offset: scalar.offset, indent: scalar.indent, items: [{ start, key: scalar, sep }] } this.onKeyLine = true this.stack[this.stack.length - 1] = map } else yield* this.lineEnd(scalar) }
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
21
private *blockScalar(scalar: BlockScalar) { switch (this.type) { case 'space': case 'comment': case 'newline': scalar.props.push(this.sourceToken) return case 'scalar': scalar.source = this.source // block-scalar source includes trailing newline this.atNewLine = true this.indent = 0 if (this.onNewLine) { let nl = this.source.indexOf('\n') + 1 while (nl !== 0) { this.onNewLine(this.offset + nl) nl = this.source.indexOf('\n', nl) + 1 } } yield* this.pop() break /* istanbul ignore next should not happen */ default: yield* this.pop() yield* this.step() } }
interface BlockScalar { type: 'block-scalar' offset: number indent: number props: Token[] source: string }
22
private *blockMap(map: BlockMap) { const it = map.items[map.items.length - 1] // it.sep is true-ish if pair already has key or : separator switch (this.type) { case 'newline': this.onKeyLine = false if (it.value) { const end = 'end' in it.value ? it.value.end : undefined const last = Array.isArray(end) ? end[end.length - 1] : undefined if (last?.type === 'comment') end?.push(this.sourceToken) else map.items.push({ start: [this.sourceToken] }) } else if (it.sep) { it.sep.push(this.sourceToken) } else { it.start.push(this.sourceToken) } return case 'space': case 'comment': if (it.value) { map.items.push({ start: [this.sourceToken] }) } else if (it.sep) { it.sep.push(this.sourceToken) } else { if (this.atIndentedComment(it.start, map.indent)) { const prev = map.items[map.items.length - 2] const end = (prev?.value as { end: SourceToken[] })?.end if (Array.isArray(end)) { Array.prototype.push.apply(end, it.start) end.push(this.sourceToken) map.items.pop() return } } it.start.push(this.sourceToken) } return } if (this.indent >= map.indent) { const atNextItem = !this.onKeyLine && this.indent === map.indent && it.sep // For empty nodes, assign newline-separated not indented empty tokens to following node let start: SourceToken[] = [] if (atNextItem && it.sep && !it.value) { const nl: number[] = [] for (let i = 0; i < it.sep.length; ++i) { const st = it.sep[i] switch (st.type) { case 'newline': nl.push(i) break case 'space': break case 'comment': if (st.indent > map.indent) nl.length = 0 break default: nl.length = 0 } } if (nl.length >= 2) start = it.sep.splice(nl[1]) } switch (this.type) { case 'anchor': case 'tag': if (atNextItem || it.value) { start.push(this.sourceToken) map.items.push({ start }) this.onKeyLine = true } else if (it.sep) { it.sep.push(this.sourceToken) } else { it.start.push(this.sourceToken) } return case 'explicit-key-ind': if (!it.sep && !includesToken(it.start, 'explicit-key-ind')) { it.start.push(this.sourceToken) } else if (atNextItem || it.value) { start.push(this.sourceToken) map.items.push({ start }) } else { this.stack.push({ type: 'block-map', offset: this.offset, indent: this.indent, items: [{ start: [this.sourceToken] }] }) } this.onKeyLine = true return case 'map-value-ind': if (includesToken(it.start, 'explicit-key-ind')) { if (!it.sep) { if (includesToken(it.start, 'newline')) { Object.assign(it, { key: null, sep: [this.sourceToken] }) } else { const start = getFirstKeyStartProps(it.start) this.stack.push({ type: 'block-map', offset: this.offset, indent: this.indent, items: [{ start, key: null, sep: [this.sourceToken] }] }) } } else if (it.value) { map.items.push({ start: [], key: null, sep: [this.sourceToken] }) } else if (includesToken(it.sep, 'map-value-ind')) { this.stack.push({ type: 'block-map', offset: this.offset, indent: this.indent, items: [{ start, key: null, sep: [this.sourceToken] }] }) } else if ( isFlowToken(it.key) && !includesToken(it.sep, 'newline') ) { const start = getFirstKeyStartProps(it.start) const key = it.key const sep = it.sep sep.push(this.sourceToken) // @ts-expect-error type guard is wrong here delete it.key, delete it.sep this.stack.push({ type: 'block-map', offset: this.offset, indent: this.indent, items: [{ start, key, sep }] }) } else if (start.length > 0) { // Not actually at next item it.sep = it.sep.concat(start, this.sourceToken) } else { it.sep.push(this.sourceToken) } } else { if (!it.sep) { Object.assign(it, { key: null, sep: [this.sourceToken] }) } else if (it.value || atNextItem) { map.items.push({ start, key: null, sep: [this.sourceToken] }) } else if (includesToken(it.sep, 'map-value-ind')) { this.stack.push({ type: 'block-map', offset: this.offset, indent: this.indent, items: [{ start: [], key: null, sep: [this.sourceToken] }] }) } else { it.sep.push(this.sourceToken) } } this.onKeyLine = true return case 'alias': case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': { const fs = this.flowScalar(this.type) if (atNextItem || it.value) { map.items.push({ start, key: fs, sep: [] }) this.onKeyLine = true } else if (it.sep) { this.stack.push(fs) } else { Object.assign(it, { key: fs, sep: [] }) this.onKeyLine = true } return } default: { const bv = this.startBlockValue(map) if (bv) { if ( atNextItem && bv.type !== 'block-seq' && includesToken(it.start, 'explicit-key-ind') ) { map.items.push({ start }) } this.stack.push(bv) return } } } } yield* this.pop() yield* this.step() }
interface BlockMap { type: 'block-map' offset: number indent: number items: Array< | { start: SourceToken[]; key?: never; sep?: never; value?: never } | { start: SourceToken[] key: Token | null sep: SourceToken[] value?: Token } > }
23
private *blockSequence(seq: BlockSequence) { const it = seq.items[seq.items.length - 1] switch (this.type) { case 'newline': if (it.value) { const end = 'end' in it.value ? it.value.end : undefined const last = Array.isArray(end) ? end[end.length - 1] : undefined if (last?.type === 'comment') end?.push(this.sourceToken) else seq.items.push({ start: [this.sourceToken] }) } else it.start.push(this.sourceToken) return case 'space': case 'comment': if (it.value) seq.items.push({ start: [this.sourceToken] }) else { if (this.atIndentedComment(it.start, seq.indent)) { const prev = seq.items[seq.items.length - 2] const end = (prev?.value as { end: SourceToken[] })?.end if (Array.isArray(end)) { Array.prototype.push.apply(end, it.start) end.push(this.sourceToken) seq.items.pop() return } } it.start.push(this.sourceToken) } return case 'anchor': case 'tag': if (it.value || this.indent <= seq.indent) break it.start.push(this.sourceToken) return case 'seq-item-ind': if (this.indent !== seq.indent) break if (it.value || includesToken(it.start, 'seq-item-ind')) seq.items.push({ start: [this.sourceToken] }) else it.start.push(this.sourceToken) return } if (this.indent > seq.indent) { const bv = this.startBlockValue(seq) if (bv) { this.stack.push(bv) return } } yield* this.pop() yield* this.step() }
interface BlockSequence { type: 'block-seq' offset: number indent: number items: Array<{ start: SourceToken[] key?: never sep?: never value?: Token }> }
24
private *flowCollection(fc: FlowCollection) { const it = fc.items[fc.items.length - 1] if (this.type === 'flow-error-end') { let top: Token | undefined do { yield* this.pop() top = this.peek(1) } while (top && top.type === 'flow-collection') } else if (fc.end.length === 0) { switch (this.type) { case 'comma': case 'explicit-key-ind': if (!it || it.sep) fc.items.push({ start: [this.sourceToken] }) else it.start.push(this.sourceToken) return case 'map-value-ind': if (!it || it.value) fc.items.push({ start: [], key: null, sep: [this.sourceToken] }) else if (it.sep) it.sep.push(this.sourceToken) else Object.assign(it, { key: null, sep: [this.sourceToken] }) return case 'space': case 'comment': case 'newline': case 'anchor': case 'tag': if (!it || it.value) fc.items.push({ start: [this.sourceToken] }) else if (it.sep) it.sep.push(this.sourceToken) else it.start.push(this.sourceToken) return case 'alias': case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': { const fs = this.flowScalar(this.type) if (!it || it.value) fc.items.push({ start: [], key: fs, sep: [] }) else if (it.sep) this.stack.push(fs) else Object.assign(it, { key: fs, sep: [] }) return } case 'flow-map-end': case 'flow-seq-end': fc.end.push(this.sourceToken) return } const bv = this.startBlockValue(fc) /* istanbul ignore else should not happen */ if (bv) this.stack.push(bv) else { yield* this.pop() yield* this.step() } } else { const parent = this.peek(2) if ( parent.type === 'block-map' && ((this.type === 'map-value-ind' && parent.indent === fc.indent) || (this.type === 'newline' && !parent.items[parent.items.length - 1].sep)) ) { yield* this.pop() yield* this.step() } else if ( this.type === 'map-value-ind' && parent.type !== 'flow-collection' ) { const prev = getPrevProps(parent) const start = getFirstKeyStartProps(prev) fixFlowSeqItems(fc) const sep = fc.end.splice(1, fc.end.length) sep.push(this.sourceToken) const map: BlockMap = { type: 'block-map', offset: fc.offset, indent: fc.indent, items: [{ start, key: fc, sep }] } this.onKeyLine = true this.stack[this.stack.length - 1] = map } else { yield* this.lineEnd(fc) } } }
interface FlowCollection { type: 'flow-collection' offset: number indent: number start: SourceToken items: CollectionItem[] end: SourceToken[] }
25
private startBlockValue(parent: Token) { switch (this.type) { case 'alias': case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': return this.flowScalar(this.type) case 'block-scalar-header': return { type: 'block-scalar', offset: this.offset, indent: this.indent, props: [this.sourceToken], source: '' } as BlockScalar case 'flow-map-start': case 'flow-seq-start': return { type: 'flow-collection', offset: this.offset, indent: this.indent, start: this.sourceToken, items: [], end: [] } as FlowCollection case 'seq-item-ind': return { type: 'block-seq', offset: this.offset, indent: this.indent, items: [{ start: [this.sourceToken] }] } as BlockSequence case 'explicit-key-ind': { this.onKeyLine = true const prev = getPrevProps(parent) const start = getFirstKeyStartProps(prev) start.push(this.sourceToken) return { type: 'block-map', offset: this.offset, indent: this.indent, items: [{ start }] } as BlockMap } case 'map-value-ind': { this.onKeyLine = true const prev = getPrevProps(parent) const start = getFirstKeyStartProps(prev) return { type: 'block-map', offset: this.offset, indent: this.indent, items: [{ start, key: null, sep: [this.sourceToken] }] } as BlockMap } } return null }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
26
private *documentEnd(docEnd: DocumentEnd) { if (this.type !== 'doc-mode') { if (docEnd.end) docEnd.end.push(this.sourceToken) else docEnd.end = [this.sourceToken] if (this.type === 'newline') yield* this.pop() } }
interface DocumentEnd { type: 'doc-end' offset: number source: string end?: SourceToken[] }
27
function setScalarValue( token: Token, value: string, context: { afterKey?: boolean implicitKey?: boolean inFlow?: boolean type?: Scalar.Type } = {} ) { let { afterKey = false, implicitKey = false, inFlow = false, type } = context let indent = 'indent' in token ? token.indent : null if (afterKey && typeof indent === 'number') indent += 2 if (!type) switch (token.type) { case 'single-quoted-scalar': type = 'QUOTE_SINGLE' break case 'double-quoted-scalar': type = 'QUOTE_DOUBLE' break case 'block-scalar': { const header = token.props[0] if (header.type !== 'block-scalar-header') throw new Error('Invalid block scalar header') type = header.source[0] === '>' ? 'BLOCK_FOLDED' : 'BLOCK_LITERAL' break } default: type = 'PLAIN' } const source = stringifyString( { type, value } as Scalar, { implicitKey: implicitKey || indent === null, indent: indent !== null && indent > 0 ? ' '.repeat(indent) : '', inFlow, options: { blockQuote: true, lineWidth: -1 } } as StringifyContext ) switch (source[0]) { case '|': case '>': setBlockScalarValue(token, source) break case '"': setFlowScalarValue(token, source, 'double-quoted-scalar') break case "'": setFlowScalarValue(token, source, 'single-quoted-scalar') break default: setFlowScalarValue(token, source, 'scalar') } }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
28
function setBlockScalarValue(token: Token, source: string) { const he = source.indexOf('\n') const head = source.substring(0, he) const body = source.substring(he + 1) + '\n' if (token.type === 'block-scalar') { const header = token.props[0] if (header.type !== 'block-scalar-header') throw new Error('Invalid block scalar header') header.source = head token.source = body } else { const { offset } = token const indent = 'indent' in token ? token.indent : -1 const props: Token[] = [ { type: 'block-scalar-header', offset, indent, source: head } ] if (!addEndtoBlockProps(props, 'end' in token ? token.end : undefined)) props.push({ type: 'newline', offset: -1, indent, source: '\n' }) for (const key of Object.keys(token)) if (key !== 'type' && key !== 'offset') delete (token as any)[key] Object.assign(token, { type: 'block-scalar', indent, props, source: body }) } }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
29
function setFlowScalarValue( token: Token, source: string, type: 'scalar' | 'double-quoted-scalar' | 'single-quoted-scalar' ) { switch (token.type) { case 'scalar': case 'double-quoted-scalar': case 'single-quoted-scalar': token.type = type token.source = source break case 'block-scalar': { const end = token.props.slice(1) let oa = source.length if (token.props[0].type === 'block-scalar-header') oa -= token.props[0].source.length for (const tok of end) tok.offset += oa delete (token as any).props Object.assign(token, { type, source, end }) break } case 'block-map': case 'block-seq': { const offset = token.offset + source.length const nl = { type: 'newline', offset, indent: token.indent, source: '\n' } delete (token as any).items Object.assign(token, { type, source, end: [nl] }) break } default: { const indent = 'indent' in token ? token.indent : -1 const end = 'end' in token && Array.isArray(token.end) ? token.end.filter( st => st.type === 'space' || st.type === 'comment' || st.type === 'newline' ) : [] for (const key of Object.keys(token)) if (key !== 'type' && key !== 'offset') delete (token as any)[key] Object.assign(token, { type, indent, source, end }) } } }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
30
private setNext(state: State) { this.buffer = this.buffer.substring(this.pos) this.pos = 0 this.lineEndPos = null this.next = state return null }
type State = | 'stream' | 'line-start' | 'block-start' | 'doc' | 'flow' | 'quoted-scalar' | 'block-scalar' | 'plain-scalar'
31
private *parseNext(next: State) { switch (next) { case 'stream': return yield* this.parseStream() case 'line-start': return yield* this.parseLineStart() case 'block-start': return yield* this.parseBlockStart() case 'doc': return yield* this.parseDocument() case 'flow': return yield* this.parseFlowCollection() case 'quoted-scalar': return yield* this.parseQuotedScalar() case 'block-scalar': return yield* this.parseBlockScalar() case 'plain-scalar': return yield* this.parsePlainScalar() } }
type State = | 'stream' | 'line-start' | 'block-start' | 'doc' | 'flow' | 'quoted-scalar' | 'block-scalar' | 'plain-scalar'
32
( item: CollectionItem, path: VisitPath ) => number | symbol | Visitor | void
type VisitPath = readonly ['key' | 'value', number][]
33
( item: CollectionItem, path: VisitPath ) => number | symbol | Visitor | void
type CollectionItem = { start: SourceToken[] key?: Token | null sep?: SourceToken[] value?: Token }
34
function _visit( path: VisitPath, item: CollectionItem, visitor: Visitor ): number | symbol | Visitor | void { let ctrl = visitor(item, path) if (typeof ctrl === 'symbol') return ctrl for (const field of ['key', 'value'] as const) { const token = item[field] if (token && 'items' in token) { for (let i = 0; i < token.items.length; ++i) { const ci = _visit( Object.freeze(path.concat([[field, i]])), token.items[i], visitor ) if (typeof ci === 'number') i = ci - 1 else if (ci === BREAK) return BREAK else if (ci === REMOVE) { token.items.splice(i, 1) i -= 1 } } if (typeof ctrl === 'function' && field === 'key') ctrl = ctrl(item, path) } } return typeof ctrl === 'function' ? ctrl(item, path) : ctrl }
type VisitPath = readonly ['key' | 'value', number][]
35
function _visit( path: VisitPath, item: CollectionItem, visitor: Visitor ): number | symbol | Visitor | void { let ctrl = visitor(item, path) if (typeof ctrl === 'symbol') return ctrl for (const field of ['key', 'value'] as const) { const token = item[field] if (token && 'items' in token) { for (let i = 0; i < token.items.length; ++i) { const ci = _visit( Object.freeze(path.concat([[field, i]])), token.items[i], visitor ) if (typeof ci === 'number') i = ci - 1 else if (ci === BREAK) return BREAK else if (ci === REMOVE) { token.items.splice(i, 1) i -= 1 } } if (typeof ctrl === 'function' && field === 'key') ctrl = ctrl(item, path) } } return typeof ctrl === 'function' ? ctrl(item, path) : ctrl }
type CollectionItem = { start: SourceToken[] key?: Token | null sep?: SourceToken[] value?: Token }
36
function _visit( path: VisitPath, item: CollectionItem, visitor: Visitor ): number | symbol | Visitor | void { let ctrl = visitor(item, path) if (typeof ctrl === 'symbol') return ctrl for (const field of ['key', 'value'] as const) { const token = item[field] if (token && 'items' in token) { for (let i = 0; i < token.items.length; ++i) { const ci = _visit( Object.freeze(path.concat([[field, i]])), token.items[i], visitor ) if (typeof ci === 'number') i = ci - 1 else if (ci === BREAK) return BREAK else if (ci === REMOVE) { token.items.splice(i, 1) i -= 1 } } if (typeof ctrl === 'function' && field === 'key') ctrl = ctrl(item, path) } } return typeof ctrl === 'function' ? ctrl(item, path) : ctrl }
type Visitor = ( item: CollectionItem, path: VisitPath ) => number | symbol | Visitor | void
37
function collectionFromPath( schema: Schema, path: unknown[], value: unknown ) { let v = value for (let i = path.length - 1; i >= 0; --i) { const k = path[i] if (typeof k === 'number' && Number.isInteger(k) && k >= 0) { const a: unknown[] = [] a[k] = v v = a } else { v = new Map<unknown, unknown>([[k, v]]) } } return createNode(v, undefined, { aliasDuplicateObjects: false, keepUndefined: false, onAnchor: () => { throw new Error('This should not happen, please report a bug.') }, schema, sourceObjects: new Map() }) }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
38
clone(schema?: Schema): Collection { const copy: Collection = Object.create( Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this) ) if (schema) copy.schema = schema copy.items = copy.items.map(it => isNode(it) || isPair(it) ? it.clone(schema) : it ) if (this.range) copy.range = this.range.slice() as NodeBase['range'] return copy }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
39
constructor(schema?: Schema) { super(MAP, schema) }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
40
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string { if (!ctx) return JSON.stringify(this) for (const item of this.items) { if (!isPair(item)) throw new Error( `Map items must all be pairs; found ${JSON.stringify(item)} instead` ) } if (!ctx.allNullValues && this.hasAllNullValues(false)) ctx = Object.assign({}, ctx, { allNullValues: true }) return stringifyCollection(this, ctx, { blockItemPrefix: '', flowChars: { start: '{', end: '}' }, itemIndent: ctx.indent || '', onChompKeep, onComment }) }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
41
clone(schema?: Schema): Pair<K, V> { let { key, value } = this if (isNode(key)) key = key.clone(schema) as unknown as K if (isNode(value)) value = value.clone(schema) as unknown as V return new Pair(key, value) }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
42
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string { return ctx?.doc ? stringifyPair(this, ctx, onComment, onChompKeep) : JSON.stringify(this) }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
43
abstract toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
44
constructor(schema?: Schema) { super(SEQ, schema) }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
45
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ): string { if (!ctx) return JSON.stringify(this) return stringifyCollection(this, ctx, { blockItemPrefix: '- ', flowChars: { start: '[', end: ']' }, itemIndent: (ctx.indent || '') + ' ', onChompKeep, onComment }) }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
46
resolve(doc: Document): Scalar | YAMLMap | YAMLSeq | undefined { let found: Scalar | YAMLMap | YAMLSeq | undefined = undefined visit(doc, { Node: (_key: unknown, node: Node) => { if (node === this) return visit.BREAK if (node.anchor === this.source) found = node } }) return found }
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
47
resolve(doc: Document): Scalar | YAMLMap | YAMLSeq | undefined { let found: Scalar | YAMLMap | YAMLSeq | undefined = undefined visit(doc, { Node: (_key: unknown, node: Node) => { if (node === this) return visit.BREAK if (node.anchor === this.source) found = node } }) return found }
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directives /** Errors encountered during parsing. */ errors: YAMLError[] = [] options: Required< Omit< ParseOptions & DocumentOptions, '_directives' | 'lineCounter' | 'version' > > /** * The `[start, value-end, node-end]` character offsets for the part of the * source parsed into this document (undefined if not parsed). The `value-end` * and `node-end` positions are themselves not included in their respective * ranges. */ declare range?: Range // TS can't figure out that setSchema() will set this, or throw /** The schema used with the document. Use `setSchema()` to change. */ declare schema: Schema /** Warnings encountered during parsing. */ warnings: YAMLWarning[] = [] /** * @param value - The initial value for the document, which will be wrapped * in a Node container. */ constructor( value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value: any, replacer: null | Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value?: unknown, replacer?: | Replacer | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions) | null, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) { Object.defineProperty(this, NODE_TYPE, { value: DOC }) let _replacer: Replacer | null = null if (typeof replacer === 'function' || Array.isArray(replacer)) { _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const opt = Object.assign( { intAsBigInt: false, keepSourceTokens: false, logLevel: 'warn', prettyErrors: true, strict: true, uniqueKeys: true, version: '1.2' }, options ) this.options = opt let { version } = opt if (options?._directives) { this.directives = options._directives.atDocument() if (this.directives.yaml.explicit) version = this.directives.yaml.version } else this.directives = new Directives({ version }) this.setSchema(version, options) if (value === undefined) this.contents = null else { this.contents = this.createNode(value, _replacer, options) as unknown as T } } /** * Create a deep copy of this Document and its contents. * * Custom Node values that inherit from `Object` still refer to their original instances. */ clone(): Document<T> { const copy: Document<T> = Object.create(Document.prototype, { [NODE_TYPE]: { value: DOC } }) copy.commentBefore = this.commentBefore copy.comment = this.comment copy.errors = this.errors.slice() copy.warnings = this.warnings.slice() copy.options = Object.assign({}, this.options) if (this.directives) copy.directives = this.directives.clone() copy.schema = this.schema.clone() copy.contents = isNode(this.contents) ? (this.contents.clone(copy.schema) as unknown as T) : this.contents if (this.range) copy.range = this.range.slice() as Document['range'] return copy } /** Adds a value to the document. */ add(value: any) { if (assertCollection(this.contents)) this.contents.add(value) } /** Adds a value to the document. */ addIn(path: Iterable<unknown>, value: unknown) { if (assertCollection(this.contents)) this.contents.addIn(path, value) } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. * * If `node` already has an anchor, `name` is ignored. * Otherwise, the `node.anchor` value will be set to `name`, * 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. * If `name` is undefined, the generated anchor will use 'a' as a prefix. */ createAlias(node: Scalar | YAMLMap | YAMLSeq, name?: string): Alias { if (!node.anchor) { const prev = anchorNames(this) node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name } return new Alias(node.anchor) } /** * Convert any value into a `Node` using the current schema, recursively * turning objects into collections. */ createNode<T = unknown>(value: T, options?: CreateNodeOptions): NodeType<T> createNode<T = unknown>( value: T, replacer: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): NodeType<T> createNode( value: unknown, replacer?: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): Node { let _replacer: Replacer | undefined = undefined if (typeof replacer === 'function') { value = replacer.call({ '': value }, '', value) _replacer = replacer } else if (Array.isArray(replacer)) { const keyToStr = (v: unknown) => typeof v === 'number' || v instanceof String || v instanceof Number const asStr = replacer.filter(keyToStr).map(String) if (asStr.length > 0) replacer = replacer.concat(asStr) _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {} const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( this, // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing anchorPrefix || 'a' ) const ctx: CreateNodeContext = { aliasDuplicateObjects: aliasDuplicateObjects ?? true, keepUndefined: keepUndefined ?? false, onAnchor, onTagObj, replacer: _replacer, schema: this.schema, sourceObjects } const node = createNode(value, tag, ctx) if (flow && isCollection(node)) node.flow = true setAnchors() return node } /** * Convert a key and a value into a `Pair` using the current schema, * recursively wrapping all values as `Scalar` or `Collection` nodes. */ createPair<K extends Node = Node, V extends Node = Node>( key: unknown, value: unknown, options: CreateNodeOptions = {} ) { const k = this.createNode(key, null, options) as K const v = this.createNode(value, null, options) as V return new Pair(k, v) } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ delete(key: unknown): boolean { return assertCollection(this.contents) ? this.contents.delete(key) : false } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ deleteIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) { if (this.contents == null) return false this.contents = null return true } return assertCollection(this.contents) ? this.contents.deleteIn(path) : false } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ get(key: unknown, keepScalar?: boolean): unknown { return isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined } /** * Returns item at `path`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path: Iterable<unknown> | null, keepScalar?: boolean): unknown { if (isEmptyPath(path)) return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : undefined } /** * Checks if the document includes a value with the key `key`. */ has(key: unknown): boolean { return isCollection(this.contents) ? this.contents.has(key) : false } /** * Checks if the document includes a value at `path`. */ hasIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) return this.contents !== undefined return isCollection(this.contents) ? this.contents.hasIn(path) : false } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ set(key: any, value: unknown): void { if (this.contents == null) { this.contents = collectionFromPath( this.schema, [key], value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.set(key, value) } } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path: Iterable<unknown> | null, value: unknown): void { if (isEmptyPath(path)) this.contents = value as T else if (this.contents == null) { this.contents = collectionFromPath( this.schema, Array.from(path), value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.setIn(path, value) } } /** * 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 the `schema` option to be given as a `Schema` instance value. * * Overrides all previously set schema options. */ setSchema( version: '1.1' | '1.2' | 'next' | null, options: SchemaOptions = {} ) { if (typeof version === 'number') version = String(version) as '1.1' | '1.2' let opt: (SchemaOptions & { schema: string }) | null switch (version) { case '1.1': if (this.directives) this.directives.yaml.version = '1.1' else this.directives = new Directives({ version: '1.1' }) opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' } break case '1.2': case 'next': if (this.directives) this.directives.yaml.version = version else this.directives = new Directives({ version }) opt = { merge: false, resolveKnownTags: true, schema: 'core' } break case null: if (this.directives) delete this.directives opt = null break default: { const sv = JSON.stringify(version) throw new Error( `Expected '1.1', '1.2' or null as first argument, but found: ${sv}` ) } } // Not using `instanceof Schema` to allow for duck typing if (options.schema instanceof Object) this.schema = options.schema else if (opt) this.schema = new Schema(Object.assign(opt, options)) else throw new Error( `With a null YAML version, the { schema: Schema } option is required` ) } /** A plain JavaScript representation of the document `contents`. */ toJS(opt?: ToJSOptions & { [ignored: string]: unknown }): any // json & jsonArg are only used from toJSON() toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver }: ToJSOptions & { json?: boolean; jsonArg?: string | null } = {}): any { const ctx: ToJSContext = { anchors: new Map(), doc: this, keep: !json, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100, stringify } const res = toJS(this.contents, jsonArg ?? '', ctx) if (typeof onAnchor === 'function') for (const { count, res } of ctx.anchors.values()) onAnchor(res, count) return typeof reviver === 'function' ? applyReviver(reviver, { '': res }, '', res) : res } /** * A JSON representation of the document `contents`. * * @param jsonArg Used by `JSON.stringify` to indicate the array index or * property name. */ toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any { return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }) } /** A YAML representation of the document. */ toString(options: ToStringOptions = {}): string { if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified') if ( 'indent' in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0) ) { const s = JSON.stringify(options.indent) throw new Error(`"indent" option must be a positive integer, not ${s}`) } return stringifyDocument(this, options) } }
48
toString( ctx?: StringifyContext, _onComment?: () => void, _onChompKeep?: () => void ) { const src = `*${this.source}` if (ctx) { anchorIsValid(this.source) if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) { const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}` throw new Error(msg) } if (ctx.implicitKey) return `${src} ` } return src }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
49
function getAliasCount( doc: Document, node: unknown, anchors: ToJSContext['anchors'] ): number { if (isAlias(node)) { const source = node.resolve(doc) const anchor = anchors && source && anchors.get(source) return anchor ? anchor.count * anchor.aliasCount : 0 } else if (isCollection(node)) { let count = 0 for (const item of node.items) { const c = getAliasCount(doc, item, anchors) if (c > count) count = c } return count } else if (isPair(node)) { const kc = getAliasCount(doc, node.key, anchors) const vc = getAliasCount(doc, node.value, anchors) return Math.max(kc, vc) } return 1 }
interface Document { type: 'document' offset: number start: SourceToken[] value?: Token end?: SourceToken[] }
50
function getAliasCount( doc: Document, node: unknown, anchors: ToJSContext['anchors'] ): number { if (isAlias(node)) { const source = node.resolve(doc) const anchor = anchors && source && anchors.get(source) return anchor ? anchor.count * anchor.aliasCount : 0 } else if (isCollection(node)) { let count = 0 for (const item of node.items) { const c = getAliasCount(doc, item, anchors) if (c > count) count = c } return count } else if (isPair(node)) { const kc = getAliasCount(doc, node.key, anchors) const vc = getAliasCount(doc, node.value, anchors) return Math.max(kc, vc) } return 1 }
class Document<T extends Node = Node> { declare readonly [NODE_TYPE]: symbol /** A comment before this Document */ commentBefore: string | null = null /** A comment immediately after this Document */ comment: string | null = null /** The document contents. */ contents: T | null directives?: Directives /** Errors encountered during parsing. */ errors: YAMLError[] = [] options: Required< Omit< ParseOptions & DocumentOptions, '_directives' | 'lineCounter' | 'version' > > /** * The `[start, value-end, node-end]` character offsets for the part of the * source parsed into this document (undefined if not parsed). The `value-end` * and `node-end` positions are themselves not included in their respective * ranges. */ declare range?: Range // TS can't figure out that setSchema() will set this, or throw /** The schema used with the document. Use `setSchema()` to change. */ declare schema: Schema /** Warnings encountered during parsing. */ warnings: YAMLWarning[] = [] /** * @param value - The initial value for the document, which will be wrapped * in a Node container. */ constructor( value?: any, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value: any, replacer: null | Replacer, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) constructor( value?: unknown, replacer?: | Replacer | (DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions) | null, options?: DocumentOptions & SchemaOptions & ParseOptions & CreateNodeOptions ) { Object.defineProperty(this, NODE_TYPE, { value: DOC }) let _replacer: Replacer | null = null if (typeof replacer === 'function' || Array.isArray(replacer)) { _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const opt = Object.assign( { intAsBigInt: false, keepSourceTokens: false, logLevel: 'warn', prettyErrors: true, strict: true, uniqueKeys: true, version: '1.2' }, options ) this.options = opt let { version } = opt if (options?._directives) { this.directives = options._directives.atDocument() if (this.directives.yaml.explicit) version = this.directives.yaml.version } else this.directives = new Directives({ version }) this.setSchema(version, options) if (value === undefined) this.contents = null else { this.contents = this.createNode(value, _replacer, options) as unknown as T } } /** * Create a deep copy of this Document and its contents. * * Custom Node values that inherit from `Object` still refer to their original instances. */ clone(): Document<T> { const copy: Document<T> = Object.create(Document.prototype, { [NODE_TYPE]: { value: DOC } }) copy.commentBefore = this.commentBefore copy.comment = this.comment copy.errors = this.errors.slice() copy.warnings = this.warnings.slice() copy.options = Object.assign({}, this.options) if (this.directives) copy.directives = this.directives.clone() copy.schema = this.schema.clone() copy.contents = isNode(this.contents) ? (this.contents.clone(copy.schema) as unknown as T) : this.contents if (this.range) copy.range = this.range.slice() as Document['range'] return copy } /** Adds a value to the document. */ add(value: any) { if (assertCollection(this.contents)) this.contents.add(value) } /** Adds a value to the document. */ addIn(path: Iterable<unknown>, value: unknown) { if (assertCollection(this.contents)) this.contents.addIn(path, value) } /** * Create a new `Alias` node, ensuring that the target `node` has the required anchor. * * If `node` already has an anchor, `name` is ignored. * Otherwise, the `node.anchor` value will be set to `name`, * 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. * If `name` is undefined, the generated anchor will use 'a' as a prefix. */ createAlias(node: Scalar | YAMLMap | YAMLSeq, name?: string): Alias { if (!node.anchor) { const prev = anchorNames(this) node.anchor = // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name } return new Alias(node.anchor) } /** * Convert any value into a `Node` using the current schema, recursively * turning objects into collections. */ createNode<T = unknown>(value: T, options?: CreateNodeOptions): NodeType<T> createNode<T = unknown>( value: T, replacer: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): NodeType<T> createNode( value: unknown, replacer?: Replacer | CreateNodeOptions | null, options?: CreateNodeOptions ): Node { let _replacer: Replacer | undefined = undefined if (typeof replacer === 'function') { value = replacer.call({ '': value }, '', value) _replacer = replacer } else if (Array.isArray(replacer)) { const keyToStr = (v: unknown) => typeof v === 'number' || v instanceof String || v instanceof Number const asStr = replacer.filter(keyToStr).map(String) if (asStr.length > 0) replacer = replacer.concat(asStr) _replacer = replacer } else if (options === undefined && replacer) { options = replacer replacer = undefined } const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {} const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors( this, // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing anchorPrefix || 'a' ) const ctx: CreateNodeContext = { aliasDuplicateObjects: aliasDuplicateObjects ?? true, keepUndefined: keepUndefined ?? false, onAnchor, onTagObj, replacer: _replacer, schema: this.schema, sourceObjects } const node = createNode(value, tag, ctx) if (flow && isCollection(node)) node.flow = true setAnchors() return node } /** * Convert a key and a value into a `Pair` using the current schema, * recursively wrapping all values as `Scalar` or `Collection` nodes. */ createPair<K extends Node = Node, V extends Node = Node>( key: unknown, value: unknown, options: CreateNodeOptions = {} ) { const k = this.createNode(key, null, options) as K const v = this.createNode(value, null, options) as V return new Pair(k, v) } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ delete(key: unknown): boolean { return assertCollection(this.contents) ? this.contents.delete(key) : false } /** * Removes a value from the document. * @returns `true` if the item was found and removed. */ deleteIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) { if (this.contents == null) return false this.contents = null return true } return assertCollection(this.contents) ? this.contents.deleteIn(path) : false } /** * Returns item at `key`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ get(key: unknown, keepScalar?: boolean): unknown { return isCollection(this.contents) ? this.contents.get(key, keepScalar) : undefined } /** * Returns item at `path`, or `undefined` if not found. By default unwraps * scalar values from their surrounding node; to disable set `keepScalar` to * `true` (collections are always returned intact). */ getIn(path: Iterable<unknown> | null, keepScalar?: boolean): unknown { if (isEmptyPath(path)) return !keepScalar && isScalar(this.contents) ? this.contents.value : this.contents return isCollection(this.contents) ? this.contents.getIn(path, keepScalar) : undefined } /** * Checks if the document includes a value with the key `key`. */ has(key: unknown): boolean { return isCollection(this.contents) ? this.contents.has(key) : false } /** * Checks if the document includes a value at `path`. */ hasIn(path: Iterable<unknown> | null): boolean { if (isEmptyPath(path)) return this.contents !== undefined return isCollection(this.contents) ? this.contents.hasIn(path) : false } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ set(key: any, value: unknown): void { if (this.contents == null) { this.contents = collectionFromPath( this.schema, [key], value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.set(key, value) } } /** * Sets a value in this document. For `!!set`, `value` needs to be a * boolean to add/remove the item from the set. */ setIn(path: Iterable<unknown> | null, value: unknown): void { if (isEmptyPath(path)) this.contents = value as T else if (this.contents == null) { this.contents = collectionFromPath( this.schema, Array.from(path), value ) as unknown as T } else if (assertCollection(this.contents)) { this.contents.setIn(path, value) } } /** * 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 the `schema` option to be given as a `Schema` instance value. * * Overrides all previously set schema options. */ setSchema( version: '1.1' | '1.2' | 'next' | null, options: SchemaOptions = {} ) { if (typeof version === 'number') version = String(version) as '1.1' | '1.2' let opt: (SchemaOptions & { schema: string }) | null switch (version) { case '1.1': if (this.directives) this.directives.yaml.version = '1.1' else this.directives = new Directives({ version: '1.1' }) opt = { merge: true, resolveKnownTags: false, schema: 'yaml-1.1' } break case '1.2': case 'next': if (this.directives) this.directives.yaml.version = version else this.directives = new Directives({ version }) opt = { merge: false, resolveKnownTags: true, schema: 'core' } break case null: if (this.directives) delete this.directives opt = null break default: { const sv = JSON.stringify(version) throw new Error( `Expected '1.1', '1.2' or null as first argument, but found: ${sv}` ) } } // Not using `instanceof Schema` to allow for duck typing if (options.schema instanceof Object) this.schema = options.schema else if (opt) this.schema = new Schema(Object.assign(opt, options)) else throw new Error( `With a null YAML version, the { schema: Schema } option is required` ) } /** A plain JavaScript representation of the document `contents`. */ toJS(opt?: ToJSOptions & { [ignored: string]: unknown }): any // json & jsonArg are only used from toJSON() toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver }: ToJSOptions & { json?: boolean; jsonArg?: string | null } = {}): any { const ctx: ToJSContext = { anchors: new Map(), doc: this, keep: !json, mapAsMap: mapAsMap === true, mapKeyWarned: false, maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100, stringify } const res = toJS(this.contents, jsonArg ?? '', ctx) if (typeof onAnchor === 'function') for (const { count, res } of ctx.anchors.values()) onAnchor(res, count) return typeof reviver === 'function' ? applyReviver(reviver, { '': res }, '', res) : res } /** * A JSON representation of the document `contents`. * * @param jsonArg Used by `JSON.stringify` to indicate the array index or * property name. */ toJSON(jsonArg?: string | null, onAnchor?: ToJSOptions['onAnchor']): any { return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor }) } /** A YAML representation of the document. */ toString(options: ToStringOptions = {}): string { if (this.errors.length > 0) throw new Error('Document with errors cannot be stringified') if ( 'indent' in options && (!Number.isInteger(options.indent) || Number(options.indent) <= 0) ) { const s = JSON.stringify(options.indent) throw new Error(`"indent" option must be a positive integer, not ${s}`) } return stringifyDocument(this, options) } }
51
(schema: Schema, value: unknown, ctx: CreateNodeContext) => Node
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
52
(schema: Schema, value: unknown, ctx: CreateNodeContext) => Node
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
53
( item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void ) => string
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
54
( item: Scalar, ctx: StringifyContext, onComment?: () => void, onChompKeep?: () => void ) => string
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this node. Used by alias nodes. */ declare anchor?: 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' */ declare format?: string /** If `value` is a number, use this value when stringifying this node. */ declare minFractionDigits?: number /** Set during parsing to the source string value */ declare source?: string /** The scalar style used for the node's string representation */ declare type?: Scalar.Type constructor(value: T) { super(SCALAR) this.value = value } toJSON(arg?: any, ctx?: ToJSContext): any { return ctx?.keep ? this.value : toJS(this.value, arg, ctx) } toString() { return String(this.value) } }
55
constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null }
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 }
56
({ value }: Scalar) => JSON.stringify(value)
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this node. Used by alias nodes. */ declare anchor?: 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' */ declare format?: string /** If `value` is a number, use this value when stringifying this node. */ declare minFractionDigits?: number /** Set during parsing to the source string value */ declare source?: string /** The scalar style used for the node's string representation */ declare type?: Scalar.Type constructor(value: T) { super(SCALAR) this.value = value } toJSON(arg?: any, ctx?: ToJSContext): any { return ctx?.keep ? this.value : toJS(this.value, arg, ctx) } toString() { return String(this.value) } }
57
function intStringify(node: Scalar, radix: number, prefix: string) { const { value } = node if (intIdentify(value) && value >= 0) return prefix + value.toString(radix) return stringifyNumber(node) }
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this node. Used by alias nodes. */ declare anchor?: 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' */ declare format?: string /** If `value` is a number, use this value when stringifying this node. */ declare minFractionDigits?: number /** Set during parsing to the source string value */ declare source?: string /** The scalar style used for the node's string representation */ declare type?: Scalar.Type constructor(value: T) { super(SCALAR) this.value = value } toJSON(arg?: any, ctx?: ToJSContext): any { return ctx?.keep ? this.value : toJS(this.value, arg, ctx) } toString() { return String(this.value) } }
58
function createPairs( schema: Schema, iterable: unknown, ctx: CreateNodeContext ) { const { replacer } = ctx const pairs = new YAMLSeq(schema) pairs.tag = 'tag:yaml.org,2002:pairs' let i = 0 if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable as Iterable<unknown>) { if (typeof replacer === 'function') it = replacer.call(iterable, String(i++), it) let key: unknown, value: unknown if (Array.isArray(it)) { if (it.length === 2) { key = it[0] value = it[1] } else throw new TypeError(`Expected [key, value] tuple: ${it}`) } else if (it && it instanceof Object) { const keys = Object.keys(it) if (keys.length === 1) { key = keys[0] value = (it as any)[key as string] } else throw new TypeError(`Expected { key: value } tuple: ${it}`) } else { key = it } pairs.items.push(createPair(key, value, ctx)) } return pairs }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
59
function createPairs( schema: Schema, iterable: unknown, ctx: CreateNodeContext ) { const { replacer } = ctx const pairs = new YAMLSeq(schema) pairs.tag = 'tag:yaml.org,2002:pairs' let i = 0 if (iterable && Symbol.iterator in Object(iterable)) for (let it of iterable as Iterable<unknown>) { if (typeof replacer === 'function') it = replacer.call(iterable, String(i++), it) let key: unknown, value: unknown if (Array.isArray(it)) { if (it.length === 2) { key = it[0] value = it[1] } else throw new TypeError(`Expected [key, value] tuple: ${it}`) } else if (it && it instanceof Object) { const keys = Object.keys(it) if (keys.length === 1) { key = keys[0] value = (it as any)[key as string] } else throw new TypeError(`Expected { key: value } tuple: ${it}`) } else { key = it } pairs.items.push(createPair(key, value, ctx)) } return pairs }
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
60
constructor(schema?: Schema) { super(schema) this.tag = YAMLSet.tag }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
61
toString( ctx?: StringifyContext, onComment?: () => void, onChompKeep?: () => void ) { if (!ctx) return JSON.stringify(this) if (this.hasAllNullValues(true)) return super.toString( Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep ) else throw new Error('Set items must all have null values') }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
62
function boolStringify({ value, source }: Scalar, ctx: StringifyContext) { const boolObj = value ? trueTag : falseTag if (source && boolObj.test.test(source)) return source return value ? ctx.options.trueStr : ctx.options.falseStr }
type StringifyContext = { actualString?: boolean allNullValues?: boolean anchors: Set<string> doc: Document forceBlockIndent?: boolean implicitKey?: boolean indent: string indentStep: string indentAtStart?: number inFlow: boolean | null inStringifyKey?: boolean flowCollectionPadding: string options: Readonly< Required<Omit<ToStringOptions, 'collectionStyle' | 'indent'>> > resolvedAliases?: Set<Alias> }
63
function boolStringify({ value, source }: Scalar, ctx: StringifyContext) { const boolObj = value ? trueTag : falseTag if (source && boolObj.test.test(source)) return source return value ? ctx.options.trueStr : ctx.options.falseStr }
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this node. Used by alias nodes. */ declare anchor?: 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' */ declare format?: string /** If `value` is a number, use this value when stringifying this node. */ declare minFractionDigits?: number /** Set during parsing to the source string value */ declare source?: string /** The scalar style used for the node's string representation */ declare type?: Scalar.Type constructor(value: T) { super(SCALAR) this.value = value } toJSON(arg?: any, ctx?: ToJSContext): any { return ctx?.keep ? this.value : toJS(this.value, arg, ctx) } toString() { return String(this.value) } }
64
function stringifySexagesimal(node: Scalar) { let { value } = node as Scalar<number> let num = (n: number) => n if (typeof value === 'bigint') num = n => BigInt(n) as unknown as number else if (isNaN(value) || !isFinite(value)) return stringifyNumber(node) let sign = '' if (value < 0) { sign = '-' value *= num(-1) } const _60 = num(60) const parts = [value % _60] // seconds, including ms if (value < 60) { parts.unshift(0) // at least one : is required } else { value = (value - parts[0]) / _60 parts.unshift(value % _60) // minutes if (value >= 60) { value = (value - parts[0]) / _60 parts.unshift(value) // hours } } return ( sign + parts .map(n => (n < 10 ? '0' + String(n) : String(n))) .join(':') .replace(/000000\d*$/, '') // % 60 may introduce error ) }
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this node. Used by alias nodes. */ declare anchor?: 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' */ declare format?: string /** If `value` is a number, use this value when stringifying this node. */ declare minFractionDigits?: number /** Set during parsing to the source string value */ declare source?: string /** The scalar style used for the node's string representation */ declare type?: Scalar.Type constructor(value: T) { super(SCALAR) this.value = value } toJSON(arg?: any, ctx?: ToJSContext): any { return ctx?.keep ? this.value : toJS(this.value, arg, ctx) } toString() { return String(this.value) } }
65
function intStringify(node: Scalar, radix: number, prefix: string) { const { value } = node if (intIdentify(value)) { const str = value.toString(radix) return value < 0 ? '-' + prefix + str.substr(1) : prefix + str } return stringifyNumber(node) }
class Scalar<T = unknown> extends NodeBase { static readonly BLOCK_FOLDED = 'BLOCK_FOLDED' static readonly BLOCK_LITERAL = 'BLOCK_LITERAL' static readonly PLAIN = 'PLAIN' static readonly QUOTE_DOUBLE = 'QUOTE_DOUBLE' static readonly QUOTE_SINGLE = 'QUOTE_SINGLE' value: T /** An optional anchor on this node. Used by alias nodes. */ declare anchor?: 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' */ declare format?: string /** If `value` is a number, use this value when stringifying this node. */ declare minFractionDigits?: number /** Set during parsing to the source string value */ declare source?: string /** The scalar style used for the node's string representation */ declare type?: Scalar.Type constructor(value: T) { super(SCALAR) this.value = value } toJSON(arg?: any, ctx?: ToJSContext): any { return ctx?.keep ? this.value : toJS(this.value, arg, ctx) } toString() { return String(this.value) } }
66
function createSeq(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { replacer } = ctx const seq = new YAMLSeq(schema) if (obj && Symbol.iterator in Object(obj)) { let i = 0 for (let it of obj as Iterable<unknown>) { if (typeof replacer === 'function') { const key = obj instanceof Set ? it : String(i++) it = replacer.call(obj, key, it) } seq.items.push(createNode(it, undefined, ctx)) } } return seq }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
67
function createSeq(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { replacer } = ctx const seq = new YAMLSeq(schema) if (obj && Symbol.iterator in Object(obj)) { let i = 0 for (let it of obj as Iterable<unknown>) { if (typeof replacer === 'function') { const key = obj instanceof Set ? it : String(i++) it = replacer.call(obj, key, it) } seq.items.push(createNode(it, undefined, ctx)) } } return seq }
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
68
function createMap(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { keepUndefined, replacer } = ctx const map = new YAMLMap(schema) const add = (key: unknown, value: unknown) => { if (typeof replacer === 'function') value = replacer.call(obj, key, value) else if (Array.isArray(replacer) && !replacer.includes(key)) return if (value !== undefined || keepUndefined) map.items.push(createPair(key, value, ctx)) } if (obj instanceof Map) { for (const [key, value] of obj) add(key, value) } else if (obj && typeof obj === 'object') { for (const key of Object.keys(obj)) add(key, (obj as any)[key]) } if (typeof schema.sortMapEntries === 'function') { map.items.sort(schema.sortMapEntries) } return map }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
69
function createMap(schema: Schema, obj: unknown, ctx: CreateNodeContext) { const { keepUndefined, replacer } = ctx const map = new YAMLMap(schema) const add = (key: unknown, value: unknown) => { if (typeof replacer === 'function') value = replacer.call(obj, key, value) else if (Array.isArray(replacer) && !replacer.includes(key)) return if (value !== undefined || keepUndefined) map.items.push(createPair(key, value, ctx)) } if (obj instanceof Map) { for (const [key, value] of obj) add(key, value) } else if (obj && typeof obj === 'object') { for (const key of Object.keys(obj)) add(key, (obj as any)[key]) } if (typeof schema.sortMapEntries === 'function') { map.items.sort(schema.sortMapEntries) } return map }
interface CreateNodeContext { aliasDuplicateObjects: boolean keepUndefined: boolean onAnchor: (source: unknown) => string onTagObj?: (tagObj: ScalarTag | CollectionTag) => void sourceObjects: Map<unknown, { anchor: string | null; node: Node | null }> replacer?: Replacer schema: Schema }
70
function composeCollection( CN: ComposeNode, ctx: ComposeContext, token: BlockMap | BlockSequence | FlowCollection, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { let coll: YAMLMap.Parsed | YAMLSeq.Parsed switch (token.type) { case 'block-map': { coll = resolveBlockMap(CN, ctx, token, onError) break } case 'block-seq': { coll = resolveBlockSeq(CN, ctx, token, onError) break } case 'flow-collection': { coll = resolveFlowCollection(CN, ctx, token, onError) break } } if (!tagToken) return coll const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg) ) if (!tagName) return coll // Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841 const Coll = coll.constructor as typeof YAMLMap | typeof YAMLSeq if (tagName === '!' || tagName === Coll.tagName) { coll.tag = Coll.tagName return coll } const expType = isMap(coll) ? 'map' : 'seq' let tag = ctx.schema.tags.find( t => t.collection === expType && t.tag === tagName ) as CollectionTag | undefined if (!tag) { const kt = ctx.schema.knownTags[tagName] if (kt && kt.collection === expType) { ctx.schema.tags.push(Object.assign({}, kt, { default: false })) tag = kt } else { onError( tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true ) coll.tag = tagName return coll } } const res = tag.resolve( coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options ) const node = isNode(res) ? (res as ParsedNode) : (new Scalar(res) as Scalar.Parsed) node.range = coll.range node.tag = tagName if (tag?.format) (node as Scalar).format = tag.format return node }
type ComposeNode = typeof CN
71
function composeCollection( CN: ComposeNode, ctx: ComposeContext, token: BlockMap | BlockSequence | FlowCollection, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { let coll: YAMLMap.Parsed | YAMLSeq.Parsed switch (token.type) { case 'block-map': { coll = resolveBlockMap(CN, ctx, token, onError) break } case 'block-seq': { coll = resolveBlockSeq(CN, ctx, token, onError) break } case 'flow-collection': { coll = resolveFlowCollection(CN, ctx, token, onError) break } } if (!tagToken) return coll const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg) ) if (!tagName) return coll // Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841 const Coll = coll.constructor as typeof YAMLMap | typeof YAMLSeq if (tagName === '!' || tagName === Coll.tagName) { coll.tag = Coll.tagName return coll } const expType = isMap(coll) ? 'map' : 'seq' let tag = ctx.schema.tags.find( t => t.collection === expType && t.tag === tagName ) as CollectionTag | undefined if (!tag) { const kt = ctx.schema.knownTags[tagName] if (kt && kt.collection === expType) { ctx.schema.tags.push(Object.assign({}, kt, { default: false })) tag = kt } else { onError( tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true ) coll.tag = tagName return coll } } const res = tag.resolve( coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options ) const node = isNode(res) ? (res as ParsedNode) : (new Scalar(res) as Scalar.Parsed) node.range = coll.range node.tag = tagName if (tag?.format) (node as Scalar).format = tag.format return node }
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
72
function composeCollection( CN: ComposeNode, ctx: ComposeContext, token: BlockMap | BlockSequence | FlowCollection, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { let coll: YAMLMap.Parsed | YAMLSeq.Parsed switch (token.type) { case 'block-map': { coll = resolveBlockMap(CN, ctx, token, onError) break } case 'block-seq': { coll = resolveBlockSeq(CN, ctx, token, onError) break } case 'flow-collection': { coll = resolveFlowCollection(CN, ctx, token, onError) break } } if (!tagToken) return coll const tagName = ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg) ) if (!tagName) return coll // Cast needed due to: https://github.com/Microsoft/TypeScript/issues/3841 const Coll = coll.constructor as typeof YAMLMap | typeof YAMLSeq if (tagName === '!' || tagName === Coll.tagName) { coll.tag = Coll.tagName return coll } const expType = isMap(coll) ? 'map' : 'seq' let tag = ctx.schema.tags.find( t => t.collection === expType && t.tag === tagName ) as CollectionTag | undefined if (!tag) { const kt = ctx.schema.knownTags[tagName] if (kt && kt.collection === expType) { ctx.schema.tags.push(Object.assign({}, kt, { default: false })) tag = kt } else { onError( tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, true ) coll.tag = tagName return coll } } const res = tag.resolve( coll, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg), ctx.options ) const node = isNode(res) ? (res as ParsedNode) : (new Scalar(res) as Scalar.Parsed) node.range = coll.range node.tag = tagName if (tag?.format) (node as Scalar).format = tag.format return node }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
73
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor || tag) onError( token, 'ALIAS_PROPS', 'An alias node must not specify any properties' ) break case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': case 'block-scalar': node = composeScalar(ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break case 'block-map': case 'block-seq': case 'flow-collection': node = composeCollection(CN, ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break default: { const message = token.type === 'error' ? token.message : `Unsupported token (type: ${token.type})` onError(token, 'UNEXPECTED_TOKEN', message) node = composeEmptyNode( ctx, token.offset, undefined, null, props, onError ) isSrcToken = false } } if (anchor && node.anchor === '') onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string') if (spaceBefore) node.spaceBefore = true if (comment) { if (token.type === 'scalar' && token.source === '') node.comment = comment else node.commentBefore = comment } // @ts-expect-error Type checking misses meaning of isSrcToken if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token return node }
interface Props { spaceBefore: boolean comment: string anchor: SourceToken | null tag: SourceToken | null end: number }
74
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor || tag) onError( token, 'ALIAS_PROPS', 'An alias node must not specify any properties' ) break case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': case 'block-scalar': node = composeScalar(ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break case 'block-map': case 'block-seq': case 'flow-collection': node = composeCollection(CN, ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break default: { const message = token.type === 'error' ? token.message : `Unsupported token (type: ${token.type})` onError(token, 'UNEXPECTED_TOKEN', message) node = composeEmptyNode( ctx, token.offset, undefined, null, props, onError ) isSrcToken = false } } if (anchor && node.anchor === '') onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string') if (spaceBefore) node.spaceBefore = true if (comment) { if (token.type === 'scalar' && token.source === '') node.comment = comment else node.commentBefore = comment } // @ts-expect-error Type checking misses meaning of isSrcToken if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token return node }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection
75
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor || tag) onError( token, 'ALIAS_PROPS', 'An alias node must not specify any properties' ) break case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': case 'block-scalar': node = composeScalar(ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break case 'block-map': case 'block-seq': case 'flow-collection': node = composeCollection(CN, ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break default: { const message = token.type === 'error' ? token.message : `Unsupported token (type: ${token.type})` onError(token, 'UNEXPECTED_TOKEN', message) node = composeEmptyNode( ctx, token.offset, undefined, null, props, onError ) isSrcToken = false } } if (anchor && node.anchor === '') onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string') if (spaceBefore) node.spaceBefore = true if (comment) { if (token.type === 'scalar' && token.source === '') node.comment = comment else node.commentBefore = comment } // @ts-expect-error Type checking misses meaning of isSrcToken if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token return node }
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
76
function composeNode( ctx: ComposeContext, token: Token, props: Props, onError: ComposeErrorHandler ) { const { spaceBefore, comment, anchor, tag } = props let node: ParsedNode let isSrcToken = true switch (token.type) { case 'alias': node = composeAlias(ctx, token, onError) if (anchor || tag) onError( token, 'ALIAS_PROPS', 'An alias node must not specify any properties' ) break case 'scalar': case 'single-quoted-scalar': case 'double-quoted-scalar': case 'block-scalar': node = composeScalar(ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break case 'block-map': case 'block-seq': case 'flow-collection': node = composeCollection(CN, ctx, token, tag, onError) if (anchor) node.anchor = anchor.source.substring(1) break default: { const message = token.type === 'error' ? token.message : `Unsupported token (type: ${token.type})` onError(token, 'UNEXPECTED_TOKEN', message) node = composeEmptyNode( ctx, token.offset, undefined, null, props, onError ) isSrcToken = false } } if (anchor && node.anchor === '') onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string') if (spaceBefore) node.spaceBefore = true if (comment) { if (token.type === 'scalar' && token.source === '') node.comment = comment else node.commentBefore = comment } // @ts-expect-error Type checking misses meaning of isSrcToken if (ctx.options.keepSourceTokens && isSrcToken) node.srcToken = token return node }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
77
function composeEmptyNode( ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler ) { const token: FlowScalar = { type: 'scalar', offset: emptyScalarPosition(offset, before, pos), indent: -1, source: '' } const node = composeScalar(ctx, token, tag, onError) if (anchor) { node.anchor = anchor.source.substring(1) if (node.anchor === '') onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string') } if (spaceBefore) node.spaceBefore = true if (comment) { node.comment = comment node.range[2] = end } return node }
interface Props { spaceBefore: boolean comment: string anchor: SourceToken | null tag: SourceToken | null end: number }
78
function composeEmptyNode( ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler ) { const token: FlowScalar = { type: 'scalar', offset: emptyScalarPosition(offset, before, pos), indent: -1, source: '' } const node = composeScalar(ctx, token, tag, onError) if (anchor) { node.anchor = anchor.source.substring(1) if (node.anchor === '') onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string') } if (spaceBefore) node.spaceBefore = true if (comment) { node.comment = comment node.range[2] = end } return node }
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
79
function composeEmptyNode( ctx: ComposeContext, offset: number, before: Token[] | undefined, pos: number | null, { spaceBefore, comment, anchor, tag, end }: Props, onError: ComposeErrorHandler ) { const token: FlowScalar = { type: 'scalar', offset: emptyScalarPosition(offset, before, pos), indent: -1, source: '' } const node = composeScalar(ctx, token, tag, onError) if (anchor) { node.anchor = anchor.source.substring(1) if (node.anchor === '') onError(anchor, 'BAD_ALIAS', 'Anchor cannot be an empty string') } if (spaceBefore) node.spaceBefore = true if (comment) { node.comment = comment node.range[2] = end } return node }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
80
function composeAlias( { options }: ComposeContext, { offset, source, end }: FlowScalar, onError: ComposeErrorHandler ) { const alias = new Alias(source.substring(1)) if (alias.source === '') onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string') if (alias.source.endsWith(':')) onError( offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true ) const valueEnd = offset + source.length const re = resolveEnd(end, valueEnd, options.strict, onError) alias.range = [offset, valueEnd, re.offset] if (re.comment) alias.comment = re.comment return alias as Alias.Parsed }
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
81
function composeAlias( { options }: ComposeContext, { offset, source, end }: FlowScalar, onError: ComposeErrorHandler ) { const alias = new Alias(source.substring(1)) if (alias.source === '') onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string') if (alias.source.endsWith(':')) onError( offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true ) const valueEnd = offset + source.length const re = resolveEnd(end, valueEnd, options.strict, onError) alias.range = [offset, valueEnd, re.offset] if (re.comment) alias.comment = re.comment return alias as Alias.Parsed }
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
82
function composeAlias( { options }: ComposeContext, { offset, source, end }: FlowScalar, onError: ComposeErrorHandler ) { const alias = new Alias(source.substring(1)) if (alias.source === '') onError(offset, 'BAD_ALIAS', 'Alias cannot be an empty string') if (alias.source.endsWith(':')) onError( offset + source.length - 1, 'BAD_ALIAS', 'Alias ending in : is ambiguous', true ) const valueEnd = offset + source.length const re = resolveEnd(end, valueEnd, options.strict, onError) alias.range = [offset, valueEnd, re.offset] if (re.comment) alias.comment = re.comment return alias as Alias.Parsed }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
83
function mapIncludes( ctx: ComposeContext, items: Pair<ParsedNode>[], search: ParsedNode ) { const { uniqueKeys } = ctx.options if (uniqueKeys === false) return false const isEqual = typeof uniqueKeys === 'function' ? uniqueKeys : (a: ParsedNode, b: ParsedNode) => a === b || (isScalar(a) && isScalar(b) && a.value === b.value && !(a.value === '<<' && ctx.schema.merge)) return items.some(pair => isEqual(pair.key, search)) }
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
84
function mapIncludes( ctx: ComposeContext, items: Pair<ParsedNode>[], search: ParsedNode ) { const { uniqueKeys } = ctx.options if (uniqueKeys === false) return false const isEqual = typeof uniqueKeys === 'function' ? uniqueKeys : (a: ParsedNode, b: ParsedNode) => a === b || (isScalar(a) && isScalar(b) && a.value === b.value && !(a.value === '<<' && ctx.schema.merge)) return items.some(pair => isEqual(pair.key, search)) }
type ParsedNode = | Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed
85
(a: ParsedNode, b: ParsedNode) => a === b || (isScalar(a) && isScalar(b) && a.value === b.value && !(a.value === '<<' && ctx.schema.merge))
type ParsedNode = | Alias.Parsed | Scalar.Parsed | YAMLMap.Parsed | YAMLSeq.Parsed
86
function resolveFlowScalar( scalar: FlowScalar, strict: boolean, onError: ComposeErrorHandler ): { value: string type: Scalar.PLAIN | Scalar.QUOTE_DOUBLE | Scalar.QUOTE_SINGLE | null comment: string range: Range } { const { offset, type, source, end } = scalar let _type: Scalar.PLAIN | Scalar.QUOTE_DOUBLE | Scalar.QUOTE_SINGLE let value: string const _onError: FlowScalarErrorHandler = (rel, code, msg) => onError(offset + rel, code, msg) switch (type) { case 'scalar': _type = Scalar.PLAIN value = plainValue(source, _onError) break case 'single-quoted-scalar': _type = Scalar.QUOTE_SINGLE value = singleQuotedValue(source, _onError) break case 'double-quoted-scalar': _type = Scalar.QUOTE_DOUBLE value = doubleQuotedValue(source, _onError) break /* istanbul ignore next should not happen */ default: onError( scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}` ) return { value: '', type: null, comment: '', range: [offset, offset + source.length, offset + source.length] } } const valueEnd = offset + source.length const re = resolveEnd(end, valueEnd, strict, onError) return { value, type: _type, comment: re.comment, range: [offset, valueEnd, re.offset] } }
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
87
function resolveFlowScalar( scalar: FlowScalar, strict: boolean, onError: ComposeErrorHandler ): { value: string type: Scalar.PLAIN | Scalar.QUOTE_DOUBLE | Scalar.QUOTE_SINGLE | null comment: string range: Range } { const { offset, type, source, end } = scalar let _type: Scalar.PLAIN | Scalar.QUOTE_DOUBLE | Scalar.QUOTE_SINGLE let value: string const _onError: FlowScalarErrorHandler = (rel, code, msg) => onError(offset + rel, code, msg) switch (type) { case 'scalar': _type = Scalar.PLAIN value = plainValue(source, _onError) break case 'single-quoted-scalar': _type = Scalar.QUOTE_SINGLE value = singleQuotedValue(source, _onError) break case 'double-quoted-scalar': _type = Scalar.QUOTE_DOUBLE value = doubleQuotedValue(source, _onError) break /* istanbul ignore next should not happen */ default: onError( scalar, 'UNEXPECTED_TOKEN', `Expected a flow scalar value, but found: ${type}` ) return { value: '', type: null, comment: '', range: [offset, offset + source.length, offset + source.length] } } const valueEnd = offset + source.length const re = resolveEnd(end, valueEnd, strict, onError) return { value, type: _type, comment: re.comment, range: [offset, valueEnd, re.offset] } }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
88
function composeScalar( ctx: ComposeContext, token: FlowScalar | BlockScalar, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { const { value, type, comment, range } = token.type === 'block-scalar' ? resolveBlockScalar(token, ctx.options.strict, onError) : resolveFlowScalar(token, ctx.options.strict, onError) const tagName = tagToken ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg) ) : null const tag = tagToken && tagName ? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError) : token.type === 'scalar' ? findScalarTagByTest(ctx, value, token, onError) : ctx.schema[SCALAR] let scalar: Scalar try { const res = tag.resolve( value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options ) scalar = isScalar(res) ? res : new Scalar(res) } catch (error) { const msg = error instanceof Error ? error.message : String(error) onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg) scalar = new Scalar(value) } scalar.range = range scalar.source = value if (type) scalar.type = type if (tagName) scalar.tag = tagName if (tag.format) scalar.format = tag.format if (comment) scalar.comment = comment return scalar as Scalar.Parsed }
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
89
function composeScalar( ctx: ComposeContext, token: FlowScalar | BlockScalar, tagToken: SourceToken | null, onError: ComposeErrorHandler ) { const { value, type, comment, range } = token.type === 'block-scalar' ? resolveBlockScalar(token, ctx.options.strict, onError) : resolveFlowScalar(token, ctx.options.strict, onError) const tagName = tagToken ? ctx.directives.tagName(tagToken.source, msg => onError(tagToken, 'TAG_RESOLVE_FAILED', msg) ) : null const tag = tagToken && tagName ? findScalarTagByName(ctx.schema, value, tagName, tagToken, onError) : token.type === 'scalar' ? findScalarTagByTest(ctx, value, token, onError) : ctx.schema[SCALAR] let scalar: Scalar try { const res = tag.resolve( value, msg => onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg), ctx.options ) scalar = isScalar(res) ? res : new Scalar(res) } catch (error) { const msg = error instanceof Error ? error.message : String(error) onError(tagToken ?? token, 'TAG_RESOLVE_FAILED', msg) scalar = new Scalar(value) } scalar.range = range scalar.source = value if (type) scalar.type = type if (tagName) scalar.tag = tagName if (tag.format) scalar.format = tag.format if (comment) scalar.comment = comment return scalar as Scalar.Parsed }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
90
function findScalarTagByName( schema: Schema, value: string, tagName: string, tagToken: SourceToken, onError: ComposeErrorHandler ) { if (tagName === '!') return schema[SCALAR] // non-specific tag const matchWithTest: ScalarTag[] = [] for (const tag of schema.tags) { if (!tag.collection && tag.tag === tagName) { if (tag.default && tag.test) matchWithTest.push(tag) else return tag } } for (const tag of matchWithTest) if (tag.test?.test(value)) return tag const kt = schema.knownTags[tagName] if (kt && !kt.collection) { // Ensure that the known tag is available for stringifying, // but does not get used by default. schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })) return kt } onError( tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str' ) return schema[SCALAR] }
interface SourceToken { 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' offset: number indent: number source: string }
91
function findScalarTagByName( schema: Schema, value: string, tagName: string, tagToken: SourceToken, onError: ComposeErrorHandler ) { if (tagName === '!') return schema[SCALAR] // non-specific tag const matchWithTest: ScalarTag[] = [] for (const tag of schema.tags) { if (!tag.collection && tag.tag === tagName) { if (tag.default && tag.test) matchWithTest.push(tag) else return tag } } for (const tag of matchWithTest) if (tag.test?.test(value)) return tag const kt = schema.knownTags[tagName] if (kt && !kt.collection) { // Ensure that the known tag is available for stringifying, // but does not get used by default. schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })) return kt } onError( tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str' ) return schema[SCALAR] }
class Schema { compat: Array<CollectionTag | ScalarTag> | null knownTags: Record<string, CollectionTag | ScalarTag> merge: boolean name: string sortMapEntries: ((a: Pair, b: Pair) => number) | null tags: Array<CollectionTag | ScalarTag> toStringOptions: Readonly<ToStringOptions> | null; // Used by createNode() and composeScalar() declare readonly [MAP]: CollectionTag; declare readonly [SCALAR]: ScalarTag; declare readonly [SEQ]: CollectionTag constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }: SchemaOptions) { this.compat = Array.isArray(compat) ? getTags(compat, 'compat') : compat ? getTags(null, compat) : null this.merge = !!merge this.name = (typeof schema === 'string' && schema) || 'core' this.knownTags = resolveKnownTags ? coreKnownTags : {} this.tags = getTags(customTags, this.name) this.toStringOptions = toStringDefaults ?? null Object.defineProperty(this, MAP, { value: map }) Object.defineProperty(this, SCALAR, { value: string }) Object.defineProperty(this, SEQ, { value: seq }) // Used by createMap() this.sortMapEntries = typeof sortMapEntries === 'function' ? sortMapEntries : sortMapEntries === true ? sortMapEntriesByKey : null } clone(): Schema { const copy: Schema = Object.create( Schema.prototype, Object.getOwnPropertyDescriptors(this) ) copy.tags = this.tags.slice() return copy } }
92
function findScalarTagByName( schema: Schema, value: string, tagName: string, tagToken: SourceToken, onError: ComposeErrorHandler ) { if (tagName === '!') return schema[SCALAR] // non-specific tag const matchWithTest: ScalarTag[] = [] for (const tag of schema.tags) { if (!tag.collection && tag.tag === tagName) { if (tag.default && tag.test) matchWithTest.push(tag) else return tag } } for (const tag of matchWithTest) if (tag.test?.test(value)) return tag const kt = schema.knownTags[tagName] if (kt && !kt.collection) { // Ensure that the known tag is available for stringifying, // but does not get used by default. schema.tags.push(Object.assign({}, kt, { default: false, test: undefined })) return kt } onError( tagToken, 'TAG_RESOLVE_FAILED', `Unresolved tag: ${tagName}`, tagName !== 'tag:yaml.org,2002:str' ) return schema[SCALAR] }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
93
function findScalarTagByTest( { directives, schema }: ComposeContext, value: string, token: FlowScalar, onError: ComposeErrorHandler ) { const tag = (schema.tags.find( tag => tag.default && tag.test?.test(value) ) as ScalarTag) || schema[SCALAR] if (schema.compat) { const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ?? schema[SCALAR] if (tag.tag !== compat.tag) { const ts = directives.tagString(tag.tag) const cs = directives.tagString(compat.tag) const msg = `Value may be parsed as either ${ts} or ${cs}` onError(token, 'TAG_RESOLVE_FAILED', msg, true) } } return tag }
interface FlowScalar { type: 'alias' | 'scalar' | 'single-quoted-scalar' | 'double-quoted-scalar' offset: number indent: number source: string end?: SourceToken[] }
94
function findScalarTagByTest( { directives, schema }: ComposeContext, value: string, token: FlowScalar, onError: ComposeErrorHandler ) { const tag = (schema.tags.find( tag => tag.default && tag.test?.test(value) ) as ScalarTag) || schema[SCALAR] if (schema.compat) { const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ?? schema[SCALAR] if (tag.tag !== compat.tag) { const ts = directives.tagString(tag.tag) const cs = directives.tagString(compat.tag) const msg = `Value may be parsed as either ${ts} or ${cs}` onError(token, 'TAG_RESOLVE_FAILED', msg, true) } } return tag }
interface ComposeContext { atRoot: boolean directives: Directives options: Readonly<Required<Omit<ParseOptions, 'lineCounter'>>> schema: Readonly<Schema> }
95
function findScalarTagByTest( { directives, schema }: ComposeContext, value: string, token: FlowScalar, onError: ComposeErrorHandler ) { const tag = (schema.tags.find( tag => tag.default && tag.test?.test(value) ) as ScalarTag) || schema[SCALAR] if (schema.compat) { const compat = schema.compat.find(tag => tag.default && tag.test?.test(value)) ?? schema[SCALAR] if (tag.tag !== compat.tag) { const ts = directives.tagString(tag.tag) const cs = directives.tagString(compat.tag) const msg = `Value may be parsed as either ${ts} or ${cs}` onError(token, 'TAG_RESOLVE_FAILED', msg, true) } } return tag }
type ComposeErrorHandler = ( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
96
( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
type ErrorSource = | number | [number, number] | Range | { offset: number; source?: string }
97
( source: ErrorSource, code: ErrorCode, message: string, warning?: boolean ) => void
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'
98
function getErrorPos(src: ErrorSource): [number, number] { if (typeof src === 'number') return [src, src + 1] if (Array.isArray(src)) return src.length === 2 ? src : [src[0], src[1]] const { offset, source } = src return [offset, offset + (typeof source === 'string' ? source.length : 1)] }
type ErrorSource = | number | [number, number] | Range | { offset: number; source?: string }
99
*next(token: Token) { if (process.env.LOG_STREAM) console.dir(token, { depth: null }) switch (token.type) { case 'directive': this.directives.add(token.source, (offset, message, warning) => { const pos = getErrorPos(token) pos[0] += offset this.onError(pos, 'BAD_DIRECTIVE', message, warning) }) this.prelude.push(token.source) this.atDirectives = true break case 'document': { const doc = composeDoc( this.options, this.directives, token, this.onError ) if (this.atDirectives && !doc.directives.docStart) this.onError( token, 'MISSING_CHAR', 'Missing directives-end/doc-start indicator line' ) this.decorate(doc, false) if (this.doc) yield this.doc this.doc = doc this.atDirectives = false break } case 'byte-order-mark': case 'space': break case 'comment': case 'newline': this.prelude.push(token.source) break case 'error': { const msg = token.source ? `${token.message}: ${JSON.stringify(token.source)}` : token.message const error = new YAMLParseError( getErrorPos(token), 'UNEXPECTED_TOKEN', msg ) if (this.atDirectives || !this.doc) this.errors.push(error) else this.doc.errors.push(error) break } case 'doc-end': { if (!this.doc) { const msg = 'Unexpected doc-end without preceding document' this.errors.push( new YAMLParseError(getErrorPos(token), 'UNEXPECTED_TOKEN', msg) ) break } this.doc.directives.docEnd = true const end = resolveEnd( token.end, token.offset + token.source.length, this.doc.options.strict, this.onError ) this.decorate(this.doc, true) if (end.comment) { const dc = this.doc.comment this.doc.comment = dc ? `${dc}\n${end.comment}` : end.comment } this.doc.range[2] = end.offset break } default: this.errors.push( new YAMLParseError( getErrorPos(token), 'UNEXPECTED_TOKEN', `Unsupported token ${token.type}` ) ) } }
type Token = | SourceToken | ErrorToken | Directive | Document | DocumentEnd | FlowScalar | BlockScalar | BlockMap | BlockSequence | FlowCollection