import { parsePipe } from "./parse-pipe" ; import { parseFormat } from "./parse-format" ; import { RMSwatch , parseSwatchStr } from "./get-swatch" ; import { err } from "./log" ; interface variableParsersReturn { error ? : string ; str ? : string ; rgb ? : number [ ] ; } export class RMParser { palette : RMSwatch [ ] ; readonly delimiter : string [ ] ; readonly delimiterRegExp : RegExp ; constructor ( palette , delimiter = [ "\\^r" , "\\^" ] ) { this . palette = palette ; this . delimiter = delimiter ; this . delimiterRegExp = new RegExp ( delimiter [ 0 ] + "(.*?)" + delimiter [ 1 ] , "g" ) ; } parseFile ( file ) { return file . replace ( this . delimiterRegExp , ( _match , capture ) : any => { const result = this . variableParser ( capture ) ; if ( result . error ) err ( result . error ) ; if ( result . str ) return result . str ; return process . exit ( 1 ) ; } ) ; } addSwatch ( ... swatch ) { this . palette . push ( ... swatch ) ; } variableParser ( str , outputString = true ) { let color = parseSwatchStr ( str , this . palette ) ; if ( ! color ) return { error : `Invalid swatch name ${ str }` } ; color = parsePipe ( str , color ) ; if ( ! outputString ) return { rgb : color . rgb ( ) . array ( ) } ; return { str : parseFormat ( str , color ) } ; } }