Input: Make functions that will define virtual modules [CODESPLIT] function makeDefineVirtualModule ( loader , load , addDep , args ) { function namer ( loadName ) { var baseName = loadName . substr ( 0 , loadName . indexOf ( "!" ) ) ; return function ( part , plugin ) { return baseName + "-" + part + ( plugin ? ( "." + plugin ) : "" ) ; } ; } function addresser ( loadAddress ) { return function ( part , plugin ) { var base = loadAddress + "." + part ; return base + ( plugin ? ( "." + plugin ) : "" ) ; } ; } var name = namer ( load . name ) ; var address = addresser ( load . address ) ; // A function for disposing of modules during live-reload var disposeModule = function ( moduleName ) { if ( loader . has ( moduleName ) ) loader [ "delete" ] ( moduleName ) ; } ; if ( loader . liveReloadInstalled || loader . has ( "live-reload" ) ) { loader . import ( "live-reload" , { name : module . id } ) . then ( function ( reload ) { disposeModule = reload . disposeModule || disposeModule ; } ) ; } return function ( defn ) { if ( defn . condition ) { if ( defn . arg ) { // viewModel args . push ( defn . arg ) ; } var moduleName = typeof defn . name === "function" ? defn . name ( name ) : name ( defn . name ) ; var moduleAddress = typeof defn . address === "function" ? defn . address ( address ) : address ( defn . address ) ; // from="something.js" if ( defn . from ) { addDep ( defn . from , false ) ; } else if ( defn . getLoad ) { var moduleSource = defn . source ( ) ; return defn . getLoad ( moduleName ) . then ( function ( newLoad ) { moduleName = newLoad . name || moduleName ; // For live-reload disposeModule ( moduleName ) ; loader . define ( moduleName , moduleSource , { metadata : newLoad . metadata , address : moduleAddress } ) ; addDep ( moduleName ) ; } ) ; } else if ( defn . source ) { addDep ( moduleName ) ; if ( loader . has ( moduleName ) ) loader [ "delete" ] ( moduleName ) ; if ( typeof defn . source !== "string" ) { return Promise . resolve ( defn . source ) . then ( function ( source ) { loader . define ( moduleName , source , { address : address ( defn . name ) , metadata : defn . metadata } ) ; } ) ; } return loader . define ( moduleName , defn . source , { address : address ( defn . name ) } ) ; } } } }


Input: !steal - remove - start [CODESPLIT] function getFilename ( name ) { var hash = name . indexOf ( '#' ) ; var bang = name . indexOf ( '!' ) ; return name . slice ( hash < bang ? ( hash + 1 ) : 0 , bang ) ; }


Input: !steal - remove - end [CODESPLIT] function translate ( load ) { var filename ; //!steal-remove-start filename = getFilename ( load . name ) ; //!steal-remove-end var localLoader = this . localLoader || this , result = parse ( load . source ) , tagName = result . tagName , texts = result . texts , types = result . types , froms = result . froms , normalize = function ( str ) { return localLoader . normalize ( str , module . id ) ; } , deps = [ normalize ( "can-component" ) ] , ases = [ "Component" ] , addDep = function ( depName , isVirtual ) { deps . push ( depName ) ; if ( isVirtual !== false ) load . metadata . virtualDeps . push ( depName ) ; } , stylePromise , templatePromise ; load . metadata . virtualDeps = [ ] ; var defineVirtualModule = makeDefineVirtualModule ( localLoader , load , addDep , ases ) ; // Define the template templatePromise = defineVirtualModule ( { condition : froms . template || froms . view || result . intermediate . length , arg : "view" , name : "view" , from : froms . template || froms . view , source : templateDefine ( result , normalize , filename ) , metadata : { originalSource : load . source , importSpecifiers : getImportSpecifiers ( result ) } } ) ; // Define the ViewModel defineVirtualModule ( { condition : froms [ "view-model" ] || texts [ "view-model" ] , arg : "ViewModel" , name : "view-model" , from : froms [ "view-model" ] , source : texts [ "view-model" ] } ) ; // Define events defineVirtualModule ( { condition : froms . events || texts . events , arg : "events" , name : "events" , from : froms . events , source : texts . events } ) ; // Define helpers defineVirtualModule ( { condition : froms . helpers || texts . helpers , arg : "helpers" , name : "helpers" , from : froms . helpers , source : texts . helpers } ) ; // Define simple-helpers defineVirtualModule ( { condition : froms [ "simple-helpers" ] || texts [ "simple-helpers" ] , arg : "simpleHelpers" , name : "simple-helpers" , from : froms [ "simple-helpers" ] , source : texts [ "simple-helpers" ] } ) ; // Define the styles stylePromise = defineVirtualModule ( { condition : froms . style || texts . style , name : function ( name ) { return name ( "style" , types . style || "css" ) + "!" } , address : function ( address ) { return address ( "style" , types . style ) ; } , source : function ( ) { var styleText = texts . style ; if ( types . style === "less" ) { var styleText = tagName + " {\n" + texts . style + "}\n" ; } return styleText ; } , getLoad : function ( styleName ) { var styleLoad = { } ; var normalizePromise = localLoader . normalize ( styleName , load . name ) ; var locatePromise = normalizePromise . then ( function ( name ) { styleName = name ; styleLoad = { name : name , metadata : { } } ; return localLoader . locate ( styleLoad ) ; } ) ; return locatePromise . then ( function ( ) { return { name : styleName , metadata : styleLoad . metadata } ; } ) ; } } ) || Promise . resolve ( ) ; return Promise . all ( [ stylePromise , templatePromise ] ) . then ( function ( ) { return Promise . all ( deps ) ; } ) . then ( function ( deps ) { return "def" + "ine(" + JSON . stringify ( deps ) + ", function(" + ases . join ( ", " ) + "){\n" + "\tvar __interop = function(m){if(m && m['default']) {return m['default'];}else if(m) return m;};\n\n" + "\tvar ViewModel = __interop(typeof ViewModel !== 'undefined' ? ViewModel : undefined);\n" + "\tvar ComponentConstructor = Component.extend({\n" + "\t\ttag: '" + tagName + "',\n" + "\t\tview: __interop(typeof view !== 'undefined' ? view : undefined),\n" + "\t\tViewModel: ViewModel,\n" + "\t\tevents: __interop(typeof events !== 'undefined' ? events : undefined),\n" + "\t\thelpers: __interop(typeof helpers !== 'undefined' ? helpers : undefined),\n" + "\t\tsimpleHelpers: __interop(typeof simpleHelpers !== 'undefined' ? simpleHelpers : undefined),\n" + "\t\tleakScope: " + result . leakScope + "\n" + "\t});\n\n" + "\treturn {\n" + "\t\tComponent: ComponentConstructor,\n" + "\t\tViewModel: ViewModel,\n" + "\t\tdefault: ComponentConstructor\n" + "\t};\n" + "});" ; } ) ; }


Input: !steal - remove - end [CODESPLIT] function ( depName , isVirtual ) { deps . push ( depName ) ; if ( isVirtual !== false ) load . metadata . virtualDeps . push ( depName ) ; }


Input: Constructor [CODESPLIT] function MIDIFile ( buffer , strictMode ) { var track ; var curIndex ; var i ; var j ; // If not buffer given, creating a new MIDI file if ( ! buffer ) { // Creating the content this . header = new MIDIFileHeader ( ) ; this . tracks = [ new MIDIFileTrack ( ) ] ; // if a buffer is provided, parsing him } else { buffer = ensureArrayBuffer ( buffer ) ; // Minimum MIDI file size is a headerChunk size (14bytes) // and an empty track (8+3bytes) if ( 25 > buffer . byteLength ) { throw new Error ( 'A buffer of a valid MIDI file must have, at least, a' + ' size of 25bytes.' ) ; } // Reading header this . header = new MIDIFileHeader ( buffer , strictMode ) ; this . tracks = [ ] ; curIndex = MIDIFileHeader . HEADER_LENGTH ; // Reading tracks for ( i = 0 , j = this . header . getTracksCount ( ) ; i < j ; i ++ ) { // Testing the buffer length if ( strictMode && curIndex >= buffer . byteLength - 1 ) { throw new Error ( "Couldn't find datas corresponding to the track #" + i + '.' ) ; } // Creating the track object track = new MIDIFileTrack ( buffer , curIndex , strictMode ) ; this . tracks . push ( track ) ; // Updating index to the track end curIndex += track . getTrackLength ( ) + 8 ; } // Testing integrity : curIndex should be at the end of the buffer if ( strictMode && curIndex !== buffer . byteLength ) { throw new Error ( 'It seems that the buffer contains too much datas.' ) ; } } }


Input: MIDIFileTrack : Read and edit a MIDI track chunk in a given ArrayBuffer [CODESPLIT] function MIDIFileTrack ( buffer , start ) { let a ; let trackLength ; // no buffer, creating him if ( ! buffer ) { a = new Uint8Array ( 12 ) ; // Adding the empty track header (MTrk) a [ 0 ] = 0x4d ; a [ 1 ] = 0x54 ; a [ 2 ] = 0x72 ; a [ 3 ] = 0x6b ; // Adding the empty track size (4) a [ 4 ] = 0x00 ; a [ 5 ] = 0x00 ; a [ 6 ] = 0x00 ; a [ 7 ] = 0x04 ; // Adding the track end event a [ 8 ] = 0x00 ; a [ 9 ] = 0xff ; a [ 10 ] = 0x2f ; a [ 11 ] = 0x00 ; // Saving the buffer this . datas = new DataView ( a . buffer , 0 , MIDIFileTrack . HDR_LENGTH + 4 ) ; // parsing the given buffer } else { if ( ! ( buffer instanceof ArrayBuffer ) ) { throw new Error ( 'Invalid buffer received.' ) ; } // Buffer length must size at least like an  empty track (8+3bytes) if ( 12 > buffer . byteLength - start ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' Buffer length must size at least 12bytes' ) ; } // Creating a temporary view to read the track header this . datas = new DataView ( buffer , start , MIDIFileTrack . HDR_LENGTH ) ; // Reading MIDI track header chunk if ( ! ( 'M' === String . fromCharCode ( this . datas . getUint8 ( 0 ) ) && 'T' === String . fromCharCode ( this . datas . getUint8 ( 1 ) ) && 'r' === String . fromCharCode ( this . datas . getUint8 ( 2 ) ) && 'k' === String . fromCharCode ( this . datas . getUint8 ( 3 ) ) ) ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' MTrk prefix not found' ) ; } // Reading the track length trackLength = this . getTrackLength ( ) ; if ( buffer . byteLength - start < trackLength ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' The track size exceed the buffer length.' ) ; } // Creating the final DataView this . datas = new DataView ( buffer , start , MIDIFileTrack . HDR_LENGTH + trackLength ) ; // Trying to find the end of track event if ( ! ( 0xff === this . datas . getUint8 ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 3 ) ) && 0x2f === this . datas . getUint8 ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 2 ) ) && 0x00 === this . datas . getUint8 ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 1 ) ) ) ) { throw new Error ( 'Invalid MIDIFileTrack (0x' + start . toString ( 16 ) + ') :' + ' No track end event found at the expected index' + ' (' + ( MIDIFileTrack . HDR_LENGTH + ( trackLength - 1 ) ) . toString ( 16 ) + ').' ) ; } } }


Input: Match protocols using semver ~ matching . [CODESPLIT] function matchSemver ( myProtocol , senderProtocol , callback ) { const mps = myProtocol . split ( '/' ) const sps = senderProtocol . split ( '/' ) const myName = mps [ 1 ] const myVersion = mps [ 2 ] const senderName = sps [ 1 ] const senderVersion = sps [ 2 ] if ( myName !== senderName ) { return callback ( null , false ) } // does my protocol satisfy the sender? const valid = semver . satisfies ( myVersion , '~' + senderVersion ) callback ( null , valid ) }


Input: prefixes a message with a varint TODO this is a pull - stream creep ( pull stream to add a byte? ) [CODESPLIT] function encode ( msg , callback ) { pull ( values ( Buffer . isBuffer ( msg ) ? [ msg ] : [ Buffer . from ( msg ) ] ) , pullLP . encode ( ) , collect ( ( err , encoded ) => { if ( err ) { return callback ( err ) } callback ( null , encoded [ 0 ] ) } ) ) }


Input: Match protocols exactly . [CODESPLIT] function matchExact ( myProtocol , senderProtocol , callback ) { const result = myProtocol === senderProtocol callback ( null , result ) }


Input: Diff two arrays . [CODESPLIT] function diffArrays ( arr1 , arr2 ) { if ( ! Array . isArray ( arr1 ) || ! Array . isArray ( arr2 ) ) { return true ; } if ( arr1 . length !== arr2 . length ) { return true ; } for ( var i = 0 , len = arr1 . length ; i < len ; i ++ ) { if ( arr1 [ i ] !== arr2 [ i ] ) { return true ; } } return false ; }


Input: Turn the rules for a sourceType into a human - readable string [CODESPLIT] function getSourceRuleString ( sourceRule ) { function getRuleString ( rule ) { if ( rule . length === 1 ) { return '"' + rule + '"' ; } return '("' + rule . join ( '" AND "' ) + '")' ; } return sourceRule . map ( getRuleString ) . join ( ' OR ' ) ; }


Input: Get the arguments for the timeline based on parameter rules [CODESPLIT] function getTimelineArgs ( scope ) { var timelineArgs = { sourceType : scope . sourceType } ; // if this is a valid sourceType... if ( rules . hasOwnProperty ( scope . sourceType ) ) { var sourceRules = rules [ scope . sourceType ] ; var valid = false ; // Loop over the required args for the source for ( var i = 0 , len = sourceRules . length ; i < len ; i ++ ) { var rule = sourceRules [ i ] ; var params = { } ; for ( var j = 0 , ruleLen = rule . length ; j < ruleLen ; j ++ ) { if ( angular . isDefined ( scope [ rule [ j ] ] ) ) { // if the rule is present, add it to the params collection params [ rule [ j ] ] = scope [ rule [ j ] ] ; } } if ( Object . keys ( params ) . length === ruleLen ) { angular . merge ( timelineArgs , params ) ; valid = true ; break ; } } if ( ! valid ) { throw new TimelineArgumentException ( scope . sourceType , 'args: ' + getSourceRuleString ( sourceRules ) ) ; } } else { throw new TimelineArgumentException ( scope . sourceType , 'unknown type' ) ; } return timelineArgs ; }


Input: find method in klass prototype chain [CODESPLIT] function ( method , klass ) { while ( ! ! klass ) { var key = null , pro = klass . prototype ; // find method in current klass Object . keys ( pro ) . some ( function ( name ) { if ( method === pro [ name ] ) { key = name ; return ! 0 ; } } ) ; // method finded in klass if ( key != null ) { return { name : key , klass : klass } ; } klass = klass . supor ; } }


Input: dump files to temporary directory [CODESPLIT] function ( config ) { _logger . info ( 'begin dump files ...' ) ; var map = { } ; [ 'fileInclude' , 'fileExclude' ] . forEach ( function ( name ) { var value = config [ name ] ; if ( ! ! value ) { if ( typeof value === 'string' ) { var reg = new RegExp ( value , 'i' ) ; config [ name ] = function ( file ) { return reg . test ( file ) ; } ; } else if ( ! ! value . test ) { config [ name ] = function ( file ) { return value . test ( file ) ; } } } if ( ! _util . isFunction ( config [ name ] ) ) { var flag = name !== 'fileExclude' ; config [ name ] = function ( file ) { return flag ; } ; } } ) ; ( config . resRoot || '' ) . split ( ',' ) . forEach ( function ( dir ) { if ( ! dir ) { return ; } var ret = _fs . lsfile ( dir , function ( name , file ) { return ! config . fileExclude ( file ) && config . fileInclude ( file ) ; } ) ; ret . forEach ( function ( v ) { map [ v ] = v . replace ( config . webRoot , config . temp ) ; } ) ; } ) ; _logger . debug ( 'package file map -> %j' , map ) ; Object . keys ( map ) . forEach ( function ( src ) { var dst = map [ src ] ; _fs . copy ( src , dst , function ( a ) { _logger . info ( 'copy file %s' , a ) ; } ) ; } ) ; }


Input: zip files package [CODESPLIT] function ( config ) { _logger . info ( 'begin zip package ...' ) ; var cmd = [ 'java' , '-jar' , JSON . stringify ( config . zip ) , JSON . stringify ( config . temp ) , JSON . stringify ( config . output ) ] . join ( ' ' ) ; _logger . debug ( 'do command: %s' , cmd ) ; exec ( cmd , function ( error , stdout , stderr ) { if ( error ) { _logger . error ( 'zip package error for reason:\n%s' , error . stack ) ; process . abort ( ) ; return ; } if ( stdout ) { _logger . info ( stdout ) ; } if ( stderr ) { _logger . error ( stderr ) ; } uploadToServer ( config ) ; } ) ; }


Input: upload package to web cache server [CODESPLIT] function ( config ) { if ( ! _fs . exist ( config . output ) ) { return abortProcess ( config , 'no package to be uploaded' ) ; } _logger . info ( 'begin build upload form ...' ) ; var form = new FormData ( ) ; var ex = _util . merge ( { version : '0.1' , platform : 'ios&android' } , config . extension ) ; // build form Object . keys ( ex ) . forEach ( function ( name ) { form . append ( name , ex [ name ] ) ; } ) ; form . append ( 'token' , config . token ) ; form . append ( 'resID' , config . appid ) ; form . append ( 'appID' , config . nativeId ) ; form . append ( 'userData' , JSON . stringify ( { domains : config . domains } ) ) ; form . append ( 'zip' , fs . createReadStream ( config . output ) ) ; // submit form _logger . info ( 'begin upload package to web cache server ...' ) ; form . submit ( config . api , function ( err , res ) { if ( err ) { return abortProcess ( config , 'upload failed for reason:\n%s' , err . stack ) ; } // chunk response data var arr = [ ] ; res . on ( 'data' , function ( chunk ) { arr . push ( chunk ) ; } ) ; // parse response result res . on ( 'end' , function ( ) { var ret = null , txt = arr . join ( '' ) ; try { ret = JSON . parse ( txt ) ; } catch ( ex ) { // result error return abortProcess ( config , '[%s] %s\n%s' , res . statusCode , txt , ex . stack ) ; } if ( ! ! ret && ret . code == 0 ) { clearTemp ( config ) ; _logger . info ( 'package upload success' ) ; config . ondone ( ) ; } else { return abortProcess ( config , 'package upload failed for reason: [%s] %s' , res . statusCode , txt ) ; } } ) ; res . resume ( ) ; } ) ; }


Input: clear temporary infomation [CODESPLIT] function ( config ) { _logger . info ( 'clear temporary directory and files' ) ; _fs . rmdir ( config . temp ) ; _fs . rm ( config . output ) ; }


Input: abort process when error [CODESPLIT] function ( config ) { var args = [ ] . slice . call ( arguments , 0 ) ; clearTemp ( args . shift ( ) ) ; _logger . error . apply ( _logger , args ) ; process . abort ( ) ; }


Input: dump dependency config [CODESPLIT] function ( content ) { var ret , handler = function ( map ) { ret = map ; } , sandbox = { NEJ : { deps : handler , config : handler } } ; // detect dep config try { //eval(content); vm . createContext ( sandbox ) ; vm . runInContext ( content , sandbox ) ; } catch ( ex ) { // ignore } return ret || null ; }


Input: parse nej patch [CODESPLIT] function ( patform , deps , func ) { var args = exports . formatARG . apply ( exports , arguments ) ; if ( ! this . patches ) { this . patches = [ ] ; } // illegal patch if ( ! args [ 0 ] ) { return ; } // cache patch config this . patches . push ( { expression : args [ 0 ] , dependency : args [ 1 ] , source : ( args [ 2 ] || '' ) . toString ( ) } ) ; }


Input: eval content to dump nej patch [CODESPLIT] function ( content ) { // emulate NEJ patch env var ret = { } , sandbox = { NEJ : { patch : _doPatch . bind ( ret ) } } ; // eval content for nej patch check try { //eval(util.format('(%s)();',content)); vm . createContext ( sandbox ) ; vm . runInContext ( util . format ( '(%s)();' , content ) , sandbox ) ; } catch ( ex ) { // ignore } return ret . patches ; }


Input: do nej define [CODESPLIT] function ( uri , deps , func ) { var args = exports . formatARG . apply ( exports , arguments ) ; this . isNEJ = ! 0 ; this . dependency = args [ 1 ] ; this . source = ( args [ 2 ] || '' ) . toString ( ) ; }


Input: for 2 . 0a< = or 2 . 0a = or 2 . 0a > = [CODESPLIT] function ( result , exp ) { switch ( exp . op ) { case '<' : case '<=' : result . lower = exp ; break ; case '>' : case '>=' : result . upper = exp ; break ; case '=' : case '==' : result . midle = exp ; break ; } delete exp . op ; }


Input: for < = 2 . 0a or = 2 . 0a or > = 2 . 0a [CODESPLIT] function ( result , exp ) { switch ( exp . op ) { case '<' : case '<=' : // check over write upper var upper = result . upper ; if ( ! upper || exp . value <= upper . value ) { result . upper = exp ; if ( ! ! upper ) { exp . eq = upper . eq && exp . eq ; } } break ; case '>' : case '>=' : // check over write lower var lower = result . lower ; if ( ! lower || exp . value >= lower . value ) { result . lower = exp ; if ( ! ! lower ) { exp . eq = lower . eq && exp . eq ; } } break ; case '=' : case '==' : // check over write lower var midle = result . midle ; if ( ! midle ) { result . midle = exp ; } else if ( midle . value !== exp . value ) { result . dirty = ! 0 ; delete result . midle ; } break ; } delete exp . op ; }


Input: format patch [CODESPLIT] function ( name , config ) { var patch = config . patch ; if ( ! patch ) { return ; } // cache patch content if not x.patch.js var content = _io . getFromCache ( patch ) ; if ( ! content ) { var ret = [ _path . uri2key ( patch ) , 'function(x){return x;}' , _path . uri2key ( config . uri ) ] ; _io . cache ( config . patch , util . format ( '%s(%s);' , name , ret . join ( ',' ) ) ) ; } // cache dependency list for x.patch.js if ( ! _dep . get ( patch ) ) { _dep . set ( patch , [ config . uri ] ) ; } }


Input: format plugin [CODESPLIT] function ( name , config , plugins ) { var plugin = config . plugin ; if ( ! plugin ) { return ; } // check plugin content var key = plugin + ':' + config . uri ; if ( _io . getFromCache ( key ) != null ) { return ; } // update plugin content var content = _io . getFromCache ( config . uri ) || '' ; // check content if ( typeof content !== 'string' && _util . isFunction ( content . stringify ) ) { content = content . stringify ( ) ; } // check plugin precessor var func = plugins [ plugin ] ; if ( ! ! func ) { if ( typeof func == 'string' ) { func = plugins [ func ] ; } if ( _util . isFunction ( func ) ) { var ret = func ( { file : config . uri , content : content } ) ; if ( ret != null ) { content = ret ; } } } // cache content after process _io . cache ( key , util . format ( '%s(%s,%s);' , name , _path . uri2key ( key ) , content ) ) ; }


Input: check all html file [CODESPLIT] function ( event ) { if ( event . type == 'script' ) { event . value = this . _checkResInScript ( event . file , event . content , options ) ; } }


Input: static resource [CODESPLIT] function ( uri , config ) { // c:/a/b/c.png?a=1 var arr = uri . split ( '?' ) ; var isdir = _fs . isdir ( arr [ 0 ] ) ; // check version only for file if ( config . versionStac && ! isdir ) { if ( ! ! arr [ 1 ] ) { this . emit ( 'warn' , { data : [ uri ] , message : 'static resource %s with error version' } ) ; } else { arr = _io . adjustResource ( arr [ 0 ] , config , function ( src , dst ) { this . emit ( 'debug' , { data : [ src , dst ] , message : 'copy static resource %s to %s' } ) ; } . bind ( this ) ) ; } } // update path arr [ 0 ] = this . _formatURI ( arr [ 0 ] , { fromPage : config . fromPage , pathRoot : config . output , webRoot : config . webRoot , domain : config . rsDomain } ) ; // fix last / for dir if ( isdir && ! / \/$ / . test ( arr [ 0 ] ) ) { arr [ 0 ] += '/' ; } return arr . join ( '?' ) ; }


Input: style resource [CODESPLIT] function ( uri , config ) { config = _util . merge ( config , { domain : config . csDomain } ) ; return this . _formatRSURI ( uri , '.css' , config ) ; }


Input: script resource [CODESPLIT] function ( uri , config ) { config = _util . merge ( config , { domain : config . jsDomain } ) ; return this . _formatRSURI ( uri , '.js' , config ) ; }


Input: source map file path [CODESPLIT] function ( uri , config ) { return this . _formatURI ( uri , { fromPage : config . fromPage , pathRoot : config . output , webRoot : config . webRoot } ) ; }


Input: manifest file [CODESPLIT] function ( uri , config ) { _io . resource ( 'manifested' , ! 0 ) ; return this . _formatURI ( config . manOutput , { pathRoot : config . output , webRoot : config . webRoot , domain : config . manRoot } ) ; }


Input: nej module root [CODESPLIT] function ( uri , config ) { uri = uri . replace ( config . srcRoot , config . outHtmlRoot ) ; return this . _formatURI ( uri , { pathRoot : config . output , webRoot : config . webRoot , domain : config . mdlRoot } ) ; }


Input: html path adjust [CODESPLIT] function ( uri , config ) { return uri . replace ( config . srcRoot , config . outHtmlRoot ) . replace ( config . webRoot , '/' ) ; }


Input: export klass or api [CODESPLIT] function global ( map ) { Object . keys ( map ) . forEach ( function ( key ) { var file = map [ key ] , arr = file . split ( '#' ) , mdl = require ( './lib/' + arr [ 0 ] + '.js' ) ; // for util/logger#Logger if ( ! ! arr [ 1 ] ) { // for util/logger#level,logger var brr = arr [ 1 ] . split ( ',' ) ; if ( brr . length > 1 ) { var ret = { } ; brr . forEach ( function ( name ) { ret [ name ] = mdl [ name ] ; } ) ; mdl = ret ; } else { mdl = mdl [ brr [ 0 ] ] ; } } exports [ key ] = mdl ; } ) ; }


Input: / * This is a very simple buffer for a predetermined set of events . It is unbounded . It forwards all arguments to any outlet emitter attached with sync () . [CODESPLIT] function ( src , events ) { // By default, we service the default stream events var self = this , streamEvents = [ 'data' , 'end' , 'error' , 'close' , 'fd' , 'drain' , 'pipe' ] ; this . events = events || streamEvents ; this . emitter = src ; this . eventBuffer = [ ] ; this . outlet = null ; this . events . forEach ( function ( name ) { self . emitter . addListener ( name , function ( ) { self . proxyEmit ( name , arguments ) ; } ) ; } ) ; }


Input: We don t use >>> 0 . We let the values negate . The only use of addition in Murmur uses the result of a multiplication which will be converted to unsigned integer by our 16 - bit at a time multiplication . [CODESPLIT] function fmix32 ( hash ) { hash ^= hash >>> 16 hash = multiply ( hash , 0x85ebca6b ) hash ^= hash >>> 13 hash = multiply ( hash , 0xc2b2ae35 ) hash ^= hash >>> 16 return hash }


Input: With this unused function we always make sure we have an unsigned integer value but it s not absolutely necessary . We re only interested in the integer value when we perform addition or write the value to our buffer . We do not do this within Murmur s mix function . I m leaving it in place for a benchmark where I can gauge the cost of >>> 0 . [CODESPLIT] function fmix32_pure ( hash ) { hash = ( hash ^ ( hash >>> 16 ) ) >>> 0 hash = multiply ( hash , 0x85ebca6b ) hash = ( hash ^ ( hash >>> 13 ) ) >>> 0 hash = multiply ( hash , 0xc2b2ae35 ) hash = ( hash ^ ( hash >>> 16 ) ) >>> 0 return hash }


Input: TODO Branch and leaf size can we just sort that out in a call to balance? [CODESPLIT] function Strata ( options ) { this . options = options this . options . comparator = options . comparator || compare this . journalist = new Journalist ( this , options ) this . housekeeper = new Turnstile this . writer = new Turnstile this . _cursors = [ ] }


Input: Define getters & setters . This function is the internal entry point to a lot of functionality . [CODESPLIT] function bindKeys ( scope , obj , def , parentNode , path ) { var meta , key if ( typeof obj !== 'object' || obj === null ) throw new TypeError ( 'Invalid type of value "' + obj + '", object expected.' ) Object . defineProperty ( obj , memoizedObjectKey , { value : { } , configurable : true } ) Object . defineProperty ( obj , metaKey , { value : { } , configurable : true } ) meta = obj [ metaKey ] for ( key in def ) { meta [ key ] = { keyPath : { key : key , root : path . root , target : obj } , activeNodes : [ ] , previousValues : [ ] , // Assign the current marker relevant to this object. This is in case of // arrays of objects. currentMarker : def [ key ] [ markerKey ] , valueIsArray : null } bindKey ( scope , obj , def , key , parentNode ) } }


Input: This is an internal function that s used for defining the getters and setters . [CODESPLIT] function bindKey ( scope , obj , def , key , parentNode ) { var memoizedObject = obj [ memoizedObjectKey ] var meta = obj [ metaKey ] [ key ] var branch = def [ key ] var node = branch [ 0 ] var change = ! branch [ hasDefinitionKey ] && branch [ 1 ] var definition = branch [ hasDefinitionKey ] && branch [ 1 ] var mount = branch [ 2 ] var isMarkerLast = branch [ isMarkerLastKey ] // Temporary keys. var keyPath = meta . keyPath var activeNodes = meta . activeNodes var previousValues = meta . previousValues var valueIsArray = meta . valueIsArray // For initialization, call this once. if ( branch [ isBoundToParentKey ] ) parentSetter ( obj [ key ] ) else setter ( obj [ key ] ) Object . defineProperty ( obj , key , { get : getter , set : branch [ isBoundToParentKey ] ? parentSetter : setter , enumerable : true , configurable : true } ) function getter ( ) { return memoizedObject [ key ] } // Special case for binding same node as parent. function parentSetter ( x ) { var previousValue = memoizedObject [ key ] var returnValue // Optimistically set the memoized value, so it persists even if an error // occurs after this point. memoizedObject [ key ] = x // Check for no-op. if ( x === previousValue ) return x // Need to qualify this check for non-empty value. if ( definition && x !== null && x !== void 0 ) bindKeys ( scope , x , definition , parentNode , keyPath ) else if ( change ) { returnValue = change ( parentNode , x , previousValue === void 0 ? null : previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( parentNode , returnValue , branch [ replaceAttributeKey ] ) } return x } function setter ( x ) { var value , marker , currentNode var a , b , i , j // Optimistically set the memoized value, so it persists even if an error // occurs after this point. memoizedObject [ key ] = x valueIsArray = meta . valueIsArray = Array . isArray ( x ) value = valueIsArray ? x : [ x ] for ( i = 0 , j = Math . max ( previousValues . length , value . length ) ; i < j ; i ++ ) { a = value [ i ] b = previousValues [ i ] currentNode = ! a || a !== b ? replaceNode ( a , b , i ) : null marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( i + 1 , activeNodes ) || marker ) } // Reset length to current values, implicitly deleting indices and // allowing for garbage collection. if ( value . length !== previousValues . length ) previousValues . length = activeNodes . length = value . length // Assign array mutator methods if we get an array. if ( valueIsArray ) { // Some mutators such as `sort`, `reverse`, `fill`, `copyWithin` are // not present here. That is because they trigger the array index // setter functions by assigning on them internally. // These mutators may alter length. value . pop = pop value . push = push value . shift = shift value . unshift = unshift value . splice = splice // Handle array index assignment. for ( i = 0 , j = value . length ; i < j ; i ++ ) defineIndex ( value , i ) } return x } function defineIndex ( array , i ) { var value = array [ i ] Object . defineProperty ( array , i , { get : function ( ) { return value } , set : function ( x ) { var a , b , marker , currentNode value = x a = array [ i ] b = previousValues [ i ] if ( a !== b ) currentNode = replaceNode ( a , b , i ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( i + 1 , activeNodes ) || marker ) } , enumerable : true , configurable : true } ) } function removeNode ( value , previousValue , i ) { var marker = meta . currentMarker var activeNode = activeNodes [ i ] var returnValue delete previousValues [ i ] if ( activeNode ) { delete activeNodes [ i ] if ( valueIsArray ) keyPath . index = i else delete keyPath . index if ( change ) returnValue = change ( activeNode , null , previousValue , keyPath ) else if ( definition && mount ) { keyPath . target = previousValue returnValue = mount ( activeNode , null , previousValue , keyPath ) } // If a change or mount function returns the retain element symbol, // skip removing the element from the DOM. if ( returnValue !== retainElementKey ) marker . parentNode . removeChild ( activeNode ) } } // The return value of this function is a Node to be added, otherwise null. function replaceNode ( value , previousValue , i ) { var activeNode = activeNodes [ i ] var currentNode = node var returnValue // Cast values to null if undefined. if ( value === void 0 ) value = null if ( previousValue === void 0 ) previousValue = null // If value is null, just remove the Node. if ( value === null ) { removeNode ( null , previousValue , i ) return null } if ( valueIsArray ) keyPath . index = i else delete keyPath . index previousValues [ i ] = value if ( definition ) { if ( activeNode ) removeNode ( value , previousValue , i ) currentNode = processNodes ( scope , node , definition ) keyPath . target = valueIsArray ? value [ i ] : value bindKeys ( scope , value , definition , currentNode , keyPath ) if ( mount ) { keyPath . target = value mount ( currentNode , value , null , keyPath ) } } else { currentNode = activeNode || node . cloneNode ( true ) if ( change ) { returnValue = change ( currentNode , value , previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( currentNode , returnValue , branch [ replaceAttributeKey ] ) } else { // Add default update behavior. Note that this event does not get // removed, since it is assumed that it will be garbage collected. if ( previousValue === null && ~ updateTags . indexOf ( currentNode . tagName ) ) currentNode . addEventListener ( 'input' , updateChange ( branch [ replaceAttributeKey ] , keyPath , key ) ) changeValue ( currentNode , value , branch [ replaceAttributeKey ] ) } // Do not actually add an element to the DOM if it's only a change // between non-empty values. if ( activeNode ) return null } activeNodes [ i ] = currentNode return currentNode } // Below are optimized array mutator methods. They have to exist within // this closure. Note that the native implementations of these methods do // not trigger setter functions on array indices. function pop ( ) { var i = this . length - 1 var previousValue = previousValues [ i ] var value = Array . prototype . pop . call ( this ) removeNode ( null , previousValue , i ) previousValues . length = activeNodes . length = this . length return value } function push ( ) { var i = this . length var j = i + arguments . length var marker , currentNode // Passing arguments to apply is fine. var value = Array . prototype . push . apply ( this , arguments ) for ( j = i + arguments . length ; i < j ; i ++ ) { currentNode = replaceNode ( this [ i ] , null , i ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , marker ) defineIndex ( this , i ) } return value } function shift ( ) { removeNode ( null , previousValues [ 0 ] , 0 ) Array . prototype . shift . call ( previousValues ) Array . prototype . shift . call ( activeNodes ) return Array . prototype . shift . call ( this ) } function unshift ( ) { var i = this . length var j , k , marker , currentNode // Passing arguments to apply is fine. var value = Array . prototype . unshift . apply ( this , arguments ) Array . prototype . unshift . apply ( previousValues , arguments ) Array . prototype . unshift . apply ( activeNodes , Array ( k ) ) for ( j = 0 , k = arguments . length ; j < k ; j ++ ) { currentNode = replaceNode ( arguments [ j ] , null , j ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( arguments . length , activeNodes ) || marker ) } for ( j = i + arguments . length ; i < j ; i ++ ) defineIndex ( this , i ) return value } function splice ( start , count ) { var insert = [ ] var i , j , k , value , marker , currentNode , shouldAppend for ( i = start , j = start + count ; i < j ; i ++ ) removeNode ( null , previousValues [ i ] , i ) for ( i = 2 , j = arguments . length ; i < j ; i ++ ) insert . push ( arguments [ i ] ) // Passing arguments to apply is fine. Array . prototype . splice . apply ( previousValues , arguments ) // In this case, avoid setting new values. Array . prototype . splice . apply ( activeNodes , [ start , count ] . concat ( Array ( insert . length ) ) ) value = Array . prototype . splice . apply ( this , arguments ) shouldAppend = start - count >= this . length - 1 for ( i = start + insert . length - 1 , j = start ; i >= j ; i -- ) { currentNode = replaceNode ( insert [ i - start ] , null , i ) marker = meta . currentMarker if ( currentNode ) if ( isMarkerLast && shouldAppend ) { marker . parentNode . appendChild ( currentNode ) marker . parentNode . appendChild ( marker ) } else marker . parentNode . insertBefore ( currentNode , getNextNode ( start + insert . length , activeNodes ) || marker ) } k = insert . length - count if ( k < 0 ) previousValues . length = activeNodes . length = this . length else if ( k > 0 ) for ( i = this . length - k , j = this . length ; i < j ; i ++ ) defineIndex ( this , i ) return value } }


Input: Special case for binding same node as parent . [CODESPLIT] function parentSetter ( x ) { var previousValue = memoizedObject [ key ] var returnValue // Optimistically set the memoized value, so it persists even if an error // occurs after this point. memoizedObject [ key ] = x // Check for no-op. if ( x === previousValue ) return x // Need to qualify this check for non-empty value. if ( definition && x !== null && x !== void 0 ) bindKeys ( scope , x , definition , parentNode , keyPath ) else if ( change ) { returnValue = change ( parentNode , x , previousValue === void 0 ? null : previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( parentNode , returnValue , branch [ replaceAttributeKey ] ) } return x }


Input: The return value of this function is a Node to be added otherwise null . [CODESPLIT] function replaceNode ( value , previousValue , i ) { var activeNode = activeNodes [ i ] var currentNode = node var returnValue // Cast values to null if undefined. if ( value === void 0 ) value = null if ( previousValue === void 0 ) previousValue = null // If value is null, just remove the Node. if ( value === null ) { removeNode ( null , previousValue , i ) return null } if ( valueIsArray ) keyPath . index = i else delete keyPath . index previousValues [ i ] = value if ( definition ) { if ( activeNode ) removeNode ( value , previousValue , i ) currentNode = processNodes ( scope , node , definition ) keyPath . target = valueIsArray ? value [ i ] : value bindKeys ( scope , value , definition , currentNode , keyPath ) if ( mount ) { keyPath . target = value mount ( currentNode , value , null , keyPath ) } } else { currentNode = activeNode || node . cloneNode ( true ) if ( change ) { returnValue = change ( currentNode , value , previousValue , keyPath ) if ( returnValue !== void 0 ) changeValue ( currentNode , returnValue , branch [ replaceAttributeKey ] ) } else { // Add default update behavior. Note that this event does not get // removed, since it is assumed that it will be garbage collected. if ( previousValue === null && ~ updateTags . indexOf ( currentNode . tagName ) ) currentNode . addEventListener ( 'input' , updateChange ( branch [ replaceAttributeKey ] , keyPath , key ) ) changeValue ( currentNode , value , branch [ replaceAttributeKey ] ) } // Do not actually add an element to the DOM if it's only a change // between non-empty values. if ( activeNode ) return null } activeNodes [ i ] = currentNode return currentNode }


Input: Below are optimized array mutator methods . They have to exist within this closure . Note that the native implementations of these methods do not trigger setter functions on array indices . [CODESPLIT] function pop ( ) { var i = this . length - 1 var previousValue = previousValues [ i ] var value = Array . prototype . pop . call ( this ) removeNode ( null , previousValue , i ) previousValues . length = activeNodes . length = this . length return value }


Input: Default behavior when a return value is given for a change function . [CODESPLIT] function changeValue ( node , value , attribute ) { var firstChild switch ( attribute ) { case 'textContent' : firstChild = node . firstChild if ( firstChild && ! firstChild . nextSibling && firstChild . nodeType === TEXT_NODE ) firstChild . textContent = value else node . textContent = value break case 'checked' : node . checked = Boolean ( value ) break case 'value' : // Prevent some misbehavior in certain browsers when setting a value to // itself, i.e. text caret not in the correct position. if ( node . value !== value ) node . value = value break default : break } }


Input: Find next node in a potentially sparse array . [CODESPLIT] function getNextNode ( index , activeNodes ) { var i , j , nextNode for ( i = index , j = activeNodes . length ; i < j ; i ++ ) if ( activeNodes [ i ] ) { nextNode = activeNodes [ i ] break } return nextNode }


Input: Internal event listener to update data on input change . [CODESPLIT] function updateChange ( targetKey , path , key ) { var target = path . target var index = path . index var replaceKey = key if ( typeof index === 'number' ) { target = target [ key ] replaceKey = index } return function handleChange ( event ) { target [ replaceKey ] = event . target [ targetKey ] } }


Input: Bind an object to the DOM . [CODESPLIT] function simulacra ( obj , def , matchNode ) { var document = this ? this . document : window . document var Node = this ? this . Node : window . Node var node , query // Before continuing, check if required features are present. featureCheck ( this || window , features ) if ( obj === null || typeof obj !== 'object' || isArray ( obj ) ) throw new TypeError ( 'First argument must be a singular object.' ) if ( ! isArray ( def ) ) throw new TypeError ( 'Second argument must be an array.' ) if ( typeof def [ 0 ] === 'string' ) { query = def [ 0 ] def [ 0 ] = document . querySelector ( query ) if ( ! def [ 0 ] ) throw new Error ( 'Top-level Node "' + query + '" could not be found in the document.' ) } else if ( ! ( def [ 0 ] instanceof Node ) ) throw new TypeError ( 'The first position of the top-level must be either a Node or a CSS ' + 'selector string.' ) if ( ! def [ isProcessedKey ] ) { // Auto-detect template tag. if ( 'content' in def [ 0 ] ) def [ 0 ] = def [ 0 ] . content def [ 0 ] = def [ 0 ] . cloneNode ( true ) cleanNode ( this , def [ 0 ] ) ensureNodes ( def [ 0 ] , def [ 1 ] ) setProperties ( def ) } node = processNodes ( this , def [ 0 ] , def [ 1 ] ) bindKeys ( this , obj , def [ 1 ] , node , { root : obj } ) if ( matchNode ) { rehydrate ( this , obj , def [ 1 ] , node , matchNode ) return matchNode } return node }


Input: Internal function to mutate string selectors into Nodes and validate that they are allowed . [CODESPLIT] function ensureNodes ( parentNode , def ) { var adjacentNodes = [ ] var i , j , key , query , branch , boundNode , matchedNodes var adjacentNode , adjacentKey if ( typeof def !== 'object' ) throw new TypeError ( 'The second position must be an object.' ) for ( key in def ) { branch = def [ key ] // Change function or definition object bound to parent. if ( typeof branch === 'function' || ( typeof branch === 'object' && branch !== null && ! Array . isArray ( branch ) ) ) def [ key ] = branch = [ parentNode , branch ] // Cast CSS selector string to array. else if ( typeof branch === 'string' ) def [ key ] = branch = [ branch ] else if ( ! Array . isArray ( branch ) ) throw new TypeError ( 'The binding on key "' + key + '" is invalid.' ) // Dereference CSS selector string to actual DOM element. if ( typeof branch [ 0 ] === 'string' ) { query = branch [ 0 ] // Match all nodes for the selector, pick the first and remove the rest. matchedNodes = parentNode . querySelectorAll ( query ) if ( ! matchedNodes . length ) throw new Error ( 'An element for selector "' + query + '" was not found.' ) for ( i = 1 , j = matchedNodes . length ; i < j ; i ++ ) matchedNodes [ i ] . parentNode . removeChild ( matchedNodes [ i ] ) branch [ 0 ] = matchedNodes [ 0 ] } else if ( ! branch [ 0 ] ) throw new TypeError ( 'The first position on key "' + key + '" must be a CSS selector string.' ) // Auto-detect template tag. if ( 'content' in branch [ 0 ] ) branch [ 0 ] = branch [ 0 ] . content boundNode = branch [ 0 ] if ( typeof branch [ 1 ] === 'object' && branch [ 1 ] !== null ) { Object . defineProperty ( branch , hasDefinitionKey , { value : true } ) if ( branch [ 2 ] && typeof branch [ 2 ] !== 'function' ) throw new TypeError ( 'The third position on key "' + key + '" must be a function.' ) } else if ( branch [ 1 ] && typeof branch [ 1 ] !== 'function' ) throw new TypeError ( 'The second position on key "' + key + '" must be an object or a function.' ) // Special case for binding to parent node. if ( parentNode === boundNode ) { Object . defineProperty ( branch , isBoundToParentKey , { value : true } ) if ( branch [ hasDefinitionKey ] ) ensureNodes ( boundNode , branch [ 1 ] ) else if ( typeof branch [ 1 ] === 'function' ) setReplaceAttribute ( branch , boundNode ) else console . warn ( // eslint-disable-line 'A change function was not defined on the key "' + key + '".' ) setProperties ( branch ) continue } adjacentNodes . push ( [ key , boundNode ] ) if ( ! parentNode . contains ( boundNode ) ) throw new Error ( 'The bound DOM element must be either ' + 'contained in or equal to the element in its parent binding.' ) if ( branch [ hasDefinitionKey ] ) { ensureNodes ( boundNode , branch [ 1 ] ) setProperties ( branch ) continue } setReplaceAttribute ( branch , boundNode ) setProperties ( branch ) } // Need to loop again to invalidate containment in adjacent nodes, after the // adjacent nodes are found. for ( key in def ) { boundNode = def [ key ] [ 0 ] for ( i = 0 , j = adjacentNodes . length ; i < j ; i ++ ) { adjacentKey = adjacentNodes [ i ] [ 0 ] adjacentNode = adjacentNodes [ i ] [ 1 ] if ( adjacentNode . contains ( boundNode ) && adjacentKey !== key ) throw new Error ( 'The element for key "' + key + '" is contained in the ' + 'element for the adjacent key "' + adjacentKey + '".' ) } } setProperties ( def ) }


Input: Internal function to strip empty text nodes . [CODESPLIT] function cleanNode ( scope , node ) { // A constant for showing text nodes. var showText = 0x00000004 var document = scope ? scope . document : window . document var treeWalker = document . createTreeWalker ( node , showText , processNodes . acceptNode , false ) var textNode while ( treeWalker . nextNode ( ) ) { textNode = treeWalker . currentNode textNode . textContent = textNode . textContent . trim ( ) } node . normalize ( ) }


Input: Internal function to remove bound nodes and replace them with markers . [CODESPLIT] function processNodes ( scope , node , def ) { var document = scope ? scope . document : window . document var key , branch , result , mirrorNode , parent , marker , indices var i , j , treeWalker , orderedKeys result = def [ templateKey ] if ( ! result ) { node = node . cloneNode ( true ) indices = [ ] matchNodes ( scope , node , def ) orderedKeys = Object . keys ( def ) . sort ( function ( a , b ) { var nodeA = def [ a ] [ 0 ] [ matchedNodeKey ] var nodeB = def [ b ] [ 0 ] [ matchedNodeKey ] if ( nodeA && nodeB ) return nodeA . index - nodeB . index return 0 } ) for ( i = 0 ; i < orderedKeys . length ; i ++ ) { key = orderedKeys [ i ] branch = def [ key ] if ( branch [ isBoundToParentKey ] ) continue result = branch [ 0 ] [ matchedNodeKey ] indices . push ( result . index ) mirrorNode = result . node parent = mirrorNode . parentNode // This value is memoized so that `appendChild` can be used instead of // `insertBefore`, which is a performance optimization. if ( mirrorNode . nextElementSibling === null ) branch [ isMarkerLastKey ] = true if ( processNodes . useCommentNode ) { marker = parent . insertBefore ( document . createComment ( ' end "' + key + '" ' ) , mirrorNode ) parent . insertBefore ( document . createComment ( ' begin "' + key + '" ' ) , marker ) } else marker = parent . insertBefore ( document . createTextNode ( '' ) , mirrorNode ) branch [ markerKey ] = marker parent . removeChild ( mirrorNode ) } Object . defineProperty ( def , templateKey , { value : { node : node . cloneNode ( true ) , indices : indices } } ) } else { node = result . node . cloneNode ( true ) indices = result . indices i = 0 j = 0 treeWalker = document . createTreeWalker ( node , showAll , acceptNode , false ) for ( key in def ) { branch = def [ key ] if ( branch [ isBoundToParentKey ] ) continue while ( treeWalker . nextNode ( ) ) { if ( i === indices [ j ] ) { branch [ markerKey ] = treeWalker . currentNode i ++ break } i ++ } j ++ } } return node }


Input: Internal function to find and set matching DOM nodes on cloned nodes . [CODESPLIT] function matchNodes ( scope , node , def ) { var document = scope ? scope . document : window . document var treeWalker = document . createTreeWalker ( node , showAll , acceptNode , false ) var nodes = [ ] var i , j , key , currentNode , childWalker var nodeIndex = 0 // This offset is a bit tricky, it's used to determine the index of the // marker in the processed node, which depends on whether comment nodes // are used and the count of child nodes. var offset = processNodes . useCommentNode ? 1 : 0 for ( key in def ) nodes . push ( def [ key ] [ 0 ] ) while ( treeWalker . nextNode ( ) && nodes . length ) { for ( i = 0 , j = nodes . length ; i < j ; i ++ ) { currentNode = nodes [ i ] if ( treeWalker . currentNode . isEqualNode ( currentNode ) ) { Object . defineProperty ( currentNode , matchedNodeKey , { value : { index : nodeIndex + offset , node : treeWalker . currentNode } } ) if ( processNodes . useCommentNode ) offset ++ childWalker = document . createTreeWalker ( currentNode , showAll , acceptNode , false ) while ( childWalker . nextNode ( ) ) offset -- nodes . splice ( i , 1 ) break } } nodeIndex ++ } }


Input: Rehydration of existing DOM nodes by recursively checking equality . [CODESPLIT] function rehydrate ( scope , obj , def , node , matchNode ) { var document = scope ? scope . document : window . document var key , branch , x , value , change , definition , mount , keyPath var meta , valueIsArray , activeNodes , index , treeWalker , currentNode for ( key in def ) { branch = def [ key ] meta = obj [ metaKey ] [ key ] change = ! branch [ hasDefinitionKey ] && branch [ 1 ] definition = branch [ hasDefinitionKey ] && branch [ 1 ] mount = branch [ 2 ] keyPath = meta . keyPath if ( branch [ isBoundToParentKey ] ) { x = obj [ key ] if ( definition && x !== null && x !== void 0 ) bindKeys ( scope , x , definition , matchNode , keyPath ) else if ( change ) change ( matchNode , x , null , keyPath ) continue } activeNodes = meta . activeNodes if ( ! activeNodes . length ) continue valueIsArray = meta . valueIsArray x = valueIsArray ? obj [ key ] : [ obj [ key ] ] index = 0 treeWalker = document . createTreeWalker ( matchNode , whatToShow , acceptNode , false ) while ( index < activeNodes . length && treeWalker . nextNode ( ) ) { currentNode = activeNodes [ index ] if ( treeWalker . currentNode . isEqualNode ( currentNode ) ) { activeNodes . splice ( index , 1 , treeWalker . currentNode ) value = x [ index ] if ( valueIsArray ) keyPath . index = index else delete keyPath . index if ( definition ) { rehydrate ( scope , value , definition , currentNode , treeWalker . currentNode ) if ( mount ) { keyPath . target = value mount ( treeWalker . currentNode , value , null , keyPath ) } } else if ( change ) change ( treeWalker . currentNode , value , null , keyPath ) index ++ } } if ( index !== activeNodes . length ) throw new Error ( 'Matching nodes could not be found on key "' + key + '", expected ' + activeNodes . length + ', found ' + index + '.' ) // Rehydrate marker node. currentNode = treeWalker . currentNode // Try to re-use comment node. if ( processNodes . useCommentNode && currentNode . nextSibling !== null && currentNode . nextSibling . nodeType === COMMENT_NODE ) branch [ markerKey ] = currentNode . nextSibling else branch [ markerKey ] = currentNode . parentNode . insertBefore ( document . createTextNode ( '' ) , currentNode . nextSibling ) } }


Input: Internal function for rendering strings . The benchmark to beat is plain old string concatenation and for loops . Although this won t be faster it should work with more or less the same functionality as the DOM version . [CODESPLIT] function render ( obj , def , html ) { var i , nodes , handler , parser , element , elementPrototype // If given bindings with a root node, pick only the binding keys. if ( Array . isArray ( def ) ) def = def [ 1 ] // Generating the render function is processing intensive. Skip if possible. if ( renderFnKey in def ) return def [ renderFnKey ] ( obj ) // Callback API looks weird. This is actually synchronous, not asynchronous. handler = new htmlParser . DomHandler ( function ( error , result ) { if ( error ) throw error nodes = result } , handlerOptions ) parser = new htmlParser . Parser ( handler ) parser . write ( html ) parser . end ( ) for ( i = nodes . length ; i -- ; ) if ( nodes [ i ] . type === 'tag' ) { element = nodes [ i ] break } if ( ! element ) throw new Error ( 'No element found!' ) elementPrototype = Object . getPrototypeOf ( element ) Element . prototype = elementPrototype Object . defineProperties ( elementPrototype , elementExtension ) processDefinition ( def , nodes ) def [ renderFnKey ] = makeRender ( def , nodes ) return def [ renderFnKey ] ( obj ) }


Input: Check if capabilities are available or throw an error . [CODESPLIT] function featureCheck ( globalScope , features ) { var i , j , k , l , feature , path for ( i = 0 , j = features . length ; i < j ; i ++ ) { path = features [ i ] if ( typeof path [ 0 ] === 'string' ) { feature = globalScope for ( k = 0 , l = path . length ; k < l ; k ++ ) { if ( ! ( path [ k ] in feature ) ) throw new Error ( 'Missing ' + path . slice ( 0 , k + 1 ) . join ( '.' ) + ' feature which is required.' ) feature = feature [ path [ k ] ] } } else { feature = path [ 0 ] for ( k = 1 , l = path . length ; k < l ; k ++ ) { if ( k > 1 ) feature = feature [ path [ k ] ] if ( typeof feature === 'undefined' ) throw new Error ( 'Missing ' + path [ 0 ] . name + path . slice ( 1 , k + 1 ) . join ( '.' ) + ' feature which is required.' ) } } } }


Input: Create String from BEM entitys [CODESPLIT] function bemNames ( entitys , delimiters ) { var resultString = '' ; var names = entitys || { mods : { } , mixin : '' } ; var delims = _extends ( { ns : '' , el : '__' , mod : '--' , modVal : '-' } , delimiters ) ; var mixin = isString ( names . mixin ) ? ' ' + names . mixin : '' ; if ( ! names . block ) return '' ; resultString = delims . ns ? delims . ns + names . block : names . block ; if ( names . el ) resultString += delims . el + names . el ; if ( isPObject ( names . mods ) ) { resultString += Object . keys ( names . mods ) . reduce ( function ( prev , name ) { var val = names . mods [ name ] ; /* eslint-disable no-param-reassign */ if ( val === true ) { prev += ' ' + resultString + delims . mod + name ; } else if ( isString ( val ) || isNumber ( val ) ) { prev += ' ' + resultString + delims . mod + name + delims . modVal + names . mods [ name ] ; } /* eslint-enable no-param-reassign */ return prev ; } , '' ) ; } return resultString + mixin ; }


Input: const { blue } = require ( . / log . js ) [CODESPLIT] function write ( dest , code ) { return new Promise ( function ( resolve , reject ) { fs . writeFile ( dest , code , function ( err ) { if ( err ) return reject ( err ) // console.log(blue(dest) + ' ' + getSize(code)) resolve ( code ) } ) } ) }


Input: Merges an array of configs [CODESPLIT] function deepMergeConfigs ( configs , options ) { return merge . all ( configs . filter ( config => config ) , options ) ; }


Input: Loads a file from GitHub [CODESPLIT] async function loadYaml ( context , params ) { try { const response = await context . github . repos . getContents ( params ) ; return parseConfig ( response . data . content ) ; } catch ( e ) { if ( e . code === 404 ) { return null ; } throw e ; } }


Input: Computes parameters for the repository specified in base [CODESPLIT] function getBaseParams ( params , base ) { if ( typeof base !== 'string' ) { throw new Error ( ` ${ BASE_KEY } ` ) ; } const match = base . match ( BASE_REGEX ) ; if ( match == null ) { throw new Error ( ` ${ BASE_KEY } ${ base } ` ) ; } return { owner : match [ 1 ] || params . owner , repo : match [ 2 ] , path : match [ 3 ] || params . path , } ; }


Input: Loads the specified config file from the context s repository [CODESPLIT] async function getConfig ( context , fileName , defaultConfig , deepMergeOptions ) { const filePath = path . posix . join ( CONFIG_PATH , fileName ) ; const params = context . repo ( { path : filePath , } ) ; const config = await loadYaml ( context , params ) ; let baseRepo ; if ( config == null ) { baseRepo = DEFAULT_BASE ; } else if ( config != null && BASE_KEY in config ) { baseRepo = config [ BASE_KEY ] ; delete config [ BASE_KEY ] ; } let baseConfig ; if ( baseRepo ) { const baseParams = getBaseParams ( params , baseRepo ) ; baseConfig = await loadYaml ( context , baseParams ) ; } if ( config == null && baseConfig == null && ! defaultConfig ) { return null ; } return deepMergeConfigs ( [ defaultConfig , baseConfig , config ] , deepMergeOptions ) ; }


Input: Sets a property on an object preserving its enumerability . This function assumes that the property is already writable . [CODESPLIT] function defineProperty ( obj , name , value ) { var enumerable = ! ! obj [ name ] && obj . propertyIsEnumerable ( name ) Object . defineProperty ( obj , name , { configurable : true , enumerable : enumerable , writable : true , value : value } ) }


Input: Keep initialization idempotent . [CODESPLIT] function shimmer ( options ) { if ( options && options . logger ) { if ( ! isFunction ( options . logger ) ) logger ( "new logger isn't a function, not replacing" ) else logger = options . logger } }


Input: inject manifest html fragment into page code [CODESPLIT] function injectManifest ( data ) { let manifestHtml = ` ${ hexo . config . pwa . manifest . path } ` ; if ( data . indexOf ( manifestHtml ) === - 1 ) { data = data . replace ( '<head>' , manifestHtml ) ; } return data ; }


Input: inject service worker registion fragment into page code [CODESPLIT] function injectSWRegister ( data ) { let swHtml = ` ${ compiledSWRegTpl } ` ; if ( data . indexOf ( compiledSWRegTpl ) === - 1 ) { data = data . replace ( '</body>' , swHtml ) ; } return data ; }


Input: inject async load page js fragment [CODESPLIT] function injectAsyncLoadPageJS ( data ) { let injectHtml = ` ${ asyncLoadPageJSTpl } ` ; if ( data . indexOf ( injectHtml ) === - 1 ) { data = data . replace ( '</head>' , injectHtml ) ; } return data ; }


Input: Attach a react compiler . [CODESPLIT] function rehype2react ( options ) { var settings = options || { } ; var createElement = settings . createElement ; var components = settings . components || { } ; this . Compiler = compiler ; /* Compile HAST to React. */ function compiler ( node ) { if ( node . type === 'root' ) { if ( node . children . length === 1 && node . children [ 0 ] . type === 'element' ) { node = node . children [ 0 ] ; } else { node = { type : 'element' , tagName : 'div' , properties : node . properties || { } , children : node . children } ; } } return toH ( h , tableCellStyle ( node ) , settings . prefix ) ; } /* Wrap `createElement` to pass components in. */ function h ( name , props , children ) { var component = has ( components , name ) ? components [ name ] : name ; return createElement ( component , props , children ) ; } }


Input: / * Compile HAST to React . [CODESPLIT] function compiler ( node ) { if ( node . type === 'root' ) { if ( node . children . length === 1 && node . children [ 0 ] . type === 'element' ) { node = node . children [ 0 ] ; } else { node = { type : 'element' , tagName : 'div' , properties : node . properties || { } , children : node . children } ; } } return toH ( h , tableCellStyle ( node ) , settings . prefix ) ; }


Input: / * Wrap createElement to pass components in . [CODESPLIT] function h ( name , props , children ) { var component = has ( components , name ) ? components [ name ] : name ; return createElement ( component , props , children ) ; }


Input: Promise wrapper for exec execFile [CODESPLIT] function doExec ( method , args ) { var cp ; var cpPromise = new ChildProcessPromise ( ) ; var reject = cpPromise . _cpReject ; var resolve = cpPromise . _cpResolve ; var finalArgs = slice . call ( args , 0 ) ; finalArgs . push ( callback ) ; cp = child_process [ method ] . apply ( child_process , finalArgs ) ; function callback ( err , stdout , stderr ) { if ( err ) { var commandStr = args [ 0 ] + ( Array . isArray ( args [ 1 ] ) ? ( ' ' + args [ 1 ] . join ( ' ' ) ) : '' ) ; err . message += ' `' + commandStr + '` (exited with error code ' + err . code + ')' ; err . stdout = stdout ; err . stderr = stderr ; var cpError = new ChildProcessError ( err . message , err . code , child_process , stdout , stderr ) ; reject ( cpError ) ; } else { resolve ( { childProcess : cp , stdout : stdout , stderr : stderr } ) ; } } cpPromise . childProcess = cp ; return cpPromise ; }


Input: spawn as Promised [CODESPLIT] function doSpawn ( method , command , args , options ) { var result = { } ; var cp ; var cpPromise = new ChildProcessPromise ( ) ; var reject = cpPromise . _cpReject ; var resolve = cpPromise . _cpResolve ; var successfulExitCodes = ( options && options . successfulExitCodes ) || [ 0 ] ; cp = method ( command , args , options ) ; // Don't return the whole Buffered result by default. var captureStdout = false ; var captureStderr = false ; var capture = options && options . capture ; if ( capture ) { for ( var i = 0 , len = capture . length ; i < len ; i ++ ) { var cur = capture [ i ] ; if ( cur === 'stdout' ) { captureStdout = true ; } else if ( cur === 'stderr' ) { captureStderr = true ; } } } result . childProcess = cp ; if ( captureStdout ) { result . stdout = '' ; cp . stdout . on ( 'data' , function ( data ) { result . stdout += data ; } ) ; } if ( captureStderr ) { result . stderr = '' ; cp . stderr . on ( 'data' , function ( data ) { result . stderr += data ; } ) ; } cp . on ( 'error' , reject ) ; cp . on ( 'close' , function ( code ) { if ( successfulExitCodes . indexOf ( code ) === - 1 ) { var commandStr = command + ( args . length ? ( ' ' + args . join ( ' ' ) ) : '' ) ; var message = '`' + commandStr + '` failed with code ' + code ; var err = new ChildProcessError ( message , code , cp ) ; if ( captureStderr ) { err . stderr = result . stderr . toString ( ) ; } if ( captureStdout ) { err . stdout = result . stdout . toString ( ) ; } reject ( err ) ; } else { result . code = code ; resolve ( result ) ; } } ) ; cpPromise . childProcess = cp ; return cpPromise ; }


Input: Calculate the slopes of the tangents ( Hermite - type interpolation ) based on the following paper : Steffen M . 1990 . A Simple Method for Monotonic Interpolation in One Dimension . Astronomy and Astrophysics Vol . 239 NO . NOV ( II ) P . 443 1990 . [CODESPLIT] function slope3 ( that , x2 , y2 ) { var h0 = that . _x1 - that . _x0 , h1 = x2 - that . _x1 , s0 = ( that . _y1 - that . _y0 ) / ( h0 || h1 < 0 && - 0 ) , s1 = ( y2 - that . _y1 ) / ( h1 || h0 < 0 && - 0 ) , p = ( s0 * h1 + s1 * h0 ) / ( h0 + h1 ) ; return ( sign ( s0 ) + sign ( s1 ) ) * Math . min ( Math . abs ( s0 ) , Math . abs ( s1 ) , 0.5 * Math . abs ( p ) ) || 0 ; }


Input: Calculate a one - sided slope . [CODESPLIT] function slope2 ( that , t ) { var h = that . _x1 - that . _x0 ; return h ? ( 3 * ( that . _y1 - that . _y0 ) / h - t ) / 2 : t ; }


Input: According to https : // en . wikipedia . org / wiki / Cubic_Hermite_spline#Representations you can express cubic Hermite interpolation in terms of cubic Bézier curves with respect to the four values p0 p0 + m0 / 3 p1 - m1 / 3 p1 . [CODESPLIT] function point ( that , t0 , t1 ) { var x0 = that . _x0 , y0 = that . _y0 , x1 = that . _x1 , y1 = that . _y1 , dx = ( x1 - x0 ) / 3 ; that . _context . bezierCurveTo ( x0 + dx , y0 + dx * t0 , x1 - dx , y1 - dx * t1 , x1 , y1 ) ; }


Input: Checks whether a property name is a writeable attribute . [CODESPLIT] function shouldSetAttribute ( name , value ) { if ( isReservedProp ( name ) ) { return false ; } if ( name . length > 2 && ( name [ 0 ] === 'o' || name [ 0 ] === 'O' ) && ( name [ 1 ] === 'n' || name [ 1 ] === 'N' ) ) { return false ; } if ( value === null ) { return true ; } switch ( typeof value ) { case 'boolean' : return shouldAttributeAcceptBooleanValue ( name ) ; case 'undefined' : case 'number' : case 'string' : case 'object' : return true ; default : // function, symbol return false ; } }


Input: Creates markup for a property . [CODESPLIT] function createMarkupForProperty ( name , value ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo ) { if ( shouldIgnoreValue ( propertyInfo , value ) ) { return '' ; } var attributeName = propertyInfo . attributeName ; if ( propertyInfo . hasBooleanValue || propertyInfo . hasOverloadedBooleanValue && value === true ) { return attributeName + '=""' ; } else if ( typeof value !== 'boolean' || shouldAttributeAcceptBooleanValue ( name ) ) { return attributeName + '=' + quoteAttributeValueForBrowser ( value ) ; } } else if ( shouldSetAttribute ( name , value ) ) { if ( value == null ) { return '' ; } return name + '=' + quoteAttributeValueForBrowser ( value ) ; } return null ; }


Input: Render a ReactElement to its initial HTML . This should only be used on the server . See https : // reactjs . org / docs / react - dom - server . html#rendertostring [CODESPLIT] function renderToString ( element ) { var renderer = new ReactDOMServerRenderer$1 ( element , false ) ; var markup = renderer . read ( Infinity ) ; return markup ; }


Input: Similar to renderToString except this doesn t create extra DOM attributes such as data - react - id that React uses internally . See https : // reactjs . org / docs / react - dom - server . html#rendertostaticmarkup [CODESPLIT] function renderToStaticMarkup ( element ) { var renderer = new ReactDOMServerRenderer$1 ( element , true ) ; var markup = renderer . read ( Infinity ) ; return markup ; }


Input: Traps top - level events by using event bubbling . [CODESPLIT] function trapBubbledEvent ( topLevelType , handlerBaseName , element ) { if ( ! element ) { return null ; } return EventListener . listen ( element , handlerBaseName , dispatchEvent . bind ( null , topLevelType ) ) ; }


Input: Returns { start end } where start is the character / codepoint index of ( anchorNode anchorOffset ) within the textContent of outerNode and end is the index of ( focusNode focusOffset ) . [CODESPLIT] function getModernOffsetsFromPoints ( outerNode , anchorNode , anchorOffset , focusNode$$1 , focusOffset ) { var length = 0 ; var start = - 1 ; var end = - 1 ; var indexWithinAnchor = 0 ; var indexWithinFocus = 0 ; var node = outerNode ; var parentNode = null ; outer : while ( true ) { var next = null ; while ( true ) { if ( node === anchorNode && ( anchorOffset === 0 || node . nodeType === TEXT_NODE ) ) { start = length + anchorOffset ; } if ( node === focusNode$$1 && ( focusOffset === 0 || node . nodeType === TEXT_NODE ) ) { end = length + focusOffset ; } if ( node . nodeType === TEXT_NODE ) { length += node . nodeValue . length ; } if ( ( next = node . firstChild ) === null ) { break ; } // Moving from `node` to its first child `next`. parentNode = node ; node = next ; } while ( true ) { if ( node === outerNode ) { // If `outerNode` has children, this is always the second time visiting // it. If it has no children, this is still the first loop, and the only // valid selection is anchorNode and focusNode both equal to this node // and both offsets 0, in which case we will have handled above. break outer ; } if ( parentNode === anchorNode && ++ indexWithinAnchor === anchorOffset ) { start = length ; } if ( parentNode === focusNode$$1 && ++ indexWithinFocus === focusOffset ) { end = length ; } if ( ( next = node . nextSibling ) !== null ) { break ; } node = parentNode ; parentNode = node . parentNode ; } // Moving from `node` to its next sibling `next`. node = next ; } if ( start === - 1 || end === - 1 ) { // This should never happen. (Would happen if the anchor/focus nodes aren't // actually inside the passed-in node.) return null ; } return { start : start , end : end } ; }


Input: Singly linked - list of updates . When an update is scheduled it is added to the queue of the current fiber and the work - in - progress fiber . The two queues are separate but they share a persistent structure . During reconciliation updates are removed from the work - in - progress fiber but they remain on the current fiber . That ensures that if a work - in - progress is aborted the aborted updates are recovered by cloning from current . The work - in - progress queue is always a subset of the current queue . When the tree is committed the work - in - progress becomes the current . [CODESPLIT] function createUpdateQueue ( baseState ) { var queue = { baseState : baseState , expirationTime : NoWork , first : null , last : null , callbackList : null , hasForceUpdate : false , isInitialized : false } ; { queue . isProcessing = false ; } return queue ; }


Input: Invokes the mount life - cycles on a previously never rendered instance . [CODESPLIT] function mountClassInstance ( workInProgress , renderExpirationTime ) { var current = workInProgress . alternate ; { checkClassInstance ( workInProgress ) ; } var instance = workInProgress . stateNode ; var state = instance . state || null ; var props = workInProgress . pendingProps ; ! props ? invariant ( false , 'There must be pending props for an initial mount. This error is likely caused by a bug in React. Please file an issue.' ) : void 0 ; var unmaskedContext = getUnmaskedContext ( workInProgress ) ; instance . props = props ; instance . state = workInProgress . memoizedState = state ; instance . refs = emptyObject ; instance . context = getMaskedContext ( workInProgress , unmaskedContext ) ; if ( enableAsyncSubtreeAPI && workInProgress . type != null && workInProgress . type . prototype != null && workInProgress . type . prototype . unstable_isAsyncReactComponent === true ) { workInProgress . internalContextTag |= AsyncUpdates ; } if ( typeof instance . componentWillMount === 'function' ) { callComponentWillMount ( workInProgress , instance ) ; // If we had additional state updates during this life-cycle, let's // process them now. var updateQueue = workInProgress . updateQueue ; if ( updateQueue !== null ) { instance . state = processUpdateQueue ( current , workInProgress , updateQueue , instance , props , renderExpirationTime ) ; } } if ( typeof instance . componentDidMount === 'function' ) { workInProgress . effectTag |= Update ; } }


Input: User - originating errors ( lifecycles and refs ) should not interrupt deletion so don t let them throw . Host - originating errors should interrupt deletion so it s okay [CODESPLIT] function commitUnmount ( current ) { if ( typeof onCommitUnmount === 'function' ) { onCommitUnmount ( current ) ; } switch ( current . tag ) { case ClassComponent : { safelyDetachRef ( current ) ; var instance = current . stateNode ; if ( typeof instance . componentWillUnmount === 'function' ) { safelyCallComponentWillUnmount ( current , instance ) ; } return ; } case HostComponent : { safelyDetachRef ( current ) ; return ; } case CallComponent : { commitNestedUnmounts ( current . stateNode ) ; return ; } case HostPortal : { // TODO: this is recursive. // We are also not using this parent because // the portal will get pushed immediately. if ( enableMutatingReconciler && mutation ) { unmountHostComponents ( current ) ; } else if ( enablePersistentReconciler && persistence ) { emptyPortalContainer ( current ) ; } return ; } } }


Input: requestWork is called by the scheduler whenever a root receives an update . It s up to the renderer to call renderRoot at some point in the future . [CODESPLIT] function requestWork ( root , expirationTime ) { if ( nestedUpdateCount > NESTED_UPDATE_LIMIT ) { invariant ( false , 'Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.' ) ; } // Add the root to the schedule. // Check if this root is already part of the schedule. if ( root . nextScheduledRoot === null ) { // This root is not already scheduled. Add it. root . remainingExpirationTime = expirationTime ; if ( lastScheduledRoot === null ) { firstScheduledRoot = lastScheduledRoot = root ; root . nextScheduledRoot = root ; } else { lastScheduledRoot . nextScheduledRoot = root ; lastScheduledRoot = root ; lastScheduledRoot . nextScheduledRoot = firstScheduledRoot ; } } else { // This root is already scheduled, but its priority may have increased. var remainingExpirationTime = root . remainingExpirationTime ; if ( remainingExpirationTime === NoWork || expirationTime < remainingExpirationTime ) { // Update the priority. root . remainingExpirationTime = expirationTime ; } } if ( isRendering ) { // Prevent reentrancy. Remaining work will be scheduled at the end of // the currently rendering batch. return ; } if ( isBatchingUpdates ) { // Flush work at the end of the batch. if ( isUnbatchingUpdates ) { // ...unless we're inside unbatchedUpdates, in which case we should // flush it now. performWorkOnRoot ( root , Sync ) ; } return ; } // TODO: Get rid of Sync and use current time? if ( expirationTime === Sync ) { performWork ( Sync , null ) ; } else if ( ! isCallbackScheduled ) { isCallbackScheduled = true ; startRequestCallbackTimer ( ) ; scheduleDeferredCallback ( performAsyncWork ) ; } }


Input: When working on async work the reconciler asks the renderer if it should yield execution . For DOM we implement this with requestIdleCallback . [CODESPLIT] function shouldYield ( ) { if ( deadline === null ) { return false ; } if ( deadline . timeRemaining ( ) > timeHeuristicForUnitOfWork ) { return false ; } deadlineDidExpire = true ; return true ; }


Input: TODO : Batching should be implemented at the renderer level not inside the reconciler . [CODESPLIT] function batchedUpdates ( fn , a ) { var previousIsBatchingUpdates = isBatchingUpdates ; isBatchingUpdates = true ; try { return fn ( a ) ; } finally { isBatchingUpdates = previousIsBatchingUpdates ; if ( ! isBatchingUpdates && ! isRendering ) { performWork ( Sync , null ) ; } } }


Input: TODO : Batching should be implemented at the renderer level not inside the reconciler . [CODESPLIT] function unbatchedUpdates ( fn ) { if ( isBatchingUpdates && ! isUnbatchingUpdates ) { isUnbatchingUpdates = true ; try { return fn ( ) ; } finally { isUnbatchingUpdates = false ; } } return fn ( ) ; }


Input: TODO : Batching should be implemented at the renderer level not within the reconciler . [CODESPLIT] function flushSync ( fn ) { var previousIsBatchingUpdates = isBatchingUpdates ; isBatchingUpdates = true ; try { return syncUpdates ( fn ) ; } finally { isBatchingUpdates = previousIsBatchingUpdates ; ! ! isRendering ? invariant ( false , 'flushSync was called from inside a lifecycle method. It cannot be called when React is already rendering.' ) : void 0 ; performWork ( Sync , null ) ; } }


Input: Sets the value for a property on a node . [CODESPLIT] function setValueForProperty ( node , name , value ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo && shouldSetAttribute ( name , value ) ) { var mutationMethod = propertyInfo . mutationMethod ; if ( mutationMethod ) { mutationMethod ( node , value ) ; } else if ( shouldIgnoreValue ( propertyInfo , value ) ) { deleteValueForProperty ( node , name ) ; return ; } else if ( propertyInfo . mustUseProperty ) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node [ propertyInfo . propertyName ] = value ; } else { var attributeName = propertyInfo . attributeName ; var namespace = propertyInfo . attributeNamespace ; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if ( namespace ) { node . setAttributeNS ( namespace , attributeName , '' + value ) ; } else if ( propertyInfo . hasBooleanValue || propertyInfo . hasOverloadedBooleanValue && value === true ) { node . setAttribute ( attributeName , '' ) ; } else { node . setAttribute ( attributeName , '' + value ) ; } } } else { setValueForAttribute ( node , name , shouldSetAttribute ( name , value ) ? value : null ) ; return ; } { } }


Input: Deletes the value for a property on a node . [CODESPLIT] function deleteValueForProperty ( node , name ) { var propertyInfo = getPropertyInfo ( name ) ; if ( propertyInfo ) { var mutationMethod = propertyInfo . mutationMethod ; if ( mutationMethod ) { mutationMethod ( node , undefined ) ; } else if ( propertyInfo . mustUseProperty ) { var propName = propertyInfo . propertyName ; if ( propertyInfo . hasBooleanValue ) { node [ propName ] = false ; } else { node [ propName ] = '' ; } } else { node . removeAttribute ( propertyInfo . attributeName ) ; } } else { node . removeAttribute ( name ) ; } }


Input: Implements an <input > host component that allows setting these optional props : checked value defaultChecked and defaultValue . [CODESPLIT] function getHostProps ( element , props ) { var node = element ; var value = props . value ; var checked = props . checked ; var hostProps = _assign ( { // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type : undefined , // Make sure we set .step before .value (setting .value before .step // means .value is rounded on mount, based upon step precision) step : undefined , // Make sure we set .min & .max before .value (to ensure proper order // in corner cases such as min or max deriving from value, e.g. Issue #7170) min : undefined , max : undefined } , props , { defaultChecked : undefined , defaultValue : undefined , value : value != null ? value : node . _wrapperState . initialValue , checked : checked != null ? checked : node . _wrapperState . initialChecked } ) ; return hostProps ; }


Input: Apply the diff . [CODESPLIT] function updateProperties$1 ( domElement , updatePayload , tag , lastRawProps , nextRawProps ) { var wasCustomComponentTag = isCustomComponent ( tag , lastRawProps ) ; var isCustomComponentTag = isCustomComponent ( tag , nextRawProps ) ; // Apply the diff. updateDOMProperties ( domElement , updatePayload , wasCustomComponentTag , isCustomComponentTag ) ; // TODO: Ensure that an update gets scheduled if any of the special props // changed. switch ( tag ) { case 'input' : // Update the wrapper around inputs *after* updating props. This has to // happen after `updateDOMProperties`. Otherwise HTML5 input validations // raise warnings and prevent the new value from being assigned. updateWrapper ( domElement , nextRawProps ) ; // We also check that we haven't missed a value update, such as a // Radio group shifting the checked value to another named radio input. updateValueIfChanged ( domElement ) ; break ; case 'textarea' : updateWrapper$1 ( domElement , nextRawProps ) ; break ; case 'select' : // <select> value update needs to occur after <option> children // reconciliation postUpdateWrapper ( domElement , nextRawProps ) ; break ; } }


Input: Base class helpers for the updating state of a component . [CODESPLIT] function PureComponent ( props , context , updater ) { // Duplicated from Component. this . props = props ; this . context = context ; this . refs = emptyObject ; // We initialize the default updater but the real one gets injected by the // renderer. this . updater = updater || ReactNoopUpdateQueue ; }


Input: Clone and return a new ReactElement using element as the starting point . See https : // reactjs . org / docs / react - api . html#cloneelement [CODESPLIT] function cloneElement ( element , config , children ) { var propName ; // Original props are copied var props = _assign ( { } , element . props ) ; // Reserved names are extracted var key = element . key ; var ref = element . ref ; // Self is preserved since the owner is preserved. var self = element . _self ; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element . _source ; // Owner will be preserved, unless ref is overridden var owner = element . _owner ; if ( config != null ) { if ( hasValidRef ( config ) ) { // Silently steal the ref from the parent. ref = config . ref ; owner = ReactCurrentOwner . current ; } if ( hasValidKey ( config ) ) { key = '' + config . key ; } // Remaining properties override existing props var defaultProps ; if ( element . type && element . type . defaultProps ) { defaultProps = element . type . defaultProps ; } for ( propName in config ) { if ( hasOwnProperty . call ( config , propName ) && ! RESERVED_PROPS . hasOwnProperty ( propName ) ) { if ( config [ propName ] === undefined && defaultProps !== undefined ) { // Resolve default props props [ propName ] = defaultProps [ propName ] ; } else { props [ propName ] = config [ propName ] ; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments . length - 2 ; if ( childrenLength === 1 ) { props . children = children ; } else if ( childrenLength > 1 ) { var childArray = Array ( childrenLength ) ; for ( var i = 0 ; i < childrenLength ; i ++ ) { childArray [ i ] = arguments [ i + 2 ] ; } props . children = childArray ; } return ReactElement ( element . type , key , ref , self , source , owner , props ) ; }


Input: Given an element validate that its props follow the propTypes definition provided by the type . [CODESPLIT] function validatePropTypes ( element ) { var componentClass = element . type ; if ( typeof componentClass !== 'function' ) { return ; } var name = componentClass . displayName || componentClass . name ; var propTypes = componentClass . propTypes ; if ( propTypes ) { currentlyValidatingElement = element ; checkPropTypes ( propTypes , element . props , 'prop' , name , getStackAddendum ) ; currentlyValidatingElement = null ; } if ( typeof componentClass . getDefaultProps === 'function' ) { warning ( componentClass . getDefaultProps . isReactClassApproved , 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.' ) ; } }


Input: Given a fragment validate that it can only be provided with fragment props [CODESPLIT] function validateFragmentProps ( fragment ) { currentlyValidatingElement = fragment ; var _iteratorNormalCompletion = true ; var _didIteratorError = false ; var _iteratorError = undefined ; try { for ( var _iterator = Object . keys ( fragment . props ) [ Symbol . iterator ] ( ) , _step ; ! ( _iteratorNormalCompletion = ( _step = _iterator . next ( ) ) . done ) ; _iteratorNormalCompletion = true ) { var key = _step . value ; if ( ! VALID_FRAGMENT_PROPS . has ( key ) ) { warning ( false , 'Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.%s' , key , getStackAddendum ( ) ) ; break ; } } } catch ( err ) { _didIteratorError = true ; _iteratorError = err ; } finally { try { if ( ! _iteratorNormalCompletion && _iterator [ 'return' ] ) { _iterator [ 'return' ] ( ) ; } } finally { if ( _didIteratorError ) { throw _iteratorError ; } } } if ( fragment . ref !== null ) { warning ( false , 'Invalid attribute `ref` supplied to `React.Fragment`.%s' , getStackAddendum ( ) ) ; } currentlyValidatingElement = null ; }


Input: Measures the impact of running a certain script on your system . Monitors the cpu and memory usage of the whole tree of processes generated by the script provided . [CODESPLIT] async function sympact ( code , options ) { if ( typeof code !== 'string' ) { throw new TypeError ( "The 'code' paramater must a string'" ) ; } if ( typeof options === 'undefined' ) { options = { } ; } if ( typeof options !== 'object' ) { throw new TypeError ( "The 'options' paramater must an object'" ) ; } const interval = options . interval || 125 ; const cwd = options . cwd || path . dirname ( caller ( ) ) ; if ( interval < 1 ) { throw new TypeError ( "The 'interval' paramater must be greater than 0'" ) ; } return new Promise ( ( resolve , reject ) => { const slave = new Worker ( code , cwd ) ; const probe = new Profiler ( slave . pid ( ) , interval ) ; slave . on ( 'ready' , async ( ) => { await probe . watch ( ) ; slave . run ( ) ; } ) ; slave . on ( 'after' , async ( start , end ) => { await probe . unwatch ( ) ; slave . kill ( ) ; resolve ( probe . report ( start , end ) ) ; } ) ; slave . on ( 'error' , async err => { await probe . unwatch ( ) ; slave . kill ( ) ; reject ( err ) ; } ) ; } ) ; }


Input: Abstract class defining the skeleton for the backoff strategies . Accepts an object holding the options for the backoff strategy : * randomisationFactor : The randomisation factor which must be between 0 and 1 where 1 equates to a randomization factor of 100% and 0 to no randomization . * initialDelay : The backoff initial delay in milliseconds . * maxDelay : The backoff maximal delay in milliseconds . [CODESPLIT] function BackoffStrategy ( options ) { options = options || { } ; if ( isDef ( options . initialDelay ) && options . initialDelay < 1 ) { throw new Error ( 'The initial timeout must be greater than 0.' ) ; } else if ( isDef ( options . maxDelay ) && options . maxDelay < 1 ) { throw new Error ( 'The maximal timeout must be greater than 0.' ) ; } this . initialDelay_ = options . initialDelay || 100 ; this . maxDelay_ = options . maxDelay || 10000 ; if ( this . maxDelay_ <= this . initialDelay_ ) { throw new Error ( 'The maximal backoff delay must be ' + 'greater than the initial backoff delay.' ) ; } if ( isDef ( options . randomisationFactor ) && ( options . randomisationFactor < 0 || options . randomisationFactor > 1 ) ) { throw new Error ( 'The randomisation factor must be between 0 and 1.' ) ; } this . randomisationFactor_ = options . randomisationFactor || 0 ; }


Input: Exponential backoff strategy . [CODESPLIT] function ExponentialBackoffStrategy ( options ) { BackoffStrategy . call ( this , options ) ; this . backoffDelay_ = 0 ; this . nextBackoffDelay_ = this . getInitialDelay ( ) ; this . factor_ = ExponentialBackoffStrategy . DEFAULT_FACTOR ; if ( options && options . factor !== undefined ) { precond . checkArgument ( options . factor > 1 , 'Exponential factor should be greater than 1 but got %s.' , options . factor ) ; this . factor_ = options . factor ; } }


Input: A class to hold the state of a backoff operation . Accepts a backoff strategy to generate the backoff delays . [CODESPLIT] function Backoff ( backoffStrategy ) { events . EventEmitter . call ( this ) ; this . backoffStrategy_ = backoffStrategy ; this . maxNumberOfRetry_ = - 1 ; this . backoffNumber_ = 0 ; this . backoffDelay_ = 0 ; this . timeoutID_ = - 1 ; this . handlers = { backoff : this . onBackoff_ . bind ( this ) } ; }


Input: Wraps a function to be called in a backoff loop . [CODESPLIT] function FunctionCall ( fn , args , callback ) { events . EventEmitter . call ( this ) ; precond . checkIsFunction ( fn , 'Expected fn to be a function.' ) ; precond . checkIsArray ( args , 'Expected args to be an array.' ) ; precond . checkIsFunction ( callback , 'Expected callback to be a function.' ) ; this . function_ = fn ; this . arguments_ = args ; this . callback_ = callback ; this . lastResult_ = [ ] ; this . numRetries_ = 0 ; this . backoff_ = null ; this . strategy_ = null ; this . failAfter_ = - 1 ; this . retryPredicate_ = FunctionCall . DEFAULT_RETRY_PREDICATE_ ; this . state_ = FunctionCall . State_ . PENDING ; }


Input: Channel constructor . [CODESPLIT] function Channel ( connection , name , options ) { options || ( options = { } ) ; options . capped = true ; // In mongo v <= 2.2 index for _id is not done by default options . autoIndexId = true ; options . size || ( options . size = 1024 * 1024 * 5 ) ; options . strict = false ; this . options = options ; this . connection = connection ; this . closed = false ; this . listening = null ; this . name = name || 'mubsub' ; this . create ( ) . listen ( ) ; this . setMaxListeners ( 0 ) ; }


Input: Connection constructor . [CODESPLIT] function Connection ( uri , options ) { var self = this ; options || ( options = { } ) ; options . autoReconnect != null || ( options . autoReconnect = true ) ; // It's a Db instance. if ( uri . collection ) { this . db = uri ; } else { MongoClient . connect ( uri , options , function ( err , db ) { if ( err ) return self . emit ( 'error' , err ) ; self . db = db ; self . emit ( 'connect' , db ) ; db . on ( 'error' , function ( err ) { self . emit ( 'error' , err ) ; } ) ; } ) ; } this . destroyed = false ; this . channels = { } ; }


Input: event listener : DOM ready [CODESPLIT] function addLoadEvent ( func ) { 'use strict' ; var oldonload = window . onload ; if ( typeof window . onload !== 'function' ) { window . onload = func ; } else { window . onload = function ( ) { oldonload ( ) ; func ( ) ; } ; } }


Input: eslint - disable - next - line no - unused - vars [CODESPLIT] function isTryBody ( path , { stackOffset = 0 } = { } ) { const node = path . getParentNode ( stackOffset - 1 ) const parent = path . getParentNode ( stackOffset ) const grandparent = path . getParentNode ( stackOffset + 1 ) const greatgrandparent = path . getParentNode ( stackOffset + 2 ) if ( parent . type === 'TryStatement' && node === parent . block ) { return true } if ( singleExpressionBlock ( parent ) && grandparent . type === 'TryStatement' && parent === grandparent . block ) { return true } if ( parent . type === 'ExpressionStatement' && singleExpressionBlock ( grandparent ) && greatgrandparent . type === 'TryStatement' && grandparent === greatgrandparent . block ) { return true } return false }


Input: function handleIfStatementComments ( text precedingNode enclosingNode followingNode comment options ) { [CODESPLIT] function handleIfStatementComments ( text , precedingNode , enclosingNode , followingNode , comment ) { if ( ! enclosingNode || ! ( enclosingNode . type === 'IfStatement' || enclosingNode . type === 'ConditionalExpression' ) || ! followingNode ) { return false } if ( precedingNode === enclosingNode . consequent && followingNode === enclosingNode . alternate ) { // if (precedingNode.type === 'BlockStatement') { //   addTrailingComment(precedingNode, comment) // } else { addDanglingComment ( enclosingNode , comment ) // } return true } return false }


Input: function parse ( text parsers opts ) { [CODESPLIT] function parse ( text ) { // Inline the require to avoid the module if we don't use it const coffeescript = require ( 'coffeescript' ) const coffeescriptOptions = { ast : true , } const ast = coffeescript . compile ( text , coffeescriptOptions ) // TODO: Any cleanup of the AST? return ast }


Input: Make an element draggable . [CODESPLIT] function Draggable ( target , options ) { if ( ! ( this instanceof Draggable ) ) { return new Draggable ( target , options ) ; } var that = this ; //ignore existing instance var instance = draggableCache . get ( target ) ; if ( instance ) { instance . state = 'reset' ; //take over options extend ( instance , options ) ; instance . update ( ) ; return instance ; } else { //get unique id for instance //needed to track event binders that . id = getUid ( ) ; that . _ns = '.draggy_' + that . id ; //save element passed that . element = target ; draggableCache . set ( target , that ) ; } //define state behaviour defineState ( that , 'state' , that . state ) ; //preset handles that . currentHandles = [ ] ; //take over options extend ( that , options ) ; //define handle if ( that . handle === undefined ) { that . handle = that . element ; } //setup droppable if ( that . droppable ) { that . initDroppable ( ) ; } //try to calc out basic limits that . update ( ) ; //go to initial state that . state = 'idle' ; }


Input: little helpers [CODESPLIT] function q ( str ) { if ( Array . isArray ( str ) ) { return str . map ( q ) . reduce ( function ( prev , curr ) { return prev . concat ( curr ) ; } , [ ] ) ; } else if ( str instanceof HTMLElement ) { return [ str ] ; } else { return [ ] . slice . call ( document . querySelectorAll ( str ) ) ; } }


Input: / * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function Functor ( name , args ) { let _name = name ; let _args = args ; let _argsCount = 0 ; let _variableHash = null ; if ( typeof _args === 'undefined' ) { _args = [ ] ; } else { _argsCount = args . length ; } this . getName = function getName ( ) { return _name ; } ; this . getId = function getId ( ) { return _name + '/' + _argsCount ; } ; this . evaluate = function evaluate ( ) { return this . toString ( ) ; } ; this . getGoal = function getGoal ( ) { return this ; } ; this . getArgumentCount = function getArgumentCount ( ) { return _argsCount ; } ; this . getVariables = function getVariables ( ) { return Object . keys ( this . getVariableHash ( ) ) ; } ; this . getVariableHash = function getVariableHash ( existingHash ) { let hash = existingHash ; if ( _variableHash !== null ) { if ( hash === undefined ) { return _variableHash ; } Object . keys ( _variableHash ) . forEach ( ( v ) => { hash [ v ] = true ; } ) ; return hash ; } if ( hash === undefined ) { hash = { } ; } let storedHash = { } ; _args . forEach ( ( arg ) => { arg . getVariableHash ( hash ) ; arg . getVariableHash ( storedHash ) ; } ) ; _variableHash = storedHash ; return hash ; } ; this . isGround = function isGround ( ) { let result = true ; for ( let i = 0 ; i < _argsCount ; i += 1 ) { let arg = _args [ i ] ; if ( ! arg . isGround ( ) ) { result = false ; break ; } } return result ; } ; this . getArguments = function getArguments ( ) { // content of _args is immutable return _args . concat ( ) ; } ; this . substitute = function substitute ( theta ) { let newArgs = _args . map ( ( arg ) => { return arg . substitute ( theta ) ; } ) ; return new Functor ( _name , newArgs ) ; } ; this . toString = function toString ( ) { let result = _name ; if ( _argsCount > 0 ) { result += '(' ; for ( let i = 0 ; i < _argsCount ; i += 1 ) { result += _args [ i ] . toString ( ) ; if ( i < _argsCount - 1 ) { result += ', ' ; } } result += ')' ; } return result ; } ; }


Input:
Maps conjunctions to a value . [CODESPLIT] function ConjunctionMap ( ) { let _conjunctions = [ ] ; /**
   * Add a mapping of a conjunction to a value to this map.
   * @param {Array} conjunction The conjunction to map the value
   * @param {any} value       The value to be mapped
   */ this . add = function add ( conjunction , value ) { if ( value === undefined ) { return ; } let map = new LiteralTreeMap ( ) ; conjunction . forEach ( ( conjunct ) => { map . add ( conjunct ) ; } ) ; _conjunctions . push ( [ map . size ( ) , map , value ] ) ; } ; /**
   * Get the value of a conjunction.
   * @return {any} Return the value of the conjunction mapped if it exists. Otherwise if the
   *    conjunction is not mapped then undefined would be returned instead.
   */ this . get = function get ( conjunction ) { let result ; for ( let i = 0 ; i < _conjunctions . length ; i += 1 ) { let pair = _conjunctions [ i ] ; let containMismatch = false ; if ( conjunction . length !== pair [ 0 ] ) { continue ; } for ( let j = 0 ; j < conjunction . length ; j += 1 ) { let conjunct = conjunction [ j ] ; if ( ! pair [ 1 ] . contains ( conjunct ) ) { containMismatch = true ; break ; } } if ( ! containMismatch ) { result = pair [ 2 ] ; break ; } } return result ; } ; }


Input: / * This file is part of the lps . js project released open source under the BSD 3 - Clause license . For more info please see https : // github . com / mauris / lps . js [CODESPLIT] function Profiler ( ) { let _values = { } ; this . reset = function reset ( key ) { _values [ key ] = 0 ; } ; this . increment = function increment ( key ) { if ( _values [ key ] === undefined || typeof _values [ key ] !== 'number' ) { return ; } _values [ key ] += 1 ; } ; this . increaseBy = function increaseBy ( key , value ) { if ( _values [ key ] === undefined || typeof _values [ key ] !== 'number' ) { return ; } _values [ key ] += value ; } ; this . set = function set ( key , value ) { _values [ key ] = value ; } ; this . add = function add ( key , value ) { if ( _values [ key ] === undefined || ! Array . isArray ( _values [ key ] ) ) { return ; } _values [ key ] . push ( value ) ; } ; this . get = function get ( key ) { return _values [ key ] ; } ; }


Input: Sort timables into set of earlyConjuncts and laterConjuncts [CODESPLIT] function sortTimables ( conjunction , forTime ) { let earlyConjuncts = [ ] ; let laterConjuncts = [ ] ; let dependentTimeVariables = { } ; // determine the time dependent variables for ( let k = 0 ; k < conjunction . length ; k += 1 ) { let conjunct = conjunction [ k ] ; if ( ! ( conjunct instanceof Timable ) ) { // skip over non-Timables if ( conjunct instanceof Functor && comparisonTerms . indexOf ( conjunct . getId ( ) ) !== - 1 ) { conjunct . getVariables ( ) . forEach ( ( v ) => { dependentTimeVariables [ v ] = true ; } ) ; } continue ; } let conjunctStartTime = conjunct . getStartTime ( ) ; let conjunctEndTime = conjunct . getEndTime ( ) ; if ( conjunctEndTime instanceof Variable ) { let endTimeName = conjunctEndTime . evaluate ( ) ; if ( conjunctStartTime instanceof Value || ( conjunctStartTime instanceof Variable && conjunctStartTime . evaluate ( ) !== endTimeName ) ) { // different start/end times dependentTimeVariables [ endTimeName ] = true ; } } } // sort between early and later for ( let k = 0 ; k < conjunction . length ; k += 1 ) { let conjunct = conjunction [ k ] ; if ( ! ( conjunct instanceof Timable ) ) { if ( laterConjuncts . length > 0 ) { laterConjuncts . push ( conjunct ) ; continue ; } earlyConjuncts . push ( conjunct ) ; continue ; } if ( ! conjunct . isInRange ( forTime ) ) { laterConjuncts . push ( conjunct ) ; continue ; } let conjunctStartTime = conjunct . getStartTime ( ) ; if ( conjunctStartTime instanceof Variable ) { if ( dependentTimeVariables [ conjunctStartTime . evaluate ( ) ] !== undefined ) { laterConjuncts . push ( conjunct ) ; continue ; } } earlyConjuncts . push ( conjunct ) ; } return [ earlyConjuncts , laterConjuncts ] ; }