import * as vscode from 'vscode' ; import { parse , findNodeAtPosition } from 'node-yaml-parser' ; export function isMapping ( node ) { return node . kind === 'MAPPING' ; } export function isSequence ( node ) { return node . kind === 'SEQ' ; } export function isMappingItem ( node ) { return node . kind === 'PAIR' ; } export interface YamlNode { readonly kind : string ; readonly raw : string ; readonly startPosition : number ; readonly endPosition : number ; readonly parent ? : YamlNode ; } export interface YamlMappingItem extends YamlNode { readonly key : YamlNode ; readonly value : YamlNode ; } export interface YamlMap extends YamlNode { readonly mappings : YamlMappingItem [ ] ; } export interface YamlSequence extends YamlNode { readonly items : YamlNode [ ] ; } export interface YamlDocument { readonly nodes : YamlNode [ ] ; readonly errors : string [ ] ; } export interface YamlCachedDocuments { yamlDocs : YamlDocument [ ] ; lineLengths : number [ ] ; version : number ; } export interface YamlMatchedElement { readonly matchedNode : YamlNode ; readonly matchedDocument : YamlDocument ; } /**
 * A yaml interpreter parse the yaml text and find the matched ast node from vscode location.
 */ export class YamlLocator { private cache : { [ key ] : YamlCachedDocuments ; } = { } ; param { vscode . TextDocument } textDocument param { vscode . Position } pos returns { YamlMatchedElement } public getMatchedElement ( textDocument , pos ) { const key = textDocument . uri . toString ( ) ; this . ensureCache ( key , textDocument ) ; const cacheEntry = this . cache [ key ] ; if ( ! cacheEntry ) { return undefined ; } return findNodeAtPosition ( cacheEntry . yamlDocs , cacheEntry . lineLengths , pos . line , pos . character ) ; } param { vscode . TextDocument } textDocument param { vscode . Position } pos returns { YamlMatchedElement } public getYamlDocuments ( textDocument ) { const key = textDocument . uri . toString ( ) ; this . ensureCache ( key , textDocument ) ; if ( ! this . cache [ key ] ) { return [ ] ; } return this . cache [ key ] . yamlDocs ? this . cache [ key ] . yamlDocs : [ ] ; } private ensureCache ( key , textDocument ) { if ( ! this . cache [ key ] ) { this . cache [ key ] = < YamlCachedDocuments > { version : - 1 } ; } if ( this . cache [ key ] . version !== textDocument . version ) { try { const { documents , lineLengths } = parse ( textDocument . getText ( ) ) ; this . cache [ key ] . yamlDocs = documents ; this . cache [ key ] . lineLengths = lineLengths ; this . cache [ key ] . version = textDocument . version ; } catch ( err ) { delete this . cache [ key ] ; } } } } const yamlLocator = new YamlLocator ( ) ; export { yamlLocator } ;