Input: Retrieves the { @link fs . Stats } for the target of the given symlink . If the symlink is broken then the Stats of the symlink itself are returned . [CODESPLIT] function symlinkStat ( fs , path , lstats , callback ) { call . safe ( fs . stat , path , ( err , stats ) => { if ( err ) { // The symlink is broken, so return the stats for the link itself return callback ( null , lstats ) ; } try { // Return the stats for the resolved symlink target, // and override the `isSymbolicLink` method to indicate that it's a symlink stats . isSymbolicLink = ( ) => true ; } catch ( err2 ) { // Setting stats.isSymbolicLink threw an error // (probably because fs.stat returned an invalid result) return callback ( err2 ) ; } callback ( null , stats ) ; } ) ; }


Input: Returns the { @link stream . Readable } of an asynchronous { @link DirectoryReader } . [CODESPLIT] function readdirStream ( dir , options , internalOptions ) { internalOptions . facade = streamFacade ; let reader = new DirectoryReader ( dir , options , internalOptions ) ; return reader . stream ; }


Input: A facade that allows { @link Array . forEach } to be called as though it were asynchronous . [CODESPLIT] function syncForEach ( array , iterator , done ) { array . forEach ( item => { iterator ( item , ( ) => { // Note: No error-handling here because this is currently only ever called // by DirectoryReader, which never passes an `error` parameter to the callback. // Instead, DirectoryReader emits an "error" event if an error occurs. } ) ; } ) ; done ( ) ; }


Input: Returns the buffered output from a synchronous { @link DirectoryReader } . [CODESPLIT] function readdirSync ( dir , options , internalOptions ) { internalOptions . facade = syncFacade ; let reader = new DirectoryReader ( dir , options , internalOptions ) ; let stream = reader . stream ; let results = [ ] ; let data = stream . read ( ) ; while ( data !== null ) { results . push ( data ) ; data = stream . read ( ) ; } return results ; }


Input: Asynchronous API . [CODESPLIT] function stat ( path , opts ) { return new Promise ( ( resolve , reject ) => { statProvider . async ( path , optionsManager . prepare ( opts ) , ( err , stats ) => err ? reject ( err ) : resolve ( stats ) ) ; } ) ; }


Input: there s 3 implementations written in increasing order of efficiency 1 - no Set type is defined [CODESPLIT] function uniqNoSet ( arr ) { var ret = [ ] ; for ( var i = 0 ; i < arr . length ; i ++ ) { if ( ret . indexOf ( arr [ i ] ) === - 1 ) { ret . push ( arr [ i ] ) ; } } return ret ; }


Input: 3 - a standard Set type is defined and it has a forEach method [CODESPLIT] function uniqSetWithForEach ( arr ) { var ret = [ ] ; ( new Set ( arr ) ) . forEach ( function ( el ) { ret . push ( el ) ; } ) ; return ret ; }


Input: V8 currently has a broken implementation https : // github . com / joyent / node / issues / 8449 [CODESPLIT] function doesForEachActuallyWork ( ) { var ret = false ; ( new Set ( [ true ] ) ) . forEach ( function ( el ) { ret = el ; } ) ; return ret === true ; }


Input: Create an instance of Base with the given config and options . [CODESPLIT] function Base ( config , options ) { if ( ! ( this instanceof Base ) ) { return new Base ( config , options ) ; } Cache . call ( this , config ) ; this . is ( 'base' ) ; this . initBase ( config , options ) ; }


Input: Convert the given braces pattern into a regex - compatible string . By default only one string is generated for every input string . Set options . expand to true to return an array of patterns ( similar to Bash or minimatch . Before using options . expand it s recommended that you read the [ performance notes ] ( #performance )) . [CODESPLIT] function braces ( pattern , options ) { var key = utils . createKey ( String ( pattern ) , options ) ; var arr = [ ] ; var disabled = options && options . cache === false ; if ( ! disabled && cache . hasOwnProperty ( key ) ) { return cache [ key ] ; } if ( Array . isArray ( pattern ) ) { for ( var i = 0 ; i < pattern . length ; i ++ ) { arr . push . apply ( arr , braces . create ( pattern [ i ] , options ) ) ; } } else { arr = braces . create ( pattern , options ) ; } if ( options && options . nodupes === true ) { arr = unique ( arr ) ; } if ( ! disabled ) { cache [ key ] = arr ; } return arr ; }


Input: Memoize a generated regex or function . A unique key is generated from the method name pattern and user - defined options . Set options . memoize to false to disable . [CODESPLIT] function memoize ( type , pattern , options , fn ) { var key = utils . createKey ( type + ':' + pattern , options ) ; var disabled = options && options . cache === false ; if ( disabled ) { braces . clearCache ( ) ; return fn ( pattern , options ) ; } if ( cache . hasOwnProperty ( key ) ) { return cache [ key ] ; } var res = fn ( pattern , options ) ; cache [ key ] = res ; return res ; }


Input: Multiply the segments in the current brace level [CODESPLIT] function multiply ( queue , n , options ) { return utils . flatten ( utils . repeat ( utils . arrayify ( queue ) , n ) ) ; }


Input: Returns true if regex parens should be used for sets . If the parent type is not brace then we re on a root node which means we should never expand segments and open / close braces should be {} ( since this indicates a brace is missing from the set ) [CODESPLIT] function isOptimized ( node , options ) { if ( node . parent . isOptimized ) return true ; return isType ( node . parent , 'brace' ) && ! isEscaped ( node . parent ) && options . expand !== true ; }


Input: Returns true if the given node does not have an inner value . [CODESPLIT] function noInner ( node , type ) { if ( node . parent . queue . length === 1 ) { return true ; } var nodes = node . parent . nodes ; return nodes . length === 3 && isType ( nodes [ 0 ] , 'brace.open' ) && ! isType ( nodes [ 1 ] , 'text' ) && isType ( nodes [ 2 ] , 'brace.close' ) ; }


Input: Combine text nodes and calculate empty sets ( { } ) [CODESPLIT] function concatNodes ( pos , node , parent , options ) { node . orig = node . val ; var prev = this . prev ( ) ; var last = utils . last ( prev . nodes ) ; var isEscaped = false ; if ( node . val . length > 1 ) { var a = node . val . charAt ( 0 ) ; var b = node . val . slice ( - 1 ) ; isEscaped = ( a === '"' && b === '"' ) || ( a === "'" && b === "'" ) || ( a === '`' && b === '`' ) ; } if ( isEscaped && options . unescape !== false ) { node . val = node . val . slice ( 1 , node . val . length - 1 ) ; node . escaped = true ; } if ( node . match ) { var match = node . match [ 1 ] ; if ( ! match || match . indexOf ( '}' ) === - 1 ) { match = node . match [ 0 ] ; } // replace each set with a single "," var val = match . replace ( / \{ / g , ',' ) . replace ( / \} / g , '' ) ; node . multiplier *= val . length ; node . val = '' ; } var simpleText = last . type === 'text' && last . multiplier === 1 && node . multiplier === 1 && node . val ; if ( simpleText ) { last . val += node . val ; return ; } prev . push ( node ) ; }


Input: Enables a debug mode by namespaces . This can include modes separated by a colon and wildcards . [CODESPLIT] function enable ( namespaces ) { exports . save ( namespaces ) ; exports . names = [ ] ; exports . skips = [ ] ; var i ; var split = ( typeof namespaces === 'string' ? namespaces : '' ) . split ( / [\s,]+ / ) ; var len = split . length ; for ( i = 0 ; i < len ; i ++ ) { if ( ! split [ i ] ) continue ; // ignore empty strings namespaces = split [ i ] . replace ( / \* / g , '.*?' ) ; if ( namespaces [ 0 ] === '-' ) { exports . skips . push ( new RegExp ( '^' + namespaces . substr ( 1 ) + '$' ) ) ; } else { exports . names . push ( new RegExp ( '^' + namespaces + '$' ) ) ; } } for ( i = 0 ; i < exports . instances . length ; i ++ ) { var instance = exports . instances [ i ] ; instance . enabled = exports . enabled ( instance . namespace ) ; } }


Input: Parses the given POSIX character class pattern and returns a string that can be used for creating regular expressions for matching . [CODESPLIT] function brackets ( pattern , options ) { debug ( 'initializing from <%s>' , __filename ) ; var res = brackets . create ( pattern , options ) ; return res . output ; }


Input:
Brackets parsers [CODESPLIT] function parsers ( brackets ) { brackets . state = brackets . state || { } ; brackets . parser . sets . bracket = brackets . parser . sets . bracket || [ ] ; brackets . parser . capture ( 'escape' , function ( ) { if ( this . isInside ( 'bracket' ) ) return ; var pos = this . position ( ) ; var m = this . match ( / ^\\(.) / ) ; if ( ! m ) return ; return pos ( { type : 'escape' , val : m [ 0 ] } ) ; } ) /**
     * Text parser
     */ . capture ( 'text' , function ( ) { if ( this . isInside ( 'bracket' ) ) return ; var pos = this . position ( ) ; var m = this . match ( not ) ; if ( ! m || ! m [ 0 ] ) return ; return pos ( { type : 'text' , val : m [ 0 ] } ) ; } ) /**
     * POSIX character classes: "[[:alpha:][:digits:]]"
     */ . capture ( 'posix' , function ( ) { var pos = this . position ( ) ; var m = this . match ( / ^\[:(.*?):\](?=.*\]) / ) ; if ( ! m ) return ; var inside = this . isInside ( 'bracket' ) ; if ( inside ) { brackets . posix ++ ; } return pos ( { type : 'posix' , insideBracket : inside , inner : m [ 1 ] , val : m [ 0 ] } ) ; } ) /**
     * Bracket (noop)
     */ . capture ( 'bracket' , function ( ) { } ) /**
     * Open: '['
     */ . capture ( 'bracket.open' , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( / ^\[(?=.*\]) / ) ; if ( ! m ) return ; var prev = this . prev ( ) ; var last = utils . last ( prev . nodes ) ; if ( parsed . slice ( - 1 ) === '\\' && ! this . isInside ( 'bracket' ) ) { last . val = last . val . slice ( 0 , last . val . length - 1 ) ; return pos ( { type : 'escape' , val : m [ 0 ] } ) ; } var open = pos ( { type : 'bracket.open' , val : m [ 0 ] } ) ; if ( last . type === 'bracket.open' || this . isInside ( 'bracket' ) ) { open . val = '\\' + open . val ; open . type = 'bracket.inner' ; open . escaped = true ; return open ; } var node = pos ( { type : 'bracket' , nodes : [ open ] } ) ; define ( node , 'parent' , prev ) ; define ( open , 'parent' , node ) ; this . push ( 'bracket' , node ) ; prev . nodes . push ( node ) ; } ) /**
     * Bracket text
     */ . capture ( 'bracket.inner' , function ( ) { if ( ! this . isInside ( 'bracket' ) ) return ; var pos = this . position ( ) ; var m = this . match ( not ) ; if ( ! m || ! m [ 0 ] ) return ; var next = this . input . charAt ( 0 ) ; var val = m [ 0 ] ; var node = pos ( { type : 'bracket.inner' , val : val } ) ; if ( val === '\\\\' ) { return node ; } var first = val . charAt ( 0 ) ; var last = val . slice ( - 1 ) ; if ( first === '!' ) { val = '^' + val . slice ( 1 ) ; } if ( last === '\\' || ( val === '^' && next === ']' ) ) { val += this . input [ 0 ] ; this . consume ( 1 ) ; } node . val = val ; return node ; } ) /**
     * Close: ']'
     */ . capture ( 'bracket.close' , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( / ^\] / ) ; if ( ! m ) return ; var prev = this . prev ( ) ; var last = utils . last ( prev . nodes ) ; if ( parsed . slice ( - 1 ) === '\\' && ! this . isInside ( 'bracket' ) ) { last . val = last . val . slice ( 0 , last . val . length - 1 ) ; return pos ( { type : 'escape' , val : m [ 0 ] } ) ; } var node = pos ( { type : 'bracket.close' , rest : this . input , val : m [ 0 ] } ) ; if ( last . type === 'bracket.open' ) { node . type = 'bracket.inner' ; node . escaped = true ; return node ; } var bracket = this . pop ( 'bracket' ) ; if ( ! this . isType ( bracket , 'bracket' ) ) { if ( this . options . strict ) { throw new Error ( 'missing opening "["' ) ; } node . type = 'bracket.inner' ; node . escaped = true ; return node ; } bracket . nodes . push ( node ) ; define ( node , 'parent' , bracket ) ; } ) ; }


Input: Return a range of numbers or letters . [CODESPLIT] function fillRange ( a , b , step , options , fn ) { if ( a == null || b == null ) { throw new Error ( 'fill-range expects the first and second args to be strings.' ) ; } if ( typeof step === 'function' ) { fn = step ; options = { } ; step = null ; } if ( typeof options === 'function' ) { fn = options ; options = { } ; } if ( isObject ( step ) ) { options = step ; step = '' ; } var expand , regex = false , sep = '' ; var opts = options || { } ; if ( typeof opts . silent === 'undefined' ) { opts . silent = true ; } step = step || opts . step ; // store a ref to unmodified arg var origA = a , origB = b ; b = ( b . toString ( ) === '-0' ) ? 0 : b ; if ( opts . optimize || opts . makeRe ) { step = step ? ( step += '~' ) : step ; expand = true ; regex = true ; sep = '~' ; } // handle special step characters if ( typeof step === 'string' ) { var match = stepRe ( ) . exec ( step ) ; if ( match ) { var i = match . index ; var m = match [ 0 ] ; // repeat string if ( m === '+' ) { return repeat ( a , b ) ; // randomize a, `b` times } else if ( m === '?' ) { return [ randomize ( a , b ) ] ; // expand right, no regex reduction } else if ( m === '>' ) { step = step . substr ( 0 , i ) + step . substr ( i + 1 ) ; expand = true ; // expand to an array, or if valid create a reduced // string for a regex logic `or` } else if ( m === '|' ) { step = step . substr ( 0 , i ) + step . substr ( i + 1 ) ; expand = true ; regex = true ; sep = m ; // expand to an array, or if valid create a reduced // string for a regex range } else if ( m === '~' ) { step = step . substr ( 0 , i ) + step . substr ( i + 1 ) ; expand = true ; regex = true ; sep = m ; } } else if ( ! isNumber ( step ) ) { if ( ! opts . silent ) { throw new TypeError ( 'fill-range: invalid step.' ) ; } return null ; } } if ( / [.&*()[\]^%$#@!] / . test ( a ) || / [.&*()[\]^%$#@!] / . test ( b ) ) { if ( ! opts . silent ) { throw new RangeError ( 'fill-range: invalid range arguments.' ) ; } return null ; } // has neither a letter nor number, or has both letters and numbers // this needs to be after the step logic if ( ! noAlphaNum ( a ) || ! noAlphaNum ( b ) || hasBoth ( a ) || hasBoth ( b ) ) { if ( ! opts . silent ) { throw new RangeError ( 'fill-range: invalid range arguments.' ) ; } return null ; } // validate arguments var isNumA = isNumber ( zeros ( a ) ) ; var isNumB = isNumber ( zeros ( b ) ) ; if ( ( ! isNumA && isNumB ) || ( isNumA && ! isNumB ) ) { if ( ! opts . silent ) { throw new TypeError ( 'fill-range: first range argument is incompatible with second.' ) ; } return null ; } // by this point both are the same, so we // can use A to check going forward. var isNum = isNumA ; var num = formatStep ( step ) ; // is the range alphabetical? or numeric? if ( isNum ) { // if numeric, coerce to an integer a = + a ; b = + b ; } else { // otherwise, get the charCode to expand alpha ranges a = a . charCodeAt ( 0 ) ; b = b . charCodeAt ( 0 ) ; } // is the pattern descending? var isDescending = a > b ; // don't create a character class if the args are < 0 if ( a < 0 || b < 0 ) { expand = false ; regex = false ; } // detect padding var padding = isPadded ( origA , origB ) ; var res , pad , arr = [ ] ; var ii = 0 ; // character classes, ranges and logical `or` if ( regex ) { if ( shouldExpand ( a , b , num , isNum , padding , opts ) ) { // make sure the correct separator is used if ( sep === '|' || sep === '~' ) { sep = detectSeparator ( a , b , num , isNum , isDescending ) ; } return wrap ( [ origA , origB ] , sep , opts ) ; } } while ( isDescending ? ( a >= b ) : ( a <= b ) ) { if ( padding && isNum ) { pad = padding ( a ) ; } // custom function if ( typeof fn === 'function' ) { res = fn ( a , isNum , pad , ii ++ ) ; // letters } else if ( ! isNum ) { if ( regex && isInvalidChar ( a ) ) { res = null ; } else { res = String . fromCharCode ( a ) ; } // numbers } else { res = formatPadding ( a , pad ) ; } // add result to the array, filtering any nulled values if ( res !== null ) arr . push ( res ) ; // increment or decrement if ( isDescending ) { a -= num ; } else { a += num ; } } // now that the array is expanded, we need to handle regex // character classes, ranges or logical `or` that wasn't // already handled before the loop if ( ( regex || expand ) && ! opts . noexpand ) { // make sure the correct separator is used if ( sep === '|' || sep === '~' ) { sep = detectSeparator ( a , b , num , isNum , isDescending ) ; } if ( arr . length === 1 || a < 0 || b < 0 ) { return arr ; } return wrap ( arr , sep , opts ) ; } return arr ; }


Input: Wrap the string with the correct regex syntax . [CODESPLIT] function wrap ( arr , sep , opts ) { if ( sep === '~' ) { sep = '-' ; } var str = arr . join ( sep ) ; var pre = opts && opts . regexPrefix ; // regex logical `or` if ( sep === '|' ) { str = pre ? pre + str : str ; str = '(' + str + ')' ; } // regex character class if ( sep === '-' ) { str = ( pre && pre === '^' ) ? pre + str : str ; str = '[' + str + ']' ; } return [ str ] ; }


Input: Check for invalid characters [CODESPLIT] function isCharClass ( a , b , step , isNum , isDescending ) { if ( isDescending ) { return false ; } if ( isNum ) { return a <= 9 && b <= 9 ; } if ( a < b ) { return step === 1 ; } return false ; }


Input: Detect the correct separator to use [CODESPLIT] function shouldExpand ( a , b , num , isNum , padding , opts ) { if ( isNum && ( a > 9 || b > 9 ) ) { return false ; } return ! padding && num === 1 && a < b ; }


Input: Detect the correct separator to use [CODESPLIT] function detectSeparator ( a , b , step , isNum , isDescending ) { var isChar = isCharClass ( a , b , step , isNum , isDescending ) ; if ( ! isChar ) { return '|' ; } return '~' ; }


Input: Format padding taking leading - into account [CODESPLIT] function formatPadding ( ch , pad ) { var res = pad ? pad + ch : ch ; if ( pad && ch . toString ( ) . charAt ( 0 ) === '-' ) { res = '-' + pad + ch . toString ( ) . substr ( 1 ) ; } return res . toString ( ) ; }


Input: Check for invalid characters [CODESPLIT] function isInvalidChar ( str ) { var ch = toStr ( str ) ; return ch === '\\' || ch === '[' || ch === ']' || ch === '^' || ch === '(' || ch === ')' || ch === '`' ; }


Input: If the string is padded returns a curried function with the a cached padding string or false if no padding . [CODESPLIT] function isPadded ( origA , origB ) { if ( hasZeros ( origA ) || hasZeros ( origB ) ) { var alen = length ( origA ) ; var blen = length ( origB ) ; var len = alen >= blen ? alen : blen ; return function ( a ) { return repeatStr ( '0' , len - length ( a ) ) ; } ; } return false ; }


Input:
Customize Snapdragon parser and renderer [CODESPLIT] function Extglob ( options ) { this . options = extend ( { source : 'extglob' } , options ) ; this . snapdragon = this . options . snapdragon || new Snapdragon ( this . options ) ; this . snapdragon . patterns = this . snapdragon . patterns || { } ; this . compiler = this . snapdragon . compiler ; this . parser = this . snapdragon . parser ; compilers ( this . snapdragon ) ; parsers ( this . snapdragon ) ; /**
   * Override Snapdragon `.parse` method
   */ define ( this . snapdragon , 'parse' , function ( str , options ) { var parsed = Snapdragon . prototype . parse . apply ( this , arguments ) ; parsed . input = str ; // escape unmatched brace/bracket/parens var last = this . parser . stack . pop ( ) ; if ( last && this . options . strict !== true ) { var node = last . nodes [ 0 ] ; node . val = '\\' + node . val ; var sibling = node . parent . nodes [ 1 ] ; if ( sibling . type === 'star' ) { sibling . loose = true ; } } // add non-enumerable parser reference define ( parsed , 'parser' , this . parser ) ; return parsed ; } ) ; /**
   * Decorate `.parse` method
   */ define ( this , 'parse' , function ( ast , options ) { return this . snapdragon . parse . apply ( this . snapdragon , arguments ) ; } ) ; /**
   * Decorate `.compile` method
   */ define ( this , 'compile' , function ( ast , options ) { return this . snapdragon . compile . apply ( this . snapdragon , arguments ) ; } ) ; }


Input: The main function takes a list of strings and one or more glob patterns to use for matching . [CODESPLIT] function micromatch ( list , patterns , options ) { patterns = utils . arrayify ( patterns ) ; list = utils . arrayify ( list ) ; var len = patterns . length ; if ( list . length === 0 || len === 0 ) { return [ ] ; } if ( len === 1 ) { return micromatch . match ( list , patterns [ 0 ] , options ) ; } var omit = [ ] ; var keep = [ ] ; var idx = - 1 ; while ( ++ idx < len ) { var pattern = patterns [ idx ] ; if ( typeof pattern === 'string' && pattern . charCodeAt ( 0 ) === 33 /* ! */ ) { omit . push . apply ( omit , micromatch . match ( list , pattern . slice ( 1 ) , options ) ) ; } else { keep . push . apply ( keep , micromatch . match ( list , pattern , options ) ) ; } } var matches = utils . diff ( keep , omit ) ; if ( ! options || options . nodupes !== false ) { return utils . unique ( matches ) ; } return matches ; }


Input: Memoize a generated regex or function . A unique key is generated from the type ( usually method name ) the pattern and user - defined options . [CODESPLIT] function memoize ( type , pattern , options , fn ) { var key = utils . createKey ( type + '=' + pattern , options ) ; if ( options && options . cache === false ) { return fn ( pattern , options ) ; } if ( cache . has ( type , key ) ) { return cache . get ( type , key ) ; } var val = fn ( pattern , options ) ; cache . set ( type , key , val ) ; return val ; }


Input: Visit node with the given fn [CODESPLIT] function visit ( node , fn ) { return node . nodes ? mapVisit ( node . nodes , fn ) : fn ( node ) ; }


Input: Map visit over array of nodes . [CODESPLIT] function mapVisit ( nodes , fn ) { var len = nodes . length ; var idx = - 1 ; while ( ++ idx < len ) { visit ( nodes [ idx ] , fn ) ; } }


Input: Create text regex [CODESPLIT] function textRegex ( pattern ) { var notStr = regexNot . create ( pattern , { contains : true , strictClose : false } ) ; var prefix = '(?:[\\^]|\\\\|' ; return toRegex ( prefix + notStr + ')' , { strictClose : false } ) ; }


Input: Synchronous API . [CODESPLIT] function sync ( source , opts ) { var works = getWorks ( source , reader_sync_1 . default , opts ) ; return arrayUtils . flatten ( works ) ; }


Input: Asynchronous API . [CODESPLIT] function async ( source , opts ) { var works = getWorks ( source , reader_async_1 . default , opts ) ; return Promise . all ( works ) . then ( arrayUtils . flatten ) ; }


Input: Stream API . [CODESPLIT] function stream ( source , opts ) { var works = getWorks ( source , reader_stream_1 . default , opts ) ; return merge2 ( works ) ; }


Input: Return a set of tasks based on provided patterns . [CODESPLIT] function generateTasks ( source , opts ) { var patterns = [ ] . concat ( source ) ; var options = optionsManager . prepare ( opts ) ; return taskManager . generate ( patterns , options ) ; }


Input: Returns a set of works based on provided tasks and class of the reader . [CODESPLIT] function getWorks ( source , _Reader , opts ) { var patterns = [ ] . concat ( source ) ; var options = optionsManager . prepare ( opts ) ; var tasks = taskManager . generate ( patterns , options ) ; var reader = new _Reader ( options ) ; return tasks . map ( reader . read , reader ) ; }


Input: Generate tasks based on parent directory of each pattern . [CODESPLIT] function generate ( patterns , options ) { var unixPatterns = patterns . map ( patternUtils . unixifyPattern ) ; var unixIgnore = options . ignore . map ( patternUtils . unixifyPattern ) ; var positivePatterns = getPositivePatterns ( unixPatterns ) ; var negativePatterns = getNegativePatternsAsPositive ( unixPatterns , unixIgnore ) ; var staticPatterns = positivePatterns . filter ( patternUtils . isStaticPattern ) ; var dynamicPatterns = positivePatterns . filter ( patternUtils . isDynamicPattern ) ; var staticTasks = convertPatternsToTasks ( staticPatterns , negativePatterns , /* dynamic */ false ) ; var dynamicTasks = convertPatternsToTasks ( dynamicPatterns , negativePatterns , /* dynamic */ true ) ; return staticTasks . concat ( dynamicTasks ) ; }


Input: Convert patterns to tasks based on parent directory of each pattern . [CODESPLIT] function convertPatternsToTasks ( positive , negative , dynamic ) { var positivePatternsGroup = groupPatternsByBaseDirectory ( positive ) ; var negativePatternsGroup = groupPatternsByBaseDirectory ( negative ) ; // When we have a global group – there is no reason to divide the patterns into independent tasks. // In this case, the global task covers the rest. if ( '.' in positivePatternsGroup ) { var task = convertPatternGroupToTask ( '.' , positive , negative , dynamic ) ; return [ task ] ; } return convertPatternGroupsToTasks ( positivePatternsGroup , negativePatternsGroup , dynamic ) ; }


Input: Return only negative patterns . [CODESPLIT] function getNegativePatternsAsPositive ( patterns , ignore ) { var negative = patternUtils . getNegativePatterns ( patterns ) . concat ( ignore ) ; var positive = negative . map ( patternUtils . convertToPositivePattern ) ; return positive ; }


Input: Group patterns by base directory of each pattern . [CODESPLIT] function groupPatternsByBaseDirectory ( patterns ) { return patterns . reduce ( function ( collection , pattern ) { var base = patternUtils . getBaseDirectory ( pattern ) ; if ( base in collection ) { collection [ base ] . push ( pattern ) ; } else { collection [ base ] = [ pattern ] ; } return collection ; } , { } ) ; }


Input: Convert group of patterns to tasks . [CODESPLIT] function convertPatternGroupsToTasks ( positive , negative , dynamic ) { var globalNegative = '.' in negative ? negative [ '.' ] : [ ] ; return Object . keys ( positive ) . map ( function ( base ) { var localNegative = findLocalNegativePatterns ( base , negative ) ; var fullNegative = localNegative . concat ( globalNegative ) ; return convertPatternGroupToTask ( base , positive [ base ] , fullNegative , dynamic ) ; } ) ; }


Input: Returns those negative patterns whose base paths includes positive base path . [CODESPLIT] function findLocalNegativePatterns ( positiveBase , negative ) { return Object . keys ( negative ) . reduce ( function ( collection , base ) { if ( base . startsWith ( positiveBase ) ) { collection . push . apply ( collection , __spread ( negative [ base ] ) ) ; } return collection ; } , [ ] ) ; }


Input: Create a task for positive and negative patterns . [CODESPLIT] function convertPatternGroupToTask ( base , positive , negative , dynamic ) { return { base : base , dynamic : dynamic , patterns : [ ] . concat ( positive , negative . map ( patternUtils . convertToNegativePattern ) ) , positive : positive , negative : negative } ; }


Input: Returns «true» when pattern ends with a slash and globstar or the last partial of the pattern is static pattern . [CODESPLIT] function isAffectDepthOfReadingPattern ( pattern ) { var basename = path . basename ( pattern ) ; return endsWithSlashGlobStar ( pattern ) || isStaticPattern ( basename ) ; }


Input: Returns true if the entry match any of the given RegExp s . [CODESPLIT] function matchAny ( entry , patternsRe ) { try { for ( var patternsRe_1 = __values ( patternsRe ) , patternsRe_1_1 = patternsRe_1 . next ( ) ; ! patternsRe_1_1 . done ; patternsRe_1_1 = patternsRe_1 . next ( ) ) { var regexp = patternsRe_1_1 . value ; if ( regexp . test ( entry ) ) { return true ; } } } catch ( e_1_1 ) { e_1 = { error : e_1_1 } ; } finally { try { if ( patternsRe_1_1 && ! patternsRe_1_1 . done && ( _a = patternsRe_1 . return ) ) _a . call ( patternsRe_1 ) ; } finally { if ( e_1 ) throw e_1 . error ; } } return false ; var e_1 , _a ; }


Input: Sync the files and persist them to the cache [CODESPLIT] function ( ) { removeNotFoundFiles ( ) ; var entries = normalizedEntries ; var keys = Object . keys ( entries ) ; if ( keys . length === 0 ) { return ; } keys . forEach ( function ( entryName ) { var cacheEntry = entries [ entryName ] ; try { var stat = fs . statSync ( cacheEntry . key ) ; var meta = assign ( cacheEntry . meta , { size : stat . size , mtime : stat . mtime . getTime ( ) } ) ; cache . setKey ( entryName , meta ) ; } catch ( err ) { // if the file does not exists we don't save it // other errors are just thrown if ( err . code !== 'ENOENT' ) { throw err ; } } } ) ; cache . save ( true ) ; }


Input: Return a range of numbers or letters . [CODESPLIT] function fillRange ( start , stop , step , options ) { if ( typeof start === 'undefined' ) { return [ ] ; } if ( typeof stop === 'undefined' || start === stop ) { // special case, for handling negative zero var isString = typeof start === 'string' ; if ( isNumber ( start ) && ! toNumber ( start ) ) { return [ isString ? '0' : 0 ] ; } return [ start ] ; } if ( typeof step !== 'number' && typeof step !== 'string' ) { options = step ; step = undefined ; } if ( typeof options === 'function' ) { options = { transform : options } ; } var opts = extend ( { step : step } , options ) ; if ( opts . step && ! isValidNumber ( opts . step ) ) { if ( opts . strictRanges === true ) { throw new TypeError ( 'expected options.step to be a number' ) ; } return [ ] ; } opts . isNumber = isValidNumber ( start ) && isValidNumber ( stop ) ; if ( ! opts . isNumber && ! isValid ( start , stop ) ) { if ( opts . strictRanges === true ) { throw new RangeError ( 'invalid range arguments: ' + util . inspect ( [ start , stop ] ) ) ; } return [ ] ; } opts . isPadded = isPadded ( start ) || isPadded ( stop ) ; opts . toString = opts . stringify || typeof opts . step === 'string' || typeof start === 'string' || typeof stop === 'string' || ! opts . isNumber ; if ( opts . isPadded ) { opts . maxLength = Math . max ( String ( start ) . length , String ( stop ) . length ) ; } // support legacy minimatch/fill-range options if ( typeof opts . optimize === 'boolean' ) opts . toRegex = opts . optimize ; if ( typeof opts . makeRe === 'boolean' ) opts . toRegex = opts . makeRe ; return expand ( start , stop , opts ) ; }


Input: Load a cache identified by the given Id . If the element does not exists then initialize an empty cache storage . If specified cacheDir will be used as the directory to persist the data to . If omitted then the cache module directory . / cache will be used instead [CODESPLIT] function ( docId , cacheDir ) { var me = this ; me . _visited = { } ; me . _persisted = { } ; me . _pathToFile = cacheDir ? path . resolve ( cacheDir , docId ) : path . resolve ( __dirname , './.cache/' , docId ) ; if ( fs . existsSync ( me . _pathToFile ) ) { me . _persisted = utils . tryParse ( me . _pathToFile , { } ) ; } }


Input: Load the cache from the provided file [CODESPLIT] function ( pathToFile ) { var me = this ; var dir = path . dirname ( pathToFile ) ; var fName = path . basename ( pathToFile ) ; me . load ( fName , dir ) ; }


Input: Remove keys that were not accessed / set since the last time the prune method was called . [CODESPLIT] function ( ) { var me = this ; var obj = { } ; var keys = Object . keys ( me . _visited ) ; // no keys visited for either get or set value if ( keys . length === 0 ) { return ; } keys . forEach ( function ( key ) { obj [ key ] = me . _persisted [ key ] ; } ) ; me . _visited = { } ; me . _persisted = obj ; }


Input: Save the state of the cache identified by the docId to disk as a JSON structure [CODESPLIT] function ( noPrune ) { var me = this ; ( ! noPrune ) && me . _prune ( ) ; writeJSON ( me . _pathToFile , me . _persisted ) ; }


Input: Load a cache identified by the given Id . If the element does not exists then initialize an empty cache storage . [CODESPLIT] function ( docId , cacheDir ) { var obj = Object . create ( cache ) ; obj . load ( docId , cacheDir ) ; return obj ; }


Input: Clear the cache identified by the given id . Caches stored in a different cache directory can be deleted directly [CODESPLIT] function ( docId , cacheDir ) { var filePath = cacheDir ? path . resolve ( cacheDir , docId ) : path . resolve ( __dirname , './.cache/' , docId ) ; return del ( filePath , { force : true } ) . length > 0 ; }


Input: Set a value for property key on cache name [CODESPLIT] function ( cacheName , key , val ) { var cache = this . cache ( cacheName ) ; cache . set ( key , val ) ; return cache ; }


Input: Get name or if specified the value of key . Invokes the [ cache ] () method so that cache name will be created it doesn t already exist . If key is not passed the entire cache ( name ) is returned . [CODESPLIT] function ( name , key ) { var cache = this . cache ( name ) ; if ( typeof key === 'string' ) { return cache . get ( key ) ; } return cache ; }


Input: walk down the path swapping out linked pathparts for their real values [CODESPLIT] function LOOP ( ) { // stop if scanned past end of path if ( pos >= p . length ) { if ( cache ) cache [ original ] = p ; return cb ( null , p ) ; } // find the next part nextPartRe . lastIndex = pos ; var result = nextPartRe . exec ( p ) ; previous = current ; current += result [ 0 ] ; base = previous + result [ 1 ] ; pos = nextPartRe . lastIndex ; // continue if not a symlink if ( knownHard [ base ] || ( cache && cache [ base ] === base ) ) { return process . nextTick ( LOOP ) ; } if ( cache && Object . prototype . hasOwnProperty . call ( cache , base ) ) { // known symbolic link.  no need to stat again. return gotResolvedLink ( cache [ base ] ) ; } return fs . lstat ( base , gotStat ) ; }


Input: ignore patterns are always in dot : true mode . [CODESPLIT] function ignoreMap ( pattern ) { var gmatcher = null if ( pattern . slice ( - 3 ) === '/**' ) { var gpattern = pattern . replace ( / (\/\*\*)+$ / , '' ) gmatcher = new Minimatch ( gpattern , { dot : true } ) } return { matcher : new Minimatch ( pattern , { dot : true } ) , gmatcher : gmatcher } }


Input: lotta situps ... [CODESPLIT] function makeAbs ( self , f ) { var abs = f if ( f . charAt ( 0 ) === '/' ) { abs = path . join ( self . root , f ) } else if ( isAbsolute ( f ) || f === '' ) { abs = f } else if ( self . changedCwd ) { abs = path . resolve ( self . cwd , f ) } else { abs = path . resolve ( f ) } if ( process . platform === 'win32' ) abs = abs . replace ( / \\ / g , '/' ) return abs }


Input: Return true if pattern ends with globstar ** for the accompanying parent directory . Ex : - If node_modules / ** is the pattern add node_modules to ignore list along with it s contents [CODESPLIT] function isIgnored ( self , path ) { if ( ! self . ignore . length ) return false return self . ignore . some ( function ( item ) { return item . matcher . match ( path ) || ! ! ( item . gmatcher && item . gmatcher . match ( path ) ) } ) }


Input: If you need to support Safari 5 - 7 ( 8 - 10 yr - old browser ) take a look at https : // github . com / feross / is - buffer [CODESPLIT] function isBuffer ( val ) { return val . constructor && typeof val . constructor . isBuffer === 'function' && val . constructor . isBuffer ( val ) ; }


Input: The main function . Pass an array of filepaths and a string or array of glob patterns [CODESPLIT] function micromatch ( files , patterns , opts ) { if ( ! files || ! patterns ) return [ ] ; opts = opts || { } ; if ( typeof opts . cache === 'undefined' ) { opts . cache = true ; } if ( ! Array . isArray ( patterns ) ) { return match ( files , patterns , opts ) ; } var len = patterns . length , i = 0 ; var omit = [ ] , keep = [ ] ; while ( len -- ) { var glob = patterns [ i ++ ] ; if ( typeof glob === 'string' && glob . charCodeAt ( 0 ) === 33 /* ! */ ) { omit . push . apply ( omit , match ( files , glob . slice ( 1 ) , opts ) ) ; } else { keep . push . apply ( keep , match ( files , glob , opts ) ) ; } } return utils . diff ( keep , omit ) ; }


Input: Return an array of files that match the given glob pattern . [CODESPLIT] function match ( files , pattern , opts ) { if ( utils . typeOf ( files ) !== 'string' && ! Array . isArray ( files ) ) { throw new Error ( msg ( 'match' , 'files' , 'a string or array' ) ) ; } files = utils . arrayify ( files ) ; opts = opts || { } ; var negate = opts . negate || false ; var orig = pattern ; if ( typeof pattern === 'string' ) { negate = pattern . charAt ( 0 ) === '!' ; if ( negate ) { pattern = pattern . slice ( 1 ) ; } // we need to remove the character regardless, // so the above logic is still needed if ( opts . nonegate === true ) { negate = false ; } } var _isMatch = matcher ( pattern , opts ) ; var len = files . length , i = 0 ; var res = [ ] ; while ( i < len ) { var file = files [ i ++ ] ; var fp = utils . unixify ( file , opts ) ; if ( ! _isMatch ( fp ) ) { continue ; } res . push ( fp ) ; } if ( res . length === 0 ) { if ( opts . failglob === true ) { throw new Error ( 'micromatch.match() found no matches for: "' + orig + '".' ) ; } if ( opts . nonull || opts . nullglob ) { res . push ( utils . unescapeGlob ( orig ) ) ; } } // if `negate` was defined, diff negated files if ( negate ) { res = utils . diff ( files , res ) ; } // if `ignore` was defined, diff ignored filed if ( opts . ignore && opts . ignore . length ) { pattern = opts . ignore ; opts = utils . omit ( opts , [ 'ignore' ] ) ; res = utils . diff ( res , micromatch ( res , pattern , opts ) ) ; } if ( opts . nodupes ) { return utils . unique ( res ) ; } return res ; }


Input: Returns a function that takes a glob pattern or array of glob patterns to be used with Array#filter () . ( Internally this function generates the matching function using the [ matcher ] method ) . [CODESPLIT] function filter ( patterns , opts ) { if ( ! Array . isArray ( patterns ) && typeof patterns !== 'string' ) { throw new TypeError ( msg ( 'filter' , 'patterns' , 'a string or array' ) ) ; } patterns = utils . arrayify ( patterns ) ; var len = patterns . length , i = 0 ; var patternMatchers = Array ( len ) ; while ( i < len ) { patternMatchers [ i ] = matcher ( patterns [ i ++ ] , opts ) ; } return function ( fp ) { if ( fp == null ) return [ ] ; var len = patternMatchers . length , i = 0 ; var res = true ; fp = utils . unixify ( fp , opts ) ; while ( i < len ) { var fn = patternMatchers [ i ++ ] ; if ( ! fn ( fp ) ) { res = false ; break ; } } return res ; } ; }


Input: Returns true if the filepath contains the given pattern . Can also return a function for matching . [CODESPLIT] function isMatch ( fp , pattern , opts ) { if ( typeof fp !== 'string' ) { throw new TypeError ( msg ( 'isMatch' , 'filepath' , 'a string' ) ) ; } fp = utils . unixify ( fp , opts ) ; if ( utils . typeOf ( pattern ) === 'object' ) { return matcher ( fp , pattern ) ; } return matcher ( pattern , opts ) ( fp ) ; }


Input: Returns true if the filepath matches the given pattern . [CODESPLIT] function contains ( fp , pattern , opts ) { if ( typeof fp !== 'string' ) { throw new TypeError ( msg ( 'contains' , 'pattern' , 'a string' ) ) ; } opts = opts || { } ; opts . contains = ( pattern !== '' ) ; fp = utils . unixify ( fp , opts ) ; if ( opts . contains && ! utils . isGlob ( pattern ) ) { return fp . indexOf ( pattern ) !== - 1 ; } return matcher ( pattern , opts ) ( fp ) ; }


Input: Returns true if a file path matches any of the given patterns . [CODESPLIT] function any ( fp , patterns , opts ) { if ( ! Array . isArray ( patterns ) && typeof patterns !== 'string' ) { throw new TypeError ( msg ( 'any' , 'patterns' , 'a string or array' ) ) ; } patterns = utils . arrayify ( patterns ) ; var len = patterns . length ; fp = utils . unixify ( fp , opts ) ; while ( len -- ) { var isMatch = matcher ( patterns [ len ] , opts ) ; if ( isMatch ( fp ) ) { return true ; } } return false ; }


Input: Filter the keys of an object with the given glob pattern and options [CODESPLIT] function matchKeys ( obj , glob , options ) { if ( utils . typeOf ( obj ) !== 'object' ) { throw new TypeError ( msg ( 'matchKeys' , 'first argument' , 'an object' ) ) ; } var fn = matcher ( glob , options ) ; var res = { } ; for ( var key in obj ) { if ( obj . hasOwnProperty ( key ) && fn ( key ) ) { res [ key ] = obj [ key ] ; } } return res ; }


Input: Return a function for matching based on the given pattern and options . [CODESPLIT] function matcher ( pattern , opts ) { // pattern is a function if ( typeof pattern === 'function' ) { return pattern ; } // pattern is a regex if ( pattern instanceof RegExp ) { return function ( fp ) { return pattern . test ( fp ) ; } ; } if ( typeof pattern !== 'string' ) { throw new TypeError ( msg ( 'matcher' , 'pattern' , 'a string, regex, or function' ) ) ; } // strings, all the way down... pattern = utils . unixify ( pattern , opts ) ; // pattern is a non-glob string if ( ! utils . isGlob ( pattern ) ) { return utils . matchPath ( pattern , opts ) ; } // pattern is a glob string var re = makeRe ( pattern , opts ) ; // `matchBase` is defined if ( opts && opts . matchBase ) { return utils . hasFilename ( re , opts ) ; } // `matchBase` is not defined return function ( fp ) { fp = utils . unixify ( fp , opts ) ; return re . test ( fp ) ; } ; }


Input: Create and cache a regular expression for matching file paths . [CODESPLIT] function toRegex ( glob , options ) { // clone options to prevent  mutating the original object var opts = Object . create ( options || { } ) ; var flags = opts . flags || '' ; if ( opts . nocase && flags . indexOf ( 'i' ) === - 1 ) { flags += 'i' ; } var parsed = expand ( glob , opts ) ; // pass in tokens to avoid parsing more than once opts . negated = opts . negated || parsed . negated ; opts . negate = opts . negated ; glob = wrapGlob ( parsed . pattern , opts ) ; var re ; try { re = new RegExp ( glob , flags ) ; return re ; } catch ( err ) { err . reason = 'micromatch invalid regex: (' + re + ')' ; if ( opts . strict ) throw new SyntaxError ( err ) ; } // we're only here if a bad pattern was used and the user // passed `options.silent`, so match nothing return / $^ / ; }


Input: Create the regex to do the matching . If the leading character in the glob is ! a negation regex is returned . [CODESPLIT] function wrapGlob ( glob , opts ) { var prefix = ( opts && ! opts . contains ) ? '^' : '' ; var after = ( opts && ! opts . contains ) ? '$' : '' ; glob = ( '(?:' + glob + ')' + after ) ; if ( opts && opts . negate ) { return prefix + ( '(?!^' + glob + ').*$' ) ; } return prefix + glob ; }


Input: Create and cache a regular expression for matching file paths . If the leading character in the glob is ! a negation regex is returned . [CODESPLIT] function makeRe ( glob , opts ) { if ( utils . typeOf ( glob ) !== 'string' ) { throw new Error ( msg ( 'makeRe' , 'glob' , 'a string' ) ) ; } return utils . cache ( toRegex , glob , opts ) ; }


Input:
Expand a glob pattern to resolve braces and similar patterns before converting to regex . [CODESPLIT] function expand ( pattern , options ) { if ( typeof pattern !== 'string' ) { throw new TypeError ( 'micromatch.expand(): argument should be a string.' ) ; } var glob = new Glob ( pattern , options || { } ) ; var opts = glob . options ; if ( ! utils . isGlob ( pattern ) ) { glob . pattern = glob . pattern . replace ( / ([\/.]) / g , '\\$1' ) ; return glob ; } glob . pattern = glob . pattern . replace ( / (\+)(?!\() / g , '\\$1' ) ; glob . pattern = glob . pattern . split ( '$' ) . join ( '\\$' ) ; if ( typeof opts . braces !== 'boolean' && typeof opts . nobraces !== 'boolean' ) { opts . braces = true ; } if ( glob . pattern === '.*' ) { return { pattern : '\\.' + star , tokens : tok , options : opts } ; } if ( glob . pattern === '*' ) { return { pattern : oneStar ( opts . dot ) , tokens : tok , options : opts } ; } // parse the glob pattern into tokens glob . parse ( ) ; var tok = glob . tokens ; tok . is . negated = opts . negated ; // dotfile handling if ( ( opts . dotfiles === true || tok . is . dotfile ) && opts . dot !== false ) { opts . dotfiles = true ; opts . dot = true ; } if ( ( opts . dotdirs === true || tok . is . dotdir ) && opts . dot !== false ) { opts . dotdirs = true ; opts . dot = true ; } // check for braces with a dotfile pattern if ( / [{,]\. / . test ( glob . pattern ) ) { opts . makeRe = false ; opts . dot = true ; } if ( opts . nonegate !== true ) { opts . negated = glob . negated ; } // if the leading character is a dot or a slash, escape it if ( glob . pattern . charAt ( 0 ) === '.' && glob . pattern . charAt ( 1 ) !== '/' ) { glob . pattern = '\\' + glob . pattern ; } /**
   * Extended globs
   */ // expand braces, e.g `{1..5}` glob . track ( 'before braces' ) ; if ( tok . is . braces ) { glob . braces ( ) ; } glob . track ( 'after braces' ) ; // expand extglobs, e.g `foo/!(a|b)` glob . track ( 'before extglob' ) ; if ( tok . is . extglob ) { glob . extglob ( ) ; } glob . track ( 'after extglob' ) ; // expand brackets, e.g `[[:alpha:]]` glob . track ( 'before brackets' ) ; if ( tok . is . brackets ) { glob . brackets ( ) ; } glob . track ( 'after brackets' ) ; // special patterns glob . _replace ( '[!' , '[^' ) ; glob . _replace ( '(?' , '(%~' ) ; glob . _replace ( / \[\] / , '\\[\\]' ) ; glob . _replace ( '/[' , '/' + ( opts . dot ? dotfiles : nodot ) + '[' , true ) ; glob . _replace ( '/?' , '/' + ( opts . dot ? dotfiles : nodot ) + '[^/]' , true ) ; glob . _replace ( '/.' , '/(?=.)\\.' , true ) ; // windows drives glob . _replace ( / ^(\w):([\\\/]+?) / gi , '(?=.)$1:$2' , true ) ; // negate slashes in exclusion ranges if ( glob . pattern . indexOf ( '[^' ) !== - 1 ) { glob . pattern = negateSlash ( glob . pattern ) ; } if ( opts . globstar !== false && glob . pattern === '**' ) { glob . pattern = globstar ( opts . dot ) ; } else { glob . pattern = balance ( glob . pattern , '[' , ']' ) ; glob . escape ( glob . pattern ) ; // if the pattern has `**` if ( tok . is . globstar ) { glob . pattern = collapse ( glob . pattern , '/**' ) ; glob . pattern = collapse ( glob . pattern , '**/' ) ; glob . _replace ( '/**/' , '(?:/' + globstar ( opts . dot ) + '/|/)' , true ) ; glob . _replace ( / \*{2,} / g , '**' ) ; // 'foo/*' glob . _replace ( / (\w+)\*(?!\/) / g , '$1[^/]*?' , true ) ; glob . _replace ( / \*\*\/\*(\w) / g , globstar ( opts . dot ) + '\\/' + ( opts . dot ? dotfiles : nodot ) + '[^/]*?$1' , true ) ; if ( opts . dot !== true ) { glob . _replace ( / \*\*\/(.) / g , '(?:**\\/|)$1' ) ; } // 'foo/**' or '{**,*}', but not 'foo**' if ( tok . path . dirname !== '' || / ,\*\*|\*\*, / . test ( glob . orig ) ) { glob . _replace ( '**' , globstar ( opts . dot ) , true ) ; } } // ends with /* glob . _replace ( / \/\*$ / , '\\/' + oneStar ( opts . dot ) , true ) ; // ends with *, no slashes glob . _replace ( / (?!\/)\*$ / , star , true ) ; // has 'n*.' (partial wildcard w/ file extension) glob . _replace ( / ([^\/]+)\* / , '$1' + oneStar ( true ) , true ) ; // has '*' glob . _replace ( '*' , oneStar ( opts . dot ) , true ) ; glob . _replace ( '?.' , '?\\.' , true ) ; glob . _replace ( '?:' , '?:' , true ) ; glob . _replace ( / \?+ / g , function ( match ) { var len = match . length ; if ( len === 1 ) { return qmark ; } return qmark + '{' + len + '}' ; } ) ; // escape '.abc' => '\\.abc' glob . _replace ( / \.([*\w]+) / g , '\\.$1' ) ; // fix '[^\\\\/]' glob . _replace ( / \[\^[\\\/]+\] / g , qmark ) ; // '///' => '\/' glob . _replace ( / \/+ / g , '\\/' ) ; // '\\\\\\' => '\\' glob . _replace ( / \\{2,} / g , '\\' ) ; } // unescape previously escaped patterns glob . unescape ( glob . pattern ) ; glob . _replace ( '__UNESC_STAR__' , '*' ) ; // escape dots that follow qmarks glob . _replace ( '?.' , '?\\.' ) ; // remove unnecessary slashes in character classes glob . _replace ( '[^\\/]' , qmark ) ; if ( glob . pattern . length > 1 ) { if ( / ^[\[?*] / . test ( glob . pattern ) ) { // only prepend the string if we don't want to match dotfiles glob . pattern = ( opts . dot ? dotfiles : nodot ) + glob . pattern ; } } return glob ; }


Input: Collapse repeated character sequences . [CODESPLIT] function collapse ( str , ch ) { var res = str . split ( ch ) ; var isFirst = res [ 0 ] === '' ; var isLast = res [ res . length - 1 ] === '' ; res = res . filter ( Boolean ) ; if ( isFirst ) res . unshift ( '' ) ; if ( isLast ) res . push ( '' ) ; return res . join ( ch ) ; }


Input: Negate slashes in exclusion ranges per glob spec : [CODESPLIT] function negateSlash ( str ) { return str . replace ( / \[\^([^\]]*?)\] / g , function ( match , inner ) { if ( inner . indexOf ( '/' ) === - 1 ) { inner = '\\/' + inner ; } return '[^' + inner + ']' ; } ) ; }


Input: Escape imbalanced braces / bracket . This is a very basic naive implementation that only does enough to serve the purpose . [CODESPLIT] function balance ( str , a , b ) { var aarr = str . split ( a ) ; var alen = aarr . join ( '' ) . length ; var blen = str . split ( b ) . join ( '' ) . length ; if ( alen !== blen ) { str = aarr . join ( '\\' + a ) ; return str . split ( b ) . join ( '\\' + b ) ; } return str ; }


Input: Expand { foo bar } or { 1 .. 5 } braces in the given string . [CODESPLIT] function braces ( str , arr , options ) { if ( str === '' ) { return [ ] ; } if ( ! Array . isArray ( arr ) ) { options = arr ; arr = [ ] ; } var opts = options || { } ; arr = arr || [ ] ; if ( typeof opts . nodupes === 'undefined' ) { opts . nodupes = true ; } var fn = opts . fn ; var es6 ; if ( typeof opts === 'function' ) { fn = opts ; opts = { } ; } if ( ! ( patternRe instanceof RegExp ) ) { patternRe = patternRegex ( ) ; } var matches = str . match ( patternRe ) || [ ] ; var m = matches [ 0 ] ; switch ( m ) { case '\\,' : return escapeCommas ( str , arr , opts ) ; case '\\.' : return escapeDots ( str , arr , opts ) ; case '\/.' : return escapePaths ( str , arr , opts ) ; case ' ' : return splitWhitespace ( str ) ; case '{,}' : return exponential ( str , opts , braces ) ; case '{}' : return emptyBraces ( str , arr , opts ) ; case '\\{' : case '\\}' : return escapeBraces ( str , arr , opts ) ; case '${' : if ( ! / \{[^{]+\{ / . test ( str ) ) { return arr . concat ( str ) ; } else { es6 = true ; str = tokens . before ( str , es6Regex ( ) ) ; } } if ( ! ( braceRe instanceof RegExp ) ) { braceRe = braceRegex ( ) ; } var match = braceRe . exec ( str ) ; if ( match == null ) { return [ str ] ; } var outter = match [ 1 ] ; var inner = match [ 2 ] ; if ( inner === '' ) { return [ str ] ; } var segs , segsLength ; if ( inner . indexOf ( '..' ) !== - 1 ) { segs = expand ( inner , opts , fn ) || inner . split ( ',' ) ; segsLength = segs . length ; } else if ( inner [ 0 ] === '"' || inner [ 0 ] === '\'' ) { return arr . concat ( str . split ( / ['"] / ) . join ( '' ) ) ; } else { segs = inner . split ( ',' ) ; if ( opts . makeRe ) { return braces ( str . replace ( outter , wrap ( segs , '|' ) ) , opts ) ; } segsLength = segs . length ; if ( segsLength === 1 && opts . bash ) { segs [ 0 ] = wrap ( segs [ 0 ] , '\\' ) ; } } var len = segs . length ; var i = 0 , val ; while ( len -- ) { var path = segs [ i ++ ] ; if ( / (\.[^.\/]) / . test ( path ) ) { if ( segsLength > 1 ) { return segs ; } else { return [ str ] ; } } val = splice ( str , outter , path ) ; if ( / \{[^{}]+?\} / . test ( val ) ) { arr = braces ( val , arr , opts ) ; } else if ( val !== '' ) { if ( opts . nodupes && arr . indexOf ( val ) !== - 1 ) { continue ; } arr . push ( es6 ? tokens . after ( val ) : val ) ; } } if ( opts . strict ) { return filter ( arr , filterEmpty ) ; } return arr ; }


Input: Expand exponential ranges [CODESPLIT] function exponential ( str , options , fn ) { if ( typeof options === 'function' ) { fn = options ; options = null ; } var opts = options || { } ; var esc = '__ESC_EXP__' ; var exp = 0 ; var res ; var parts = str . split ( '{,}' ) ; if ( opts . nodupes ) { return fn ( parts . join ( '' ) , opts ) ; } exp = parts . length - 1 ; res = fn ( parts . join ( esc ) , opts ) ; var len = res . length ; var arr = [ ] ; var i = 0 ; while ( len -- ) { var ele = res [ i ++ ] ; var idx = ele . indexOf ( esc ) ; if ( idx === - 1 ) { arr . push ( ele ) ; } else { ele = ele . split ( '__ESC_EXP__' ) . join ( '' ) ; if ( ! ! ele && opts . nodupes !== false ) { arr . push ( ele ) ; } else { var num = Math . pow ( 2 , exp ) ; arr . push . apply ( arr , repeat ( ele , num ) ) ; } } } return arr ; }


Input: Wrap a value with parens brackets or braces based on the given character / separator . [CODESPLIT] function wrap ( val , ch ) { if ( ch === '|' ) { return '(' + val . join ( ch ) + ')' ; } if ( ch === ',' ) { return '{' + val . join ( ch ) + '}' ; } if ( ch === '-' ) { return '[' + val . join ( ch ) + ']' ; } if ( ch === '\\' ) { return '\\{' + val + '\\}' ; } }


Input: Handle empty braces : {} [CODESPLIT] function emptyBraces ( str , arr , opts ) { return braces ( str . split ( '{}' ) . join ( '\\{\\}' ) , arr , opts ) ; }


Input: Handle patterns with whitespace [CODESPLIT] function splitWhitespace ( str ) { var segs = str . split ( ' ' ) ; var len = segs . length ; var res = [ ] ; var i = 0 ; while ( len -- ) { res . push . apply ( res , braces ( segs [ i ++ ] ) ) ; } return res ; }


Input: Handle escaped braces : \\ { foo bar } [CODESPLIT] function escapeBraces ( str , arr , opts ) { if ( ! / \{[^{]+\{ / . test ( str ) ) { return arr . concat ( str . split ( '\\' ) . join ( '' ) ) ; } else { str = str . split ( '\\{' ) . join ( '__LT_BRACE__' ) ; str = str . split ( '\\}' ) . join ( '__RT_BRACE__' ) ; return map ( braces ( str , arr , opts ) , function ( ele ) { ele = ele . split ( '__LT_BRACE__' ) . join ( '{' ) ; return ele . split ( '__RT_BRACE__' ) . join ( '}' ) ; } ) ; } }


Input: Handle escaped dots : { 1 \\ . 2 } [CODESPLIT] function escapePaths ( str , arr , opts ) { str = str . split ( '\/.' ) . join ( '__ESC_PATH__' ) ; return map ( braces ( str , arr , opts ) , function ( ele ) { return ele . split ( '__ESC_PATH__' ) . join ( '\/.' ) ; } ) ; }


Input: Handle escaped commas : { a \\ b } [CODESPLIT] function escapeCommas ( str , arr , opts ) { if ( ! / \w, / . test ( str ) ) { return arr . concat ( str . split ( '\\' ) . join ( '' ) ) ; } else { str = str . split ( '\\,' ) . join ( '__ESC_COMMA__' ) ; return map ( braces ( str , arr , opts ) , function ( ele ) { return ele . split ( '__ESC_COMMA__' ) . join ( ',' ) ; } ) ; } }


Input: Faster alternative to String . replace () when the index of the token to be replaces can t be supplied [CODESPLIT] function splice ( str , token , replacement ) { var i = str . indexOf ( token ) ; return str . substr ( 0 , i ) + replacement + str . substr ( i + token . length ) ; }


Input: Fast array filter [CODESPLIT] function filter ( arr , cb ) { if ( arr == null ) return [ ] ; if ( typeof cb !== 'function' ) { throw new TypeError ( 'braces: filter expects a callback function.' ) ; } var len = arr . length ; var res = arr . slice ( ) ; var i = 0 ; while ( len -- ) { if ( ! cb ( arr [ len ] , i ++ ) ) { res . splice ( len , 1 ) ; } } return res ; }


Input: Convert the given extglob string to a regex - compatible string . [CODESPLIT] function extglob ( str , opts ) { opts = opts || { } ; var o = { } , i = 0 ; // fix common character reversals // '*!(.js)' => '*.!(js)' str = str . replace ( / !\(([^\w*()]) / g , '$1!(' ) ; // support file extension negation str = str . replace ( / ([*\/])\.!\([*]\) / g , function ( m , ch ) { if ( ch === '/' ) { return escape ( '\\/[^.]+' ) ; } return escape ( '[^.]+' ) ; } ) ; // create a unique key for caching by // combining the string and options var key = str + String ( ! ! opts . regex ) + String ( ! ! opts . contains ) + String ( ! ! opts . escape ) ; if ( cache . hasOwnProperty ( key ) ) { return cache [ key ] ; } if ( ! ( re instanceof RegExp ) ) { re = regex ( ) ; } opts . negate = false ; var m ; while ( m = re . exec ( str ) ) { var prefix = m [ 1 ] ; var inner = m [ 3 ] ; if ( prefix === '!' ) { opts . negate = true ; } var id = '__EXTGLOB_' + ( i ++ ) + '__' ; // use the prefix of the _last_ (outtermost) pattern o [ id ] = wrap ( inner , prefix , opts . escape ) ; str = str . split ( m [ 0 ] ) . join ( id ) ; } var keys = Object . keys ( o ) ; var len = keys . length ; // we have to loop again to allow us to convert // patterns in reverse order (starting with the // innermost/last pattern first) while ( len -- ) { var prop = keys [ len ] ; str = str . split ( prop ) . join ( o [ prop ] ) ; } var result = opts . regex ? toRegex ( str , opts . contains , opts . negate ) : str ; result = result . split ( '.' ) . join ( '\\.' ) ; // cache the result and return it return ( cache [ key ] = result ) ; }


Input: Convert string to a regex string . [CODESPLIT] function wrap ( inner , prefix , esc ) { if ( esc ) inner = escape ( inner ) ; switch ( prefix ) { case '!' : return '(?!' + inner + ')[^/]' + ( esc ? '%%%~' : '*?' ) ; case '@' : return '(?:' + inner + ')' ; case '+' : return '(?:' + inner + ')+' ; case '*' : return '(?:' + inner + ')' + ( esc ? '%%' : '*' ) case '?' : return '(?:' + inner + '|)' ; default : return inner ; } }


Input: Create the regex to do the matching . If the leading character in the pattern is ! a negation regex is returned . [CODESPLIT] function toRegex ( pattern , contains , isNegated ) { var prefix = contains ? '^' : '' ; var after = contains ? '$' : '' ; pattern = ( '(?:' + pattern + ')' + after ) ; if ( isNegated ) { pattern = prefix + negate ( pattern ) ; } return new RegExp ( prefix + pattern ) ; }


Input: Copy properties from the source object to the target object . [CODESPLIT] function copy ( val , key ) { if ( key === '__proto__' ) { return ; } var obj = this [ key ] ; if ( isObject ( val ) && isObject ( obj ) ) { mixinDeep ( obj , val ) ; } else { this [ key ] = val ; } }


Input: Advance to the next non - escaped character [CODESPLIT] function advanceTo ( input , endChar ) { var ch = input . charAt ( 0 ) ; var tok = { len : 1 , val : '' , esc : '' } ; var idx = 0 ; function advance ( ) { if ( ch !== '\\' ) { tok . esc += '\\' + ch ; tok . val += ch ; } ch = input . charAt ( ++ idx ) ; tok . len ++ ; if ( ch === '\\' ) { advance ( ) ; advance ( ) ; } } while ( ch && ch !== endChar ) { advance ( ) ; } return tok ; }


Input: Create text regex [CODESPLIT] function createTextRegex ( pattern ) { if ( cached ) return cached ; var opts = { contains : true , strictClose : false } ; var not = regexNot . create ( pattern , opts ) ; var re = toRegex ( '^(?:[*]\\((?=.)|' + not + ')' , opts ) ; return ( cached = re ) ; }


Input: Create a new { @link Processor } instance that will apply plugins as CSS processors . [CODESPLIT] function postcss ( ) { for ( var _len = arguments . length , plugins = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { plugins [ _key ] = arguments [ _key ] ; } if ( plugins . length === 1 && Array . isArray ( plugins [ 0 ] ) ) { plugins = plugins [ 0 ] ; } return new _processor2 . default ( plugins ) ; }


Input: A BasicSourceMapConsumer instance represents a parsed source map which we can query for information about the original file positions by giving it a file position in the generated source . [CODESPLIT] function BasicSourceMapConsumer ( aSourceMap , aSourceMapURL ) { var sourceMap = aSourceMap ; if ( typeof aSourceMap === 'string' ) { sourceMap = util . parseSourceMapInput ( aSourceMap ) ; } var version = util . getArg ( sourceMap , 'version' ) ; var sources = util . getArg ( sourceMap , 'sources' ) ; // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util . getArg ( sourceMap , 'names' , [ ] ) ; var sourceRoot = util . getArg ( sourceMap , 'sourceRoot' , null ) ; var sourcesContent = util . getArg ( sourceMap , 'sourcesContent' , null ) ; var mappings = util . getArg ( sourceMap , 'mappings' ) ; var file = util . getArg ( sourceMap , 'file' , null ) ; // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if ( version != this . _version ) { throw new Error ( 'Unsupported version: ' + version ) ; } if ( sourceRoot ) { sourceRoot = util . normalize ( sourceRoot ) ; } sources = sources . map ( String ) // Some source maps produce relative source paths like "./foo.js" instead of // "foo.js".  Normalize these first so that future comparisons will succeed. // See bugzil.la/1090768. . map ( util . normalize ) // Always ensure that absolute sources are internally stored relative to // the source root, if the source root is absolute. Not doing this would // be particularly problematic when the source root is a prefix of the // source (valid, but why??). See github issue #199 and bugzil.la/1188982. . map ( function ( source ) { return sourceRoot && util . isAbsolute ( sourceRoot ) && util . isAbsolute ( source ) ? util . relative ( sourceRoot , source ) : source ; } ) ; // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this . _names = ArraySet . fromArray ( names . map ( String ) , true ) ; this . _sources = ArraySet . fromArray ( sources , true ) ; this . _absoluteSources = this . _sources . toArray ( ) . map ( function ( s ) { return util . computeSourceURL ( sourceRoot , s , aSourceMapURL ) ; } ) ; this . sourceRoot = sourceRoot ; this . sourcesContent = sourcesContent ; this . _mappings = mappings ; this . _sourceMapURL = aSourceMapURL ; this . file = file ; }


Input: Comparator between two mappings where the original positions are compared . [CODESPLIT] function compareByOriginalPositions ( mappingA , mappingB , onlyCompareOriginal ) { var cmp = strcmp ( mappingA . source , mappingB . source ) ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalLine - mappingB . originalLine ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalColumn - mappingB . originalColumn ; if ( cmp !== 0 || onlyCompareOriginal ) { return cmp ; } cmp = mappingA . generatedColumn - mappingB . generatedColumn ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . generatedLine - mappingB . generatedLine ; if ( cmp !== 0 ) { return cmp ; } return strcmp ( mappingA . name , mappingB . name ) ; }


Input: Comparator between two mappings with deflated source and name indices where the generated positions are compared . [CODESPLIT] function compareByGeneratedPositionsDeflated ( mappingA , mappingB , onlyCompareGenerated ) { var cmp = mappingA . generatedLine - mappingB . generatedLine ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . generatedColumn - mappingB . generatedColumn ; if ( cmp !== 0 || onlyCompareGenerated ) { return cmp ; } cmp = strcmp ( mappingA . source , mappingB . source ) ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalLine - mappingB . originalLine ; if ( cmp !== 0 ) { return cmp ; } cmp = mappingA . originalColumn - mappingB . originalColumn ; if ( cmp !== 0 ) { return cmp ; } return strcmp ( mappingA . name , mappingB . name ) ; }


Input: Compute the URL of a source given the the source root the source s URL and the source map s URL . [CODESPLIT] function computeSourceURL ( sourceRoot , sourceURL , sourceMapURL ) { sourceURL = sourceURL || '' ; if ( sourceRoot ) { // This follows what Chrome does. if ( sourceRoot [ sourceRoot . length - 1 ] !== '/' && sourceURL [ 0 ] !== '/' ) { sourceRoot += '/' ; } // The spec says: //   Line 4: An optional source root, useful for relocating source //   files on a server or removing repeated values in the //   “sources” entry.  This value is prepended to the individual //   entries in the “source” field. sourceURL = sourceRoot + sourceURL ; } // Historically, SourceMapConsumer did not take the sourceMapURL as // a parameter.  This mode is still somewhat supported, which is why // this code block is conditional.  However, it's preferable to pass // the source map URL to SourceMapConsumer, so that this function // can implement the source URL resolution algorithm as outlined in // the spec.  This block is basically the equivalent of: //    new URL(sourceURL, sourceMapURL).toString() // ... except it avoids using URL, which wasn't available in the // older releases of node still supported by this library. // // The spec says: //   If the sources are not absolute URLs after prepending of the //   “sourceRoot”, the sources are resolved relative to the //   SourceMap (like resolving script src in a html document). if ( sourceMapURL ) { var parsed = urlParse ( sourceMapURL ) ; if ( ! parsed ) { throw new Error ( "sourceMapURL could not be parsed" ) ; } if ( parsed . path ) { // Strip the last path component, but keep the "/". var index = parsed . path . lastIndexOf ( '/' ) ; if ( index >= 0 ) { parsed . path = parsed . path . substring ( 0 , index + 1 ) ; } } sourceURL = join ( urlGenerate ( parsed ) , sourceURL ) ; } return normalize ( sourceURL ) ; }


Input: It seems a linked list but it is not there will be only 2 of these for each stream [CODESPLIT] function CorkedRequest ( state ) { var _this = this ; this . next = null ; this . entry = null ; this . finish = function ( ) { onCorkedFinish ( _this , state ) ; } ; }


Input: if there s something in the buffer waiting then process it [CODESPLIT] function clearBuffer ( stream , state ) { state . bufferProcessing = true ; var entry = state . bufferedRequest ; if ( stream . _writev && entry && entry . next ) { // Fast case, write everything using _writev() var l = state . bufferedRequestCount ; var buffer = new Array ( l ) ; var holder = state . corkedRequestsFree ; holder . entry = entry ; var count = 0 ; var allBuffers = true ; while ( entry ) { buffer [ count ] = entry ; if ( ! entry . isBuf ) allBuffers = false ; entry = entry . next ; count += 1 ; } buffer . allBuffers = allBuffers ; doWrite ( stream , state , true , state . length , buffer , '' , holder . finish ) ; // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state . pendingcb ++ ; state . lastBufferedRequest = null ; if ( holder . next ) { state . corkedRequestsFree = holder . next ; holder . next = null ; } else { state . corkedRequestsFree = new CorkedRequest ( state ) ; } state . bufferedRequestCount = 0 ; } else { // Slow case, write chunks one-by-one while ( entry ) { var chunk = entry . chunk ; var encoding = entry . encoding ; var cb = entry . callback ; var len = state . objectMode ? 1 : chunk . length ; doWrite ( stream , state , false , len , chunk , encoding , cb ) ; entry = entry . next ; state . bufferedRequestCount -- ; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if ( state . writing ) { break ; } } if ( entry === null ) state . lastBufferedRequest = null ; } state . bufferedRequest = entry ; state . bufferProcessing = false ; }


Input: / * < / replacement > undocumented cb () API needed for core not for public API [CODESPLIT] function destroy ( err , cb ) { var _this = this ; var readableDestroyed = this . _readableState && this . _readableState . destroyed ; var writableDestroyed = this . _writableState && this . _writableState . destroyed ; if ( readableDestroyed || writableDestroyed ) { if ( cb ) { cb ( err ) ; } else if ( err && ( ! this . _writableState || ! this . _writableState . errorEmitted ) ) { pna . nextTick ( emitErrorNT , this , err ) ; } return this ; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if ( this . _readableState ) { this . _readableState . destroyed = true ; } // if this is a duplex stream mark the writable part as destroyed as well if ( this . _writableState ) { this . _writableState . destroyed = true ; } this . _destroy ( err || null , function ( err ) { if ( ! cb && err ) { pna . nextTick ( emitErrorNT , _this , err ) ; if ( _this . _writableState ) { _this . _writableState . errorEmitted = true ; } } else if ( cb ) { cb ( err ) ; } } ) ; return this ; }


Input: Create a new AST Node with the given val and type . [CODESPLIT] function Node ( val , type , parent ) { if ( typeof type !== 'string' ) { parent = type ; type = null ; } define ( this , 'parent' , parent ) ; define ( this , 'isNode' , true ) ; define ( this , 'expect' , null ) ; if ( typeof type !== 'string' && isObject ( val ) ) { lazyKeys ( ) ; var keys = Object . keys ( val ) ; for ( var i = 0 ; i < keys . length ; i ++ ) { var key = keys [ i ] ; if ( ownNames . indexOf ( key ) === - 1 ) { this [ key ] = val [ key ] ; } } } else { this . type = type ; this . val = val ; } }


Input: Shim to ensure the . append methods work with any version of snapdragon [CODESPLIT] function append ( compiler , val , node ) { if ( typeof compiler . append !== 'function' ) { return compiler . emit ( val , node ) ; } return compiler . append ( val , node ) ; }


Input: Create a new instance of Snapdragon with the given options . [CODESPLIT] function Snapdragon ( options ) { Base . call ( this , null , options ) ; this . options = utils . extend ( { source : 'string' } , this . options ) ; this . compiler = new Compiler ( this . options ) ; this . parser = new Parser ( this . options ) ; Object . defineProperty ( this , 'compilers' , { get : function ( ) { return this . compiler . compilers ; } } ) ; Object . defineProperty ( this , 'parsers' , { get : function ( ) { return this . parser . parsers ; } } ) ; Object . defineProperty ( this , 'regex' , { get : function ( ) { return this . parser . regex ; } } ) ; }


Input: Create a new Compiler with the given options . [CODESPLIT] function Compiler ( options , state ) { debug ( 'initializing' , __filename ) ; this . options = utils . extend ( { source : 'string' } , options ) ; this . state = state || { } ; this . compilers = { } ; this . output = '' ; this . set ( 'eos' , function ( node ) { return this . emit ( node . val , node ) ; } ) ; this . set ( 'noop' , function ( node ) { return this . emit ( node . val , node ) ; } ) ; this . set ( 'bos' , function ( node ) { return this . emit ( node . val , node ) ; } ) ; use ( this ) ; }


Input: Throw an error message with details including the cursor position . [CODESPLIT] function ( msg , node ) { var pos = node . position || { start : { column : 0 } } ; var message = this . options . source + ' column:' + pos . start . column + ': ' + msg ; var err = new Error ( message ) ; err . reason = msg ; err . column = pos . start . column ; err . source = this . pattern ; if ( this . options . silent ) { this . errors . push ( err ) ; } else { throw err ; } }


Input: Visit node . [CODESPLIT] function ( node , nodes , i ) { var fn = this . compilers [ node . type ] ; this . idx = i ; if ( typeof fn !== 'function' ) { throw this . error ( 'compiler "' + node . type + '" is not registered' , node ) ; } return fn . call ( this , node , nodes , i ) ; }


Input: Map visit over array of nodes . [CODESPLIT] function ( nodes ) { if ( ! Array . isArray ( nodes ) ) { throw new TypeError ( 'expected an array' ) ; } var len = nodes . length ; var idx = - 1 ; while ( ++ idx < len ) { this . visit ( nodes [ idx ] , nodes , idx ) ; } return this ; }


Input: Compile ast . [CODESPLIT] function ( ast , options ) { var opts = utils . extend ( { } , this . options , options ) ; this . ast = ast ; this . parsingErrors = this . ast . errors ; this . output = '' ; // source map support if ( opts . sourcemap ) { var sourcemaps = require ( './source-maps' ) ; sourcemaps ( this ) ; this . mapVisit ( this . ast . nodes ) ; this . applySourceMaps ( ) ; this . map = opts . sourcemap === 'generator' ? this . map : this . map . toJSON ( ) ; return this ; } this . mapVisit ( this . ast . nodes ) ; return this ; }


Input: Create a new Parser with the given input and options . [CODESPLIT] function Parser ( options ) { debug ( 'initializing' , __filename ) ; this . options = utils . extend ( { source : 'string' } , options ) ; this . init ( this . options ) ; use ( this ) ; }


Input: Mark position and patch node . position . [CODESPLIT] function ( ) { var start = { line : this . line , column : this . column } ; var self = this ; return function ( node ) { define ( node , 'position' , new Position ( start , self ) ) ; return node ; } ; }


Input: Set parser name with the given fn [CODESPLIT] function ( type , fn ) { if ( this . types . indexOf ( type ) === - 1 ) { this . types . push ( type ) ; } this . parsers [ type ] = fn . bind ( this ) ; return this ; }


Input: Push a token onto the type stack . [CODESPLIT] function ( type , token ) { this . sets [ type ] = this . sets [ type ] || [ ] ; this . count ++ ; this . stack . push ( token ) ; return this . sets [ type ] . push ( token ) ; }


Input: Pop a token off of the type stack [CODESPLIT] function ( type ) { this . sets [ type ] = this . sets [ type ] || [ ] ; this . count -- ; this . stack . pop ( ) ; return this . sets [ type ] . pop ( ) ; }


Input: Get the previous AST node [CODESPLIT] function ( n ) { return this . stack . length > 0 ? utils . last ( this . stack , n ) : utils . last ( this . nodes , n ) ; }


Input: Update column based on str . [CODESPLIT] function ( str , len ) { var lines = str . match ( / \n / g ) ; if ( lines ) this . line += lines . length ; var i = str . lastIndexOf ( '\n' ) ; this . column = ~ i ? len - i : this . column + len ; this . parsed += str ; this . consume ( len ) ; }


Input: Capture type with the given regex . [CODESPLIT] function ( type , regex ) { if ( typeof regex === 'function' ) { return this . set . apply ( this , arguments ) ; } this . regex . set ( type , regex ) ; this . set ( type , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( regex ) ; if ( ! m || ! m [ 0 ] ) return ; var prev = this . prev ( ) ; var node = pos ( { type : type , val : m [ 0 ] , parsed : parsed , rest : this . input } ) ; if ( m [ 1 ] ) { node . inner = m [ 1 ] ; } define ( node , 'inside' , this . stack . length > 0 ) ; define ( node , 'parent' , prev ) ; prev . nodes . push ( node ) ; } . bind ( this ) ) ; return this ; }


Input:
Create a parser with open and close for parens brackets or braces [CODESPLIT] function ( type , openRegex , closeRegex , fn ) { this . sets [ type ] = this . sets [ type ] || [ ] ; /**
     * Open
     */ this . set ( type + '.open' , function ( ) { var parsed = this . parsed ; var pos = this . position ( ) ; var m = this . match ( openRegex ) ; if ( ! m || ! m [ 0 ] ) return ; var val = m [ 0 ] ; this . setCount ++ ; this . specialChars = true ; var open = pos ( { type : type + '.open' , val : val , rest : this . input } ) ; if ( typeof m [ 1 ] !== 'undefined' ) { open . inner = m [ 1 ] ; } var prev = this . prev ( ) ; var node = pos ( { type : type , nodes : [ open ] } ) ; define ( node , 'rest' , this . input ) ; define ( node , 'parsed' , parsed ) ; define ( node , 'prefix' , m [ 1 ] ) ; define ( node , 'parent' , prev ) ; define ( open , 'parent' , node ) ; if ( typeof fn === 'function' ) { fn . call ( this , open , node ) ; } this . push ( type , node ) ; prev . nodes . push ( node ) ; } ) ; /**
     * Close
     */ this . set ( type + '.close' , function ( ) { var pos = this . position ( ) ; var m = this . match ( closeRegex ) ; if ( ! m || ! m [ 0 ] ) return ; var parent = this . pop ( type ) ; var node = pos ( { type : type + '.close' , rest : this . input , suffix : m [ 1 ] , val : m [ 0 ] } ) ; if ( ! this . isType ( parent , type ) ) { if ( this . options . strict ) { throw new Error ( 'missing opening "' + type + '"' ) ; } this . setCount -- ; node . escaped = true ; return node ; } if ( node . suffix === '\\' ) { parent . escaped = true ; node . escaped = true ; } parent . nodes . push ( node ) ; define ( node , 'parent' , parent ) ; } ) ; return this ; }


Input: Capture end - of - string [CODESPLIT] function ( ) { var pos = this . position ( ) ; if ( this . input ) return ; var prev = this . prev ( ) ; while ( prev . type !== 'root' && ! prev . visited ) { if ( this . options . strict === true ) { throw new SyntaxError ( 'invalid syntax:' + util . inspect ( prev , null , 2 ) ) ; } if ( ! hasDelims ( prev ) ) { prev . parent . escaped = true ; prev . escaped = true ; } visit ( prev , function ( node ) { if ( ! hasDelims ( node . parent ) ) { node . parent . escaped = true ; node . escaped = true ; } } ) ; prev = prev . parent ; } var tok = pos ( { type : 'eos' , val : this . append || '' } ) ; define ( tok , 'parent' , this . ast ) ; return tok ; }


Input: Run parsers to advance the cursor position [CODESPLIT] function ( ) { var parsed = this . parsed ; var len = this . types . length ; var idx = - 1 ; var tok ; while ( ++ idx < len ) { if ( ( tok = this . parsers [ this . types [ idx ] ] . call ( this ) ) ) { define ( tok , 'rest' , this . input ) ; define ( tok , 'parsed' , parsed ) ; this . last = tok ; return tok ; } } }


Input: Parse the given string . [CODESPLIT] function ( input ) { if ( typeof input !== 'string' ) { throw new TypeError ( 'expected a string' ) ; } this . init ( this . options ) ; this . orig = input ; this . input = input ; var self = this ; function parse ( ) { // check input before calling `.next()` input = self . input ; // get the next AST ndoe var node = self . next ( ) ; if ( node ) { var prev = self . prev ( ) ; if ( prev ) { define ( node , 'parent' , prev ) ; if ( prev . nodes ) { prev . nodes . push ( node ) ; } } if ( self . sets . hasOwnProperty ( prev . type ) ) { self . currentType = prev . type ; } } // if we got here but input is not changed, throw an error if ( self . input && input === self . input ) { throw new Error ( 'no parsers registered for: "' + self . input . slice ( 0 , 5 ) + '"' ) ; } } while ( this . input ) parse ( ) ; if ( this . stack . length && this . options . strict ) { var node = this . stack . pop ( ) ; throw this . error ( 'missing opening ' + node . type + ': "' + this . orig + '"' ) ; } var eos = this . eos ( ) ; var tok = this . prev ( ) ; if ( tok . type !== 'eos' ) { this . ast . nodes . push ( eos ) ; } return this . ast ; }


Input: Visit node with the given fn [CODESPLIT] function visit ( node , fn ) { if ( ! node . visited ) { define ( node , 'visited' , true ) ; return node . nodes ? mapVisit ( node . nodes , fn ) : fn ( node ) ; } return node ; }


Input: Mixin source map support into compiler . [CODESPLIT] function mixin ( compiler ) { define ( compiler , '_comment' , compiler . comment ) ; compiler . map = new utils . SourceMap . SourceMapGenerator ( ) ; compiler . position = { line : 1 , column : 1 } ; compiler . content = { } ; compiler . files = { } ; for ( var key in exports ) { define ( compiler , key , exports [ key ] ) ; } }


Input: For UTF - 8 a replacement character is added when ending on a partial character . [CODESPLIT] function utf8End ( buf ) { var r = buf && buf . length ? this . write ( buf ) : '' ; if ( this . lastNeed ) return r + '\ufffd' ; return r ; }


Input: Convert a range to a regex pattern [CODESPLIT] function rangeToPattern ( start , stop , options ) { if ( start === stop ) { return { pattern : String ( start ) , digits : [ ] } ; } var zipped = zip ( String ( start ) , String ( stop ) ) ; var len = zipped . length , i = - 1 ; var pattern = '' ; var digits = 0 ; while ( ++ i < len ) { var numbers = zipped [ i ] ; var startDigit = numbers [ 0 ] ; var stopDigit = numbers [ 1 ] ; if ( startDigit === stopDigit ) { pattern += startDigit ; } else if ( startDigit !== '0' || stopDigit !== '9' ) { pattern += toCharacterClass ( startDigit , stopDigit ) ; } else { digits += 1 ; } } if ( digits ) { pattern += options . shorthand ? '\\d' : '[0-9]' ; } return { pattern : pattern , digits : [ digits ] } ; }


Input: Zip strings ( for in can be used on string characters ) [CODESPLIT] function zip ( a , b ) { var arr = [ ] ; for ( var ch in a ) arr . push ( [ a [ ch ] , b [ ch ] ] ) ; return arr ; }


Input: Call plugin fn . If a function is returned push it into the fns array to be called by the run method . [CODESPLIT] function use ( type , fn , options ) { var offset = 1 ; if ( typeof type === 'string' || Array . isArray ( type ) ) { fn = wrap ( type , fn ) ; offset ++ ; } else { options = fn ; fn = type ; } if ( typeof fn !== 'function' ) { throw new TypeError ( 'expected a function' ) ; } var self = this || app ; var fns = self [ prop ] ; var args = [ ] . slice . call ( arguments , offset ) ; args . unshift ( self ) ; if ( typeof opts . hook === 'function' ) { opts . hook . apply ( self , args ) ; } var val = fn . apply ( self , args ) ; if ( typeof val === 'function' && fns . indexOf ( val ) === - 1 ) { fns . push ( val ) ; } return self ; }


Input: Wrap a named plugin function so that it s only called on objects of the given type [CODESPLIT] function wrap ( type , fn ) { return function plugin ( ) { return this . type === type ? fn . apply ( this , arguments ) : plugin ; } ; }


Input: / methods /// [CODESPLIT] function processArguments ( ) { var arg ; for ( var i = 2 ; i < process . argv . length ; ++ i ) { arg = process . argv [ i ] ; if ( arg === "-l" || arg === "-log" ) enableLog = true ; else if ( arg === "-m" || arg === "--minify" ) enableMinify = true ; else if ( arg === "-f" || arg === "--folder" ) inputIsFolder = true ; else if ( arg === "-s" || arg === "--silent" ) enableSilent = true ; else if ( arg === "-i" || arg === "--input" ) input = process . argv [ ++ i ] ; else if ( arg === "-o" || arg === "--output" ) output = process . argv [ ++ i ] ; else if ( arg === "-e" || arg === "--ensure" ) includeInq = true ; else if ( arg === "-d" || arg === "--define" ) definitions = process . argv [ ++ i ] . split ( ' ' ) ; else console . error ( "[WARNING] Unknown compiler flag: " + arg ) ; } if ( ! output ) output = input + ( inputIsFolder ? "" : ".js" ) ; return ! ! input ; }


Input: / private methods /// [CODESPLIT] function tryInit ( ) { var temp , i , files ; if ( ! processors . length ) { var processorsPath = path . resolve ( __dirname , "processor" ) ; files = fs . readdirSync ( processorsPath ) ; for ( i = 0 ; i < files . length ; ++ i ) { temp = require ( path . resolve ( processorsPath , files [ i ] ) ) ; processors . push ( temp ) ; processorsNamed [ temp . name ] = temp ; } } if ( ! complexExpressions . length ) { var expressionsPath = path . resolve ( __dirname , "combination" ) ; files = fs . readdirSync ( expressionsPath ) ; for ( i = 0 ; i < files . length ; ++ i ) { temp = require ( path . resolve ( expressionsPath , files [ i ] ) ) ; complexExpressions [ temp . name ] = temp . value ; } } }


Input: CalEvent object [CODESPLIT] function CalEvent ( name , startDate , endDate , description , location , uid ) { if ( startDate instanceof Date ) { this . startDate = startDate ; } else { return null ; } if ( endDate instanceof Date ) { this . endDate = endDate ; } else { return null ; } this . uid = uid == null ? ( util . guid ( ) + '@node-cal-event.js' ) : uid ; this . summary = name ; this . location = location ; this . description = description ; }


Input: Public functions [CODESPLIT] function ask ( questions ) { "use strict" ; let answers = { } ; let i = 0 ; return new Promise ( function ( resolve , reject ) { function askQuestion ( item ) { let key = item . key ; let msg = item . msg ; let fn = fnList [ item . fn ] ; if ( ! key ) { throw new Error ( 'A value for `key` must be defined for question ' + i ) ; } if ( ! msg ) { throw new Error ( 'A value for `msg` must be defined for question ' + i ) ; } if ( ! fn ) { throw new Error ( 'A value for `fn` must be "prompt", "confirm", or "multiline" for question ' + i ) ; } if ( fn ) { fn ( msg , key , answers ) . then ( function ( ) { next ( ) ; } ) ; } } function next ( ) { if ( i < questions . length ) { var question = questions [ i ] ; i ++ ; askQuestion ( question ) ; } else { resolve ( answers ) ; } } next ( ) ; } ) ; }


Input: Private functions [CODESPLIT] function promiseFn ( msg , key , answers , fn ) { "use strict" ; answers = answers || { } ; return fn ( msg ) . then ( function ( resp ) { answers [ key ] = resp ; return answers ; } ) ; }


Input: create a middleware stack ( obj obj [ fn ( obj obj fn? ) ] fn ) - > null [CODESPLIT] function httpMiddleware ( req , res , arr , done ) { done = done || noop assert . ok ( isReq ( req ) , 'is incoming message' ) assert . ok ( isRes ( res ) , 'is server response' ) assert . ok ( Array . isArray ( arr ) , 'is array' ) assert . equal ( typeof done , 'function' , 'is function' ) mapLimit ( arr , 1 , iterator , done ) function iterator ( fn , next ) { next = dezalgo ( next ) if ( fn . length === 3 ) return fn ( req , res , next ) fn ( req , res ) next ( ) } }


Input: Caches results of unary or binary function . [CODESPLIT] function memoize ( fun ) { // Making cache = {} an optional ES6 parameter breaks coverage. Why? /** @type {({ [key: string]: any })} */ const cache = { } ; if ( fun . length === 1 ) { return ( /** @type {any} */ arg ) => { if ( arg in cache ) { return cache [ arg ] ; } const result = fun ( arg ) ; cache [ arg ] = result ; return result ; } ; } return ( /** @type {any} */ arg1 , /** @type {any} */ arg2 ) => { if ( cache [ arg1 ] && arg2 in cache [ arg1 ] ) { return cache [ arg1 ] [ arg2 ] ; } const result = fun ( arg1 , arg2 ) ; if ( ! cache [ arg1 ] ) { cache [ arg1 ] = { } ; } cache [ arg1 ] [ arg2 ] = result ; return result ; } ; }


Input: Creates all the task definition to shut down ( detach ) all instances in origin . [CODESPLIT] function generateDetachTasks ( planner , origin , opts ) { _ . forIn ( origin . topology . containers , function ( container ) { var stopSubTask = { cmd : 'stop' , id : container . id , parent : container . containedBy } ; var removeSubTask = { cmd : 'remove' , id : container . id , parent : container . containedBy } ; var unlinkSubTask = { cmd : 'unlink' , id : container . id , parent : container . containedBy } ; var detachOp = { preconditions : containerStatus ( container , 'running' ) , subTasks : [ unlinkSubTask , stopSubTask , removeSubTask ] } ; var unlinkPreconditions = containerStatus ( container , 'running' ) ; var stopPrecondition = containerStatus ( container , 'started' ) ; var removePrecondition = containerStatus ( container , 'added' ) ; container . contains . forEach ( function ( contained ) { var status = containerStatus ( { id : contained } , 'started' ) ; stopPrecondition = _ . merge ( stopPrecondition , status ) ; detachOp . subTasks . splice ( 1 , 0 , { cmd : 'detach' , id : contained } ) ; } ) ; if ( opts . mode === 'safe' ) { allParentsIds ( origin , container ) . forEach ( function ( id ) { detachOp . subTasks . unshift ( { cmd : 'unlink' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; detachOp . subTasks . push ( { cmd : 'link' , id : id , parent : origin . topology . containers [ id ] . containedBy } ) ; } ) ; } planner . addTask ( { cmd : 'detach' , id : container . id } , { preconditions : containerStatus ( container , 'detached' ) , subTasks : [ { cmd : 'nop' } ] } ) ; planner . addTask ( { cmd : 'detach' , id : container . id } , detachOp ) ; planner . addTask ( unlinkSubTask , { preconditions : unlinkPreconditions , effects : containerStatus ( container , { running : false } ) } ) ; planner . addTask ( unlinkSubTask , { preconditions : containerStatus ( container , { running : false } ) , subTasks : [ { cmd : 'nop' } ] } ) ; planner . addTask ( stopSubTask , { preconditions : containerStatus ( container , 'started' ) , effects : containerStatus ( container , 'added' ) } ) ; planner . addTask ( stopSubTask , { preconditions : containerStatus ( container , { running : false , started : false } ) , subTasks : [ { cmd : 'nop' } ] } ) ; planner . addTask ( removeSubTask , { preconditions : removePrecondition , effects : containerStatus ( container , 'detached' ) } ) ; planner . addTask ( removeSubTask , { preconditions : containerStatus ( container , 'detached' ) , subTasks : [ { cmd : 'nop' } ] } ) ; } ) ; }


Input: Protects the given object by wrapping it in a Proxy . [CODESPLIT] function keyblade ( obj , opts ) { opts = Object . assign ( { message : _defaultMessage , logBeforeThrow : true , ignore : [ ] } , opts ) opts . ignore = ( opts . ignore && Array . isArray ( opts . ignore ) ) ? opts . ignore : [ ] return new Proxy ( obj , { get ( target , propKey , receiver ) { const useGetter = Reflect . has ( target , propKey , receiver ) || _isReserved ( propKey , opts . ignore ) if ( useGetter ) { return Reflect . get ( target , propKey , receiver ) } // Leave symbols alone. if ( typeof propKey === 'symbol' ) { return Reflect . get ( target , propKey , receiver ) } const message = opts . message ( propKey ) if ( opts . logBeforeThrow ) { if ( typeof opts . logBeforeThrow === 'function' ) { opts . logBeforeThrow ( message , propKey ) } else { console . error ( message ) } } throw new UndefinedKeyError ( message ) } } ) }


Input: LINEAR CORRELATION // FUNCTION : pcorr ( arr1 [ arr2 ... ] ) Computes Pearson product - moment correlation coefficients between one or more numeric arrays . [CODESPLIT] function pcorr ( ) { var args , nArgs , len , deltas , delta , means , stdevs , C , cov , corr , arr , N , r , A , B , sum , val , sigma , i , j , n ; args = Array . prototype . slice . call ( arguments ) ; nArgs = args . length ; if ( ! nArgs ) { throw new Error ( 'pcorr()::insufficient input arguments. Must provide array arguments.' ) ; } for ( i = 0 ; i < nArgs ; i ++ ) { if ( ! Array . isArray ( args [ i ] ) ) { throw new TypeError ( 'pcorr()::invalid input argument. Must provide array arguments.' ) ; } } if ( Array . isArray ( args [ 0 ] [ 0 ] ) ) { // If the first argument is an array of arrays, calculate the correlation matrix over the nested arrays, disregarding any other arguments... args = args [ 0 ] ; } nArgs = args . length ; len = args [ 0 ] . length ; for ( i = 1 ; i < nArgs ; i ++ ) { if ( args [ i ] . length !== len ) { throw new Error ( 'pcorr()::invalid input argument. All arrays must have equal length.' ) ; } } // [0] Initialization... deltas = new Array ( nArgs ) ; means = new Array ( nArgs ) ; stdevs = new Array ( nArgs ) ; C = new Array ( nArgs ) ; cov = new Array ( nArgs ) ; corr = new Array ( nArgs ) ; for ( i = 0 ; i < nArgs ; i ++ ) { means [ i ] = args [ i ] [ 0 ] ; arr = new Array ( nArgs ) ; for ( j = 0 ; j < nArgs ; j ++ ) { arr [ j ] = 0 ; } C [ i ] = arr ; cov [ i ] = arr . slice ( ) ; // copy! corr [ i ] = arr . slice ( ) ; // copy! } if ( len < 2 ) { return corr ; } // [1] Compute the covariance... for ( n = 1 ; n < len ; n ++ ) { N = n + 1 ; r = n / N ; // [a] Extract the values and compute the deltas... for ( i = 0 ; i < nArgs ; i ++ ) { deltas [ i ] = args [ i ] [ n ] - means [ i ] ; } // [b] Update the covariance between one array and every other array... for ( i = 0 ; i < nArgs ; i ++ ) { arr = C [ i ] ; delta = deltas [ i ] ; for ( j = i ; j < nArgs ; j ++ ) { A = arr [ j ] ; B = r * delta * deltas [ j ] ; sum = A + B ; // Exploit the fact that the covariance matrix is symmetric... if ( i !== j ) { C [ j ] [ i ] = sum ; } arr [ j ] = sum ; } // end FOR j } // end FOR i // [c] Update the means... for ( i = 0 ; i < nArgs ; i ++ ) { means [ i ] += deltas [ i ] / N ; } } // end FOR n // [2] Normalize the co-moments... n = N - 1 ; for ( i = 0 ; i < nArgs ; i ++ ) { arr = C [ i ] ; for ( j = i ; j < nArgs ; j ++ ) { val = arr [ j ] / n ; cov [ i ] [ j ] = val ; if ( i !== j ) { cov [ j ] [ i ] = val ; } } } // [3] Compute the standard deviations... for ( i = 0 ; i < nArgs ; i ++ ) { // Diagonal elements of covariance matrix... stdevs [ i ] = Math . sqrt ( cov [ i ] [ i ] ) ; } // [4] Set the diagonal elements to 1: for ( i = 0 ; i < nArgs ; i ++ ) { corr [ i ] [ i ] = 1 ; } // [5] Compute the correlation coefficients... for ( i = 0 ; i < nArgs ; i ++ ) { arr = cov [ i ] ; sigma = stdevs [ i ] ; for ( j = i + 1 ; j < nArgs ; j ++ ) { val = arr [ j ] / ( sigma * stdevs [ j ] ) ; // Address floating point errors introduced by taking the sqrt and enforce strict [-1,1] bounds... if ( val > 1 ) { val = 1 ; } else if ( val < - 1 ) { val = - 1 ; } corr [ i ] [ j ] = val ; corr [ j ] [ i ] = val ; } } return corr ; }


Input: Get or build a sub register for an object . [CODESPLIT] function subRegister ( obj , name ) { var res ; res = isPrimitive ( obj [ name ] ) ? { } : obj [ name ] ; return obj [ name ] = mixable ( res ) . mixin ( proto , 'register' , 'extend' ) ; }


Input: Try to handle with require () . [CODESPLIT] function registerMod ( leaf , dir , name ) { var modPath ; try { modPath = require . resolve ( dir ) ; } catch ( _error ) { } if ( modPath == null ) { return false ; } // Define a getter with the base name. name = path . basename ( name , path . extname ( name ) ) ; Object . defineProperty ( leaf , name , { configurable : true , enumerable : true , get : function ( ) { if ( require . cache [ modPath ] == null ) { debug ( 'loading %s.' , modPath ) ; } return require ( modPath ) ; } } ) ; return true ; }


Input: Try to handle as a directory . [CODESPLIT] function registerDir ( leaf , dir , name ) { var files ; try { files = fs . readdirSync ( dir ) ; } catch ( _error ) { } if ( files == null ) { return false ; } if ( name != null ) { leaf = subRegister ( leaf , name ) ; } for ( var i = 0 , len = files . length ; i < len ; i ++ ) { name = files [ i ] ; leaf . register ( dir , name ) ; } return true ; }


Input: Register . [CODESPLIT] function register ( root ) { var leaf = this ; // jscs:ignore safeContextKeyword // TODO: default base path? var dir = path . resolve ( root ) ; // Try as a directory if no name given. if ( arguments . length <= 1 ) { registerDir ( this , dir ) ; return this ; } // The names are not only path to the files but also path to the attributes. for ( var i = 1 , len = arguments . length - 1 ; i < len ; i ++ ) { var sub = arguments [ i ] ; leaf = subRegister ( leaf , sub ) ; dir = path . resolve ( dir , sub ) ; } // Only the last name is registered (others are used as the path; see above). var name = arguments [ i ++ ] ; dir = path . resolve ( dir , name ) ; // Handle with require if possible. if ( registerMod ( leaf , dir , name ) ) { return this ; } // Handle as a directory if possible. registerDir ( leaf , dir , name ) ; return this ; }


Input: A small helper which allows us to just use all of our existing . / middleware / * . js and . / params / * . js targeted at express with socket . io . This is in an effort to reuse as much code as possible and lower the probability of oops bugs as in Oops! I changed it in middleware / ns . js and tested it but I forgot got to update it in io . js : ( . [CODESPLIT] function applyMiddleware ( socket , req , done ) { // A stub for the `res` argument express usually provides. var res = { } ; // Map the socket.io request into a `req` like stub as well. var params = clone ( req ) ; assign ( params , { session_id : socket . decoded_token . session_id , deployment_id : socket . decoded_token . deployment_id } ) ; req = { params : params , query : { } , body : { } } ; // Yay! Now we can just use all of our existing middleware! series ( { 'Load token data' : partial ( Token . load , socket . decoded_token , req ) , 'Add typed param getters' : partial ( typedParams , req , res ) , 'Parse the namespace param if presented' : function ( next ) { unpackNamespaceParam ( req , res , next , req . params . ns ) ; } , 'The collection must already exist' : partial ( collectionRequired , req , res ) , 'Parse sample options' : partial ( sampleOptions , req , res ) } , function ( err ) { if ( err ) { return done ( err ) ; } debug ( 'middleware applied successfully' , req ) ; done ( null , req ) ; } ) ; }