import { IPipe } from '../IPipe' ; export class InlinePowerShell implements IPipe { public readonly name : string = 'inlinePowerShell' ; public apply ( code ) { if ( ! code || ! hasLines ( code ) ) { return code ; } const processor = new Array < ( data : string ) => string > ( ... [ inlineComments , mergeLinesWithBacktick , mergeHereStrings , mergeNewLines , ] ) . reduce ( ( a , b ) => ( data ) => b ( a ( data ) ) ) ; const newCode = processor ( code ) ; return newCode ; } } function hasLines ( text ) { return text . includes ( '\n' ) || text . includes ( '\r' ) ; } function inlineComments ( code ) { const makeInlineComment = ( comment ) => { const value = comment ?. trim ( ) ; if ( ! value ) { return '<##>' ; } return `<# ${ value } #>` ; } ; return code . replaceAll ( /<#.*?#>|#(.*)/g , ( match , captureComment ) => { if ( captureComment === undefined ) { return match ; } return makeInlineComment ( captureComment ) ; } ) ; } function getLines ( code ) { return ( code ?. split ( /\r\n|\r|\n/ ) || [ ] ) ; } function mergeHereStrings ( code ) { const regex = /@(['"])\s*(?:\r\n|\r|\n)((.|\n|\r)+?)(\r\n|\r|\n)\1@/g ; return code . replaceAll ( regex , ( _$ , quotes , scope ) => { const newString = getHereStringHandler ( quotes ) ; const escaped = scope . replaceAll ( quotes , newString . escapedQuotes ) ; const lines = getLines ( escaped ) ; const inlined = lines . join ( newString . separator ) ; const quoted = `${ newString . quotesAround }${ inlined }${ newString . quotesAround }` ; return quoted ; } ) ; } interface IInlinedHereString { readonly quotesAround : string ; readonly escapedQuotes : string ; readonly separator : string ; } function getHereStringHandler ( quotes ) { const expandableNewLine = '`r`n' ; switch ( quotes ) { case '\'' : return { quotesAround : '\'' , escapedQuotes : '\'\'' , separator : `'+"${ expandableNewLine }"+'` , } ; case '"' : return { quotesAround : '"' , escapedQuotes : '`"' , separator : expandableNewLine , } ; default : throw new Error ( `expected quotes: ${ quotes }` ) ; } } function mergeLinesWithBacktick ( code ) { return code . replaceAll ( / +`\s*(?:\r\n|\r|\n)\s*/g , ' ' ) ; } function mergeNewLines ( code ) { return getLines ( code ) . map ( ( line ) => line . trim ( ) ) . filter ( ( line ) => line . length > 0 ) . join ( '; ' ) ; }