Input: Open a popup using the first argument . Wait for it to close . Returns the window object [CODESPLIT] function popupExecute ( execute , url , name , options , callback ) { var popupName = name || defaultPopupName ( ) ; var popupOptions = optionsResolveCentered ( assign ( { } , defaultOptions , options ) ) ; var popupCallback = callback || function noop ( ) { } ; var optionsString = optionsToString ( popupOptions ) ; var win = execute ( url , popupName , optionsString ) ; var isMessageSent = false ; var interval ; function popupCallbackOnce ( err , data ) { if ( ! isMessageSent ) { isMessageSent = true ; popupCallback ( err , data ) ; } } function onMessage ( message ) { var data = message ? message . data : undefined ; if ( data ) { popupCallbackOnce ( undefined , data ) ; window . removeEventListener ( "message" , onMessage ) ; } } window . addEventListener ( "message" , onMessage , false ) ; if ( win ) { interval = setInterval ( function closePopupCallback ( ) { if ( win == null || win . closed ) { setTimeout ( function delayWindowClosing ( ) { clearInterval ( interval ) ; popupCallbackOnce ( new Error ( "Popup closed" ) ) ; } , 500 ) ; } } , 100 ) ; } else { popupCallbackOnce ( new Error ( "Popup blocked" ) ) ; } return win ; }


Input: Open a popup using the first argument . Wait for it to close and call the callback . Set the options string using the options object Returns the window object [CODESPLIT] function popup ( url , name , options , callback ) { return popupExecute ( window . open , url , name , options , callback ) ; }


Input: Open a popup using the first argument . Post the data into the open popup . Wait for it to close and call the callback . Set the options string using the options object Returns the window object [CODESPLIT] function popupWithPost ( url , postData , name , options , callback ) { function openWithPostData ( popupUrl , popupName , optionsString ) { return openPopupWithPost ( popupUrl , postData , popupName , optionsString ) ; } return popupExecute ( openWithPostData , url , name , options , callback ) ; }


Input: Selector directive [CODESPLIT] function Selector ( filter , timeout , window , http , q ) { this . restrict = 'EAC' ; this . replace = true ; this . transclude = true ; this . scope = { name : '@?' , value : '=model' , disabled : '=?disable' , disableSearch : '=?' , required : '=?require' , multiple : '=?multi' , placeholder : '@?' , valueAttr : '@' , labelAttr : '@?' , groupAttr : '@?' , options : '=?' , debounce : '=?' , create : '&?' , limit : '=?' , rtl : '=?' , api : '=?' , change : '&?' , remote : '&?' , remoteParam : '@?' , remoteValidation : '&?' , remoteValidationParam : '@?' , removeButton : '=?' , softDelete : '=?' , closeAfterSelection : '=?' , viewItemTemplate : '=?' , dropdownItemTemplate : '=?' , dropdownCreateTemplate : '=?' , dropdownGroupTemplate : '=?' } ; this . templateUrl = 'selector/selector.html' ; $filter = filter ; $timeout = timeout ; $window = window ; $http = http ; $q = q ; }


Input: Returns parser - supported syntax of given editor ( like html css etc . ) . Returns null if editor’s syntax is unsupported [CODESPLIT] function getSyntax ( editor ) { const mode = editor . getMode ( ) ; if ( mode . name === 'htmlmixed' ) { return 'html' ; } return mode . name === 'xml' ? mode . configuration : mode . name ; }


Input: Returns content range that should be wrapped [CODESPLIT] function getWrappingContentRange ( editor ) { if ( editor . somethingSelected ( ) ) { const sel = editor . listSelections ( ) . filter ( sel => sel . anchor !== sel . head ) [ 0 ] ; if ( sel ) { return comparePos ( sel . anchor , sel . head ) < 0 ? { from : sel . anchor , to : sel . head } : { from : sel . head , to : sel . anchor } ; } } // Nothing selected, find parent HTML node and return range for its content return getTagRangeForPos ( editor , editor . getCursor ( ) ) ; }


Input: Returns either inner or outer tag range ( depending on pos location ) for given position [CODESPLIT] function getTagRangeForPos ( editor , pos ) { const model = editor . getEmmetDocumentModel ( ) ; const tag = model && model . nodeForPoint ( pos ) ; if ( ! tag ) { return null ; } // Depending on given position, return either outer or inner tag range if ( inRange ( tag . open , pos ) || inRange ( tag . close , pos ) ) { // Outer range return rangeFromNode ( tag ) ; } // Inner range const from = tag . open . end ; const to = tag . close ? tag . close . start : tag . open . end ; return narrowToNonSpace ( editor , from , to ) ; }


Input: Check if given range is a single caret between tags [CODESPLIT] function betweenTags ( editor , range ) { if ( equalCursorPos ( range . anchor , range . head ) ) { const cursor = range . anchor ; const mode = editor . getModeAt ( cursor ) ; if ( mode . name === 'xml' ) { const left = editor . getTokenAt ( cursor ) ; const right = editor . getTokenAt ( Object . assign ( { } , cursor , { ch : cursor . ch + 1 } ) ) ; return left . type === 'tag bracket' && left . string === '>' && right . type === 'tag bracket' && right . string === '</' ; } } }


Input: Check if abbreviation can be extracted from given position [CODESPLIT] function canExtract ( editor , pos , config ) { const tokenType = editor . getTokenTypeAt ( pos ) ; if ( config . type === 'stylesheet' ) { return tokenType !== 'comment' && tokenType !== 'string' ; } if ( config . syntax === 'html' ) { return tokenType === null ; } if ( config . syntax === 'slim' || config . syntax === 'pug' ) { return tokenType === null || tokenType === 'tag' || ( tokenType && / attribute / . test ( tokenType ) ) ; } if ( config . syntax === 'haml' ) { return tokenType === null || tokenType === 'attribute' ; } if ( config . syntax === 'jsx' ) { // JSX a bit tricky, delegate it to caller return true ; } return false ; }


Input: Returns completions for markup syntaxes ( HTML Slim Pug etc . ) [CODESPLIT] function getMarkupCompletions ( editor , pos , config ) { const line = editor . getLine ( pos . line ) . slice ( 0 , pos . ch ) ; const prefix = extractPrefix ( line , / [\w:\-$@] / ) ; // Make sure that current position precedes element name (e.g. not attribute, // class, id etc.) if ( prefix ) { const prefixRange = { from : { line : pos . line , ch : pos . ch - prefix . length } , to : pos } ; return getSnippetCompletions ( editor , pos , config ) . filter ( completion => completion . key !== prefix && completion . key . indexOf ( prefix ) === 0 ) . map ( completion => new EmmetCompletion ( 'snippet' , editor , prefixRange , completion . key , completion . preview , completion . snippet ) ) ; } return [ ] ; }


Input: Returns completions for stylesheet syntaxes [CODESPLIT] function getStylesheetCompletions ( editor , pos , config ) { const line = editor . getLine ( pos . line ) . slice ( 0 , pos . ch ) ; const prefix = extractPrefix ( line , / [\w-@$] / ) ; if ( prefix ) { // Make sure that current position precedes element name (e.g. not attribute, // class, id etc.) const prefixRange = { from : { line : pos . line , ch : pos . ch - prefix . length } , to : pos } ; if ( config . options && config . options . property ) { const lowerProp = config . options . property . toLowerCase ( ) ; // Find matching CSS property snippet for keyword completions const completion = getSnippetCompletions ( editor , pos , config ) . find ( item => item . property && item . property === lowerProp ) ; if ( completion && completion . keywords . length ) { return completion . keywords . map ( kw => { return kw . key . indexOf ( prefix ) === 0 && new EmmetCompletion ( 'value' , editor , prefixRange , kw . key , kw . preview , kw . snippet ) ; } ) . filter ( Boolean ) ; } } else { return getSnippetCompletions ( editor , pos , config ) . filter ( completion => completion . key !== prefix && completion . key . indexOf ( prefix ) === 0 ) . map ( completion => new EmmetCompletion ( 'snippet' , editor , prefixRange , completion . key , completion . preview , completion . snippet ) ) ; } } return [ ] ; }


Input: Returns all possible snippets completions for given editor context . Completions are cached in editor for for re - use [CODESPLIT] function getSnippetCompletions ( editor , pos , config ) { const { type , syntax } = config ; if ( ! editor . state . emmetCompletions ) { editor . state . emmetCompletions = { } ; } const cache = editor . state . emmetCompletions ; if ( ! ( syntax in cache ) ) { const registry = createSnippetsRegistry ( type , syntax , config . snippets ) ; cache [ syntax ] = type === 'stylesheet' ? getStylesheetSnippets ( registry , config ) : getMarkupSnippets ( registry , config ) ; } return cache [ syntax ] ; }


Input: Returns stylesheet snippets list [CODESPLIT] function getStylesheetSnippets ( registry ) { return convertToCSSSnippets ( registry ) . map ( snippet => { let preview = snippet . property ; const keywords = snippet . keywords ( ) ; if ( keywords . length ) { preview += ` ${ removeFields ( keywords . join ( ' | ' ) ) } ` ; } else if ( snippet . value ) { preview += ` ${ removeFields ( snippet . value ) } ` ; } return { key : snippet . key , value : snippet . value , snippet : snippet . key , property : snippet . property , keywords : keywords . map ( kw => { const m = kw . match ( / ^[\w-]+ / ) ; return m && { key : m [ 0 ] , preview : removeFields ( kw ) , snippet : kw } ; } ) . filter ( Boolean ) , preview } ; } ) ; }


Input: Returns markup snippets list [CODESPLIT] function getMarkupSnippets ( registry , config ) { return registry . all ( { type : 'string' } ) . map ( snippet => ( { key : snippet . key , value : snippet . value , preview : removeFields ( expand ( snippet . value , config ) ) , snippet : snippet . key } ) ) ; }


Input: Extracts prefix from the end of given string that matches match regexp [CODESPLIT] function extractPrefix ( str , match ) { let offset = str . length ; while ( offset > 0 ) { if ( ! match . test ( str [ offset - 1 ] ) ) { break ; } offset -- ; } return str . slice ( offset ) ; }


Input: Ensures that given editor Emmet abbreviation marker contains valid Emmet abbreviation and updates abbreviation model if required [CODESPLIT] function isValidMarker ( editor , marker ) { const range = marker . find ( ) ; // No newlines inside abbreviation if ( range . from . line !== range . to . line ) { return false ; } // Make sure marker contains valid abbreviation let text = editor . getRange ( range . from , range . to ) ; if ( ! text || / ^\s|\s$ / g . test ( text ) ) { return false ; } if ( marker . model && marker . model . config . syntax === 'jsx' && text [ 0 ] === '<' ) { text = text . slice ( 1 ) ; } if ( ! marker . model || marker . model . abbreviation !== text ) { // marker contents was updated, re-parse abbreviation try { marker . model = new Abbreviation ( text , range , marker . model . config ) ; if ( ! marker . model . valid ( editor , true ) ) { marker . model = null ; } } catch ( err ) { console . warn ( err ) ; marker . model = null ; } } return Boolean ( marker . model && marker . model . snippet ) ; }


Input: Toggle boolean properties or properties that have a values array in its definition . [CODESPLIT] function ( property ) { var def = this . _definition [ property ] ; if ( def . type === 'boolean' ) { // if it's a bool, just flip it this [ property ] = ! this [ property ] ; } else if ( def && def . values ) { // If it's a property with an array of values // skip to the next one looping back if at end. this [ property ] = arrayNext ( def . values , this [ property ] ) ; } else { throw new TypeError ( 'Can only toggle properties that are type `boolean` or have `values` array.' ) ; } return this ; }


Input: Determine if the model has changed since the last change event . If you specify an attribute name determine if that attribute has changed . [CODESPLIT] function ( attr ) { if ( attr == null ) return ! ! Object . keys ( this . _changed ) . length ; if ( has ( this . _derived , attr ) ) { return this . _derived [ attr ] . depList . some ( function ( dep ) { return this . hasChanged ( dep ) ; } , this ) ; } return has ( this . _changed , attr ) ; }


Input: Returns a bound handler for doing event bubbling while adding a name to the change string . [CODESPLIT] function ( propertyName ) { if ( ! this . _eventBubblingHandlerCache [ propertyName ] ) { this . _eventBubblingHandlerCache [ propertyName ] = function ( name , model , newValue ) { if ( changeRE . test ( name ) ) { this . trigger ( 'change:' + propertyName + '.' + name . split ( ':' ) [ 1 ] , model , newValue ) ; } else if ( name === 'change' ) { this . trigger ( 'change' , this ) ; } } . bind ( this ) ; } return this . _eventBubblingHandlerCache [ propertyName ] ; }


Input: helper for creating / storing property definitions and creating appropriate getters / setters [CODESPLIT] function createPropertyDefinition ( object , name , desc , isSession ) { var def = object . _definition [ name ] = { } ; var type , descArray ; if ( isString ( desc ) ) { // grab our type if all we've got is a string type = object . _ensureValidType ( desc ) ; if ( type ) def . type = type ; } else { //Transform array of ['type', required, default] to object form if ( Array . isArray ( desc ) ) { descArray = desc ; desc = { type : descArray [ 0 ] , required : descArray [ 1 ] , 'default' : descArray [ 2 ] } ; } type = object . _ensureValidType ( desc . type ) ; if ( type ) def . type = type ; if ( desc . required ) def . required = true ; if ( desc [ 'default' ] && typeof desc [ 'default' ] === 'object' ) { throw new TypeError ( 'The default value for ' + name + ' cannot be an object/array, must be a value or a function which returns a value/object/array' ) ; } def [ 'default' ] = desc [ 'default' ] ; def . allowNull = desc . allowNull ? desc . allowNull : false ; if ( desc . setOnce ) def . setOnce = true ; if ( def . required && def [ 'default' ] === undefined && ! def . setOnce ) def [ 'default' ] = object . _getDefaultForType ( type ) ; def . test = desc . test ; def . values = desc . values ; } if ( isSession ) def . session = true ; if ( ! type ) { type = isString ( desc ) ? desc : desc . type ; // TODO: start throwing a TypeError in future major versions instead of warning console . warn ( 'Invalid data type of `' + type + '` for `' + name + '` property. Use one of the default types or define your own' ) ; } // define a getter/setter on the prototype // but they get/set on the instance Object . defineProperty ( object , name , { set : function ( val ) { this . set ( name , val ) ; } , get : function ( ) { if ( ! this . _values ) { throw Error ( 'You may be trying to `extend` a state object with "' + name + '" which has been defined in `props` on the object being extended' ) ; } var value = this . _values [ name ] ; var typeDef = this . _dataTypes [ def . type ] ; if ( typeof value !== 'undefined' ) { if ( typeDef && typeDef . get ) { value = typeDef . get ( value ) ; } return value ; } var defaultValue = result ( def , 'default' ) ; this . _values [ name ] = defaultValue ; // If we've set a defaultValue, fire a change handler effectively marking // its change from undefined to the default value. if ( typeof defaultValue !== 'undefined' ) { var onChange = this . _getOnChangeForType ( def . type ) ; onChange ( defaultValue , value , name ) ; } return defaultValue ; } } ) ; return def ; }


Input: helper for creating derived property definitions [CODESPLIT] function createDerivedProperty ( modelProto , name , definition ) { var def = modelProto . _derived [ name ] = { fn : isFunction ( definition ) ? definition : definition . fn , cache : ( definition . cache !== false ) , depList : definition . deps || [ ] } ; // add to our shared dependency list def . depList . forEach ( function ( dep ) { modelProto . _deps [ dep ] = union ( modelProto . _deps [ dep ] || [ ] , [ name ] ) ; } ) ; // defined a top-level getter for derived names Object . defineProperty ( modelProto , name , { get : function ( ) { return this . _getDerivedProperty ( name ) ; } , set : function ( ) { throw new TypeError ( "`" + name + "` is a derived property, it can't be set directly." ) ; } } ) ; }


Input: proceed [CODESPLIT] function queue ( ) { while ( current < config . concurLimit && files . length > 0 ) { var file = files . shift ( ) allFiles . push ( Promise . resolve ( file ) . then ( function ( file ) { return clean . processOneClean ( file ) . then ( function ( filePath ) { if ( typeof filePath === 'string' ) { filesCleaned . push ( filePath ) } proceed ( ) } ) . catch ( function ( err ) { proceed ( ) functions . logError ( err ) throw err } ) } ) ) current ++ } }


Input:
----------- Functions ----------- [CODESPLIT] function reWriter ( goCrazy , filePath , data ) { /*
    Keep on writing a file until chokidar notices us.
    @param  {Boolean}  goCrazy   Start or continue to write a file every 500 ms until someone stops us!
    @param  {String}   filePath  String file path like '/source/file.txt'. Not used if goCrazy is false.
    @param  {String}   [data]    Optional data to write to the file. Defaults to 'changed data'.
    */ if ( goCrazy ) { data = data || 'changed data' fs . writeFileSync ( filePath , data ) reWriteTimer = setTimeout ( function ( ) { reWriter ( goCrazy , filePath , data ) } , 500 ) } else { clearTimeout ( reWriteTimer ) } }


Input: / * Normalize source maps . [CODESPLIT] function missingSource ( ) { let preferredPath = path . basename ( config . path . source ) let source = obj . source source = source . replace ( config . path . source , preferredPath ) source = source . replace ( config . path . dest , preferredPath ) source = source . replace ( path . basename ( config . path . dest ) , preferredPath ) if ( source . toLowerCase ( ) . endsWith ( '.map' ) ) { source = functions . removeExt ( source ) } if ( shared . slash !== '/' ) { // we are on windows source = source . replace ( / \\ / g , '/' ) } return [ source ] }


Input: proceed [CODESPLIT] function queue ( ) { while ( current < config . concurLimit && files . length > 0 ) { var file = files . shift ( ) allFiles . push ( Promise . resolve ( file ) . then ( function ( file ) { return build . processOneBuild ( file ) . then ( function ( filePath ) { if ( typeof filePath === 'string' ) { filesBuilt . push ( filePath ) } proceed ( ) } ) . catch ( function ( err ) { proceed ( ) functions . logError ( err ) throw err } ) } ) ) current ++ } }


Input: The Image class . [CODESPLIT] function Image ( image , address ) { var at = this . attributes = image . attribs ; this . name = path . basename ( at . src , path . extname ( at . src ) ) ; this . saveTo = path . dirname ( require . main . filename ) + "/" ; this . extension = path . extname ( at . src ) ; this . address = url . resolve ( address , at . src ) ; this . fromAddress = address ; }


Input: Shipit task . [CODESPLIT] function shipitTask ( grunt ) { 'use strict' ; // Init shipit grunt . shipit = new Shipit ( ) ; grunt . registerTask ( 'shipit' , 'Shipit Task' , function ( env ) { var config = grunt . config . get ( 'shipit' ) ; grunt . shipit . environment = env ; // Support legacy options. if ( ! config . default && config . options ) config . default = config . options ; grunt . shipit . initConfig ( config ) . initialize ( ) ; } ) ; }


Input: Only support for es5 modules [CODESPLIT] function injectTemplate ( s , node , offset , id ) { const t = node . src ? readSrc ( id , node . src ) : node . content // Compile template const compiled = compiler . compile ( t ) const renderFuncs = '\nrender: ' + toFunction ( compiled . render ) + ',' + '\nstaticRenderFns: [' + compiled . staticRenderFns . map ( toFunction ) . join ( ',' ) + '],' s . appendLeft ( offset , renderFuncs ) return renderFuncs }


Input: / * EjsElectron . listen () -- Start intercepting requests on the file : protocol looking for . ejs files . It is not necessary to call this function up - front as ejs - electron starts listening as soon as it s loaded . Use this only to start listening again after calling EjsElectron . stopListening () . [CODESPLIT] function listen ( ) { if ( state . listening ) return EjsElectron // already listening; nothing to do here protocol . interceptBufferProtocol ( 'file' , protocolListener ) state . listening = true return EjsElectron // for chaining }


Input: / * EjsElectron . stopListening () -- Stop intercepting requests restoring the original file : protocol handler . [CODESPLIT] function stopListening ( ) { if ( ! state . listening ) return EjsElectron // we're not listening; nothing to stop here protocol . uninterceptProtocol ( 'file' ) state . listening = false return EjsElectron }


Input: Helper Functions [CODESPLIT] function compileEjs ( pathname , contentBuffer ) { state . data . ejse = EjsElectron state . options . filename = pathname let contentString = contentBuffer . toString ( ) let compiledEjs = ejs . render ( contentString , state . data , state . options ) return new Buffer ( compiledEjs ) }


Input: A closure factory to build the checkSize function for most of our handlers [CODESPLIT] function _defaultCheckSize ( size ) { return function ( raw ) { if ( raw . length < size ) { return false ; } this . buffer = raw . substr ( size ) ; return raw . substr ( 0 , size ) ; } ; }


Input: / * Calculate the HMAC - SHA - 512 of a key and some data ( raw strings ) [CODESPLIT] function rstr_hmac_sha512 ( key , data ) { var bkey = rstr2binb ( key ) ; if ( bkey . length > 32 ) bkey = binb_sha512 ( bkey , key . length * 8 ) ; var ipad = Array ( 32 ) , opad = Array ( 32 ) ; for ( var i = 0 ; i < 32 ; i ++ ) { ipad [ i ] = bkey [ i ] ^ 0x36363636 ; opad [ i ] = bkey [ i ] ^ 0x5C5C5C5C ; } var hash = binb_sha512 ( ipad . concat ( rstr2binb ( data ) ) , 1024 + data . length * 8 ) ; return binb2rstr ( binb_sha512 ( opad . concat ( hash ) , 1024 + 512 ) ) ; }


Input: Same except with 5 addends [CODESPLIT] function int64add5 ( dst , a , b , c , d , e ) { var w0 = ( a . l & 0xffff ) + ( b . l & 0xffff ) + ( c . l & 0xffff ) + ( d . l & 0xffff ) + ( e . l & 0xffff ) ; var w1 = ( a . l >>> 16 ) + ( b . l >>> 16 ) + ( c . l >>> 16 ) + ( d . l >>> 16 ) + ( e . l >>> 16 ) + ( w0 >>> 16 ) ; var w2 = ( a . h & 0xffff ) + ( b . h & 0xffff ) + ( c . h & 0xffff ) + ( d . h & 0xffff ) + ( e . h & 0xffff ) + ( w1 >>> 16 ) ; var w3 = ( a . h >>> 16 ) + ( b . h >>> 16 ) + ( c . h >>> 16 ) + ( d . h >>> 16 ) + ( e . h >>> 16 ) + ( w2 >>> 16 ) ; dst . l = ( w0 & 0xffff ) | ( w1 << 16 ) ; dst . h = ( w2 & 0xffff ) | ( w3 << 16 ) ; }


Input: LmdBuilder LMD Package Builder [CODESPLIT] function ( configFile , options ) { DataStream . call ( this ) ; this . options = options || { } ; var self = this ; // apply config this . configFile = configFile ; this . init ( ) ; // Bundles streams this . bundles = { } ; // Let return instance before build this . buildConfig = this . compileConfig ( configFile , self . options ) ; this . makeEmptyStreamsUnreadable ( this . buildConfig ) ; var isFatalErrors = ! this . isAllModulesExists ( this . buildConfig ) ; if ( isFatalErrors ) { this . readable = false ; this . style . readable = false ; this . sourceMap . readable = false ; } else { this . _initBundlesStreams ( this . buildConfig . bundles ) ; } process . nextTick ( function ( ) { if ( ! isFatalErrors ) { if ( configFile ) { var buildResult = self . build ( self . buildConfig ) ; self . write ( buildResult . source ) ; self . style . write ( buildResult . style ) ; self . sourceMap . write ( buildResult . sourceMap . toString ( ) ) ; self . _streamBundles ( buildResult . bundles ) ; } else { self . log . write ( 'lmd usage:\n\t    ' + 'lmd' . blue + ' ' + 'config.lmd.js(on)' . green + ' [output.lmd.js]\n' ) ; } } else { self . printFatalErrors ( self . buildConfig ) ; } self . closeStreams ( ) ; } ) ; }


Input: Uses variable sandbox for create replacement map [CODESPLIT] function getSandboxMap ( ast ) { var map = { } ; walker . with_walkers ( { // looking for first var with sandbox item; "var" : function ( vars ) { for ( var i = 0 , c = vars . length , varItem ; i < c ; i ++ ) { varItem = vars [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { varItem [ 1 ] [ 1 ] . forEach ( function ( objectVar ) { map [ objectVar [ 0 ] ] = objectVar [ 1 ] [ 1 ] ; } ) ; throw 0 ; } } } } , function ( ) { try { return walker . walk ( ast ) ; } catch ( e ) { } } ) ; return map ; }


Input: looking for first var with sandbox item ; [CODESPLIT] function ( vars ) { for ( var i = 0 , c = vars . length , varItem ; i < c ; i ++ ) { varItem = vars [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { varItem [ 1 ] [ 1 ] . forEach ( function ( objectVar ) { map [ objectVar [ 0 ] ] = objectVar [ 1 ] [ 1 ] ; } ) ; throw 0 ; } } }


Input: Brakes sendbox in one module [CODESPLIT] function breakSandbox ( ast , replaceMap ) { var sandboxName = ast [ 2 ] [ 0 ] || 'sb' ; var newAst = walker . with_walkers ( { // lookup for dot // looking for this pattern // ["dot", ["name", "sb"], "require"] -> ["name", map["require"]] "dot" : function ( ) { if ( this [ 1 ] && this [ 1 ] [ 0 ] === "name" && this [ 1 ] [ 1 ] === sandboxName ) { var sourceName = this [ 2 ] ; return [ "name" , replaceMap [ sourceName ] ] ; } } } , function ( ) { return walker . walk ( ast ) ; } ) ; // remove IEFE's `sb` or whatever argument newAst [ 1 ] [ 2 ] = [ ] ; return newAst ; }


Input: Brake sandbox : Using UglifyJS AST and sandbox variable in lmd . js file replace all sb . smth with actual value of sandbox [ smth ] than delete sandbox variable from lmd . js and all modules [CODESPLIT] function brakeSandboxes ( ast ) { var map = getSandboxMap ( ast ) , isSandboxVariableWiped = false ; return walker . with_walkers ( { // lookup for modules // looking for this pattern // [ 'call', //  [ 'function', null, [ 'sb' ], [ [Object] ] ], //  [ [ 'name', 'sandbox' ] ] ] "call" : function ( content ) { if ( this [ 2 ] && this [ 2 ] . length > 0 && this [ 2 ] [ 0 ] [ 0 ] === "name" && this [ 2 ] [ 0 ] [ 1 ] === "sandbox" && this [ 1 ] && this [ 1 ] [ 0 ] === "function" ) { // 1. remove sandbox argument this [ 2 ] = [ ] ; // 2. break sandbox in each module return breakSandbox ( this , map ) ; } } , // wipe sandobx variable "var" : function ( ) { if ( isSandboxVariableWiped ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { isSandboxVariableWiped = true ; this [ 1 ] . splice ( i , 1 ) ; return this ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; }


Input: wipe sandobx variable [CODESPLIT] function ( ) { if ( isSandboxVariableWiped ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem [ 0 ] === 'sandbox' ) { isSandboxVariableWiped = true ; this [ 1 ] . splice ( i , 1 ) ; return this ; } } }


Input: Collects all plugins events with usage and event index [CODESPLIT] function getEvents ( ast ) { var usage = { } , eventIndex = 0 ; walker . with_walkers ( { // looking for first var with sandbox item; "call" : function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] ; switch ( functionName ) { case "lmd_on" : case "lmd_trigger" : var eventName = this [ 2 ] [ 0 ] [ 1 ] ; if ( ! usage [ eventName ] ) { usage [ eventName ] = { on : 0 , trigger : 0 , eventIndex : eventIndex } ; eventIndex ++ ; } if ( functionName === "lmd_on" ) { usage [ eventName ] . on ++ ; } else { usage [ eventName ] . trigger ++ ; } break ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; return usage ; }


Input: looking for first var with sandbox item ; [CODESPLIT] function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] ; switch ( functionName ) { case "lmd_on" : case "lmd_trigger" : var eventName = this [ 2 ] [ 0 ] [ 1 ] ; if ( ! usage [ eventName ] ) { usage [ eventName ] = { on : 0 , trigger : 0 , eventIndex : eventIndex } ; eventIndex ++ ; } if ( functionName === "lmd_on" ) { usage [ eventName ] . on ++ ; } else { usage [ eventName ] . trigger ++ ; } break ; } } }


Input: Wipes lmd_on lmd_trigger lmd_events variables from source [CODESPLIT] function wipeLmdEvents ( ast ) { var itemsToWipe = [ 'lmd_on' , 'lmd_trigger' , 'lmd_events' ] ; return walker . with_walkers ( { // wipe lmdEvents variables "var" : function ( ) { if ( ! itemsToWipe . length ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem ) { var itemIndex = itemsToWipe . indexOf ( varItem [ 0 ] ) ; if ( itemIndex !== - 1 ) { itemsToWipe . splice ( itemIndex , 1 ) ; this [ 1 ] . splice ( i , 1 ) ; i -- ; } } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; }


Input: wipe lmdEvents variables [CODESPLIT] function ( ) { if ( ! itemsToWipe . length ) { return ; } for ( var i = 0 , c = this [ 1 ] . length , varItem ; i < c ; i ++ ) { varItem = this [ 1 ] [ i ] ; if ( varItem ) { var itemIndex = itemsToWipe . indexOf ( varItem [ 0 ] ) ; if ( itemIndex !== - 1 ) { itemsToWipe . splice ( itemIndex , 1 ) ; this [ 1 ] . splice ( i , 1 ) ; i -- ; } } } }


Input:
Optimizes number of lmd_ { on|trigger } calls [CODESPLIT] function reduceAndShortenLmdEvents ( ast ) { var events = getEvents ( ast ) , isWipeLmdEvents = true ; for ( var eventName in events ) { if ( isWipeLmdEvents ) { if ( events [ eventName ] . on !== 0 && events [ eventName ] . trigger !== 0 ) { // something is calling events isWipeLmdEvents = false ; } } } // If no lmd_trigger and lmd_on calls // than delete them plus lmd_events from lmd.js code if ( isWipeLmdEvents ) { ast = wipeLmdEvents ( ast ) ; } ast = walker . with_walkers ( { // looking for first var with sandbox item; "call" : function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] , eventName , eventDescriptor ; switch ( functionName ) { case "lmd_on" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event triggers (no lmd_trigger(event_name,...)) // delete all lmd_on(event_name,...) statements if ( eventDescriptor . trigger === 0 ) { return [ "stat" ] ; // wipe statement = return empty statement - ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers //console.log(this); this [ 2 ] [ 0 ] = [ "num" , eventDescriptor . eventIndex ] ; break ; case "lmd_trigger" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event listeners (no lmd_on(event_name,...)) // replace all lmd_trigger(event_name, argument, argument) // expressions with array [argument, argument] if ( eventDescriptor . on === 0 ) { // if parent is statement -> return void // to prevent loony arrays eg ["pewpew", "ololo"]; if ( walker . parent ( ) [ 0 ] === "stat" ) { return [ "stat" ] ; // wipe statement = return empty statement - ; } /*
                                [
                                    "call",
                                    ["name", "lmd_trigger"],
                                    [
                                        ["string", "lmd-register:call-sandboxed-module"],
                                        ["name", "moduleName"],
                                        ["name", "require"]
                                    ]
                                ]

                                  --->

                                [
                                    "array",
                                    [
                                        ["name", "moduleName"],
                                        ["name", "require"]
                                    ]
                                ]
                                */ return [ "array" , this [ 2 ] . slice ( 1 ) ] ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers this [ 2 ] [ 0 ] = [ "num" , eventDescriptor . eventIndex ] ; break ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; // #52 optimise constant expressions like [main][0] ast = walker . with_walkers ( { "sub" : function ( ) { // Looking for this pattern // [ 'sub', [ 'array', [ [Object], [Object] ] ], [ 'num', 1 ] ] if ( this [ 1 ] [ 0 ] === "array" && this [ 2 ] [ 0 ] === "num" ) { var isConstantArray = this [ 1 ] [ 1 ] . every ( function ( item ) { return item [ 0 ] === "num" || item [ 0 ] === "string" || item [ 0 ] === "name" || item [ 0 ] === "array" || item [ 0 ] === "object" ; } ) ; if ( isConstantArray ) { var index = this [ 2 ] [ 1 ] ; /*
                         [main][0]

                          --->

                         main
                        */ return this [ 1 ] [ 1 ] [ index ] ; } } } } , function ( ) { return walker . walk ( ast ) ; } ) ; return ast ; }


Input:
looking for first var with sandbox item ; [CODESPLIT] function ( ) { if ( this [ 1 ] && this [ 2 ] [ 0 ] ) { var functionName = this [ 1 ] [ 1 ] , eventName , eventDescriptor ; switch ( functionName ) { case "lmd_on" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event triggers (no lmd_trigger(event_name,...)) // delete all lmd_on(event_name,...) statements if ( eventDescriptor . trigger === 0 ) { return [ "stat" ] ; // wipe statement = return empty statement - ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers //console.log(this); this [ 2 ] [ 0 ] = [ "num" , eventDescriptor . eventIndex ] ; break ; case "lmd_trigger" : eventName = this [ 2 ] [ 0 ] [ 1 ] ; eventDescriptor = events [ eventName ] ; // if no event listeners (no lmd_on(event_name,...)) // replace all lmd_trigger(event_name, argument, argument) // expressions with array [argument, argument] if ( eventDescriptor . on === 0 ) { // if parent is statement -> return void // to prevent loony arrays eg ["pewpew", "ololo"]; if ( walker . parent ( ) [ 0 ] === "stat" ) { return [ "stat" ] ; // wipe statement = return empty statement - ; } /*
                                [
                                    "call",
                                    ["name", "lmd_trigger"],
                                    [
                                        ["string", "lmd-register:call-sandboxed-module"],
                                        ["name", "moduleName"],
                                        ["name", "require"]
                                    ]
                                ]

                                  --->

                                [
                                    "array",
                                    [
                                        ["name", "moduleName"],
                                        ["name", "require"]
                                    ]
                                ]
                                */ return [ "array" , this [ 2 ] . slice ( 1 ) ] ; } // Shorten event names: Using UglifyJS AST find all event names // from lmd_trigger and lmd_on and replace them with corresponding numbers this [ 2 ] [ 0 ] = [ "num" , eventDescriptor . eventIndex ] ; break ; } } }


Input: Applies or removes block from lmd_js [CODESPLIT] function ( optionName , isApply , isInline ) { // /*if ($P.CSS || $P.JS || $P.ASYNC) {*/ var inlinePreprocessorBlock = isInline ? '/*if (' + optionName + ') {*/' : 'if (' + optionName + ') {' , bracesCounter = 0 , startIndex = lmd_js . indexOf ( inlinePreprocessorBlock ) , startLength = inlinePreprocessorBlock . length , endIndex = startIndex + inlinePreprocessorBlock . length , endLength = isInline ? 5 : 1 ; if ( startIndex === - 1 ) { return false ; } // lookup for own } while ( lmd_js . length > endIndex ) { if ( lmd_js [ endIndex ] === '{' ) { bracesCounter ++ ; } if ( lmd_js [ endIndex ] === '}' ) { bracesCounter -- ; } // found! if ( bracesCounter === - 1 ) { if ( isInline ) { // step back endIndex -= 2 ; } else { // remove leading spaces from open part while ( startIndex ) { startIndex -- ; startLength ++ ; if ( lmd_js [ startIndex ] !== '\t' && lmd_js [ startIndex ] !== ' ' ) { startIndex ++ ; startLength -- ; break ; } } // remove leading spaces from close part while ( endIndex ) { endIndex -- ; endLength ++ ; if ( lmd_js [ endIndex ] !== '\t' && lmd_js [ endIndex ] !== ' ' ) { endIndex ++ ; endLength -- ; break ; } } // add front \n endLength ++ ; startLength ++ ; } if ( isApply ) { // wipe preprocessor blocks only // open lmd_js = lmd_js . substr ( 0 , startIndex ) + lmd_js . substr ( startIndex + startLength ) ; // close lmd_js = lmd_js . substr ( 0 , endIndex - startLength ) + lmd_js . substr ( endIndex + endLength - startLength ) ; if ( ! isInline ) { // indent block back var blockForIndent = lmd_js . substr ( startIndex , endIndex - startLength - startIndex ) ; blockForIndent = blockForIndent . split ( '\n' ) . map ( function ( line ) { return line . replace ( / ^\s{4} / , '' ) ; } ) . join ( '\n' ) ; lmd_js = lmd_js . substr ( 0 , startIndex ) + blockForIndent + lmd_js . substr ( endIndex - startLength ) ; } } else { // wipe all lmd_js = lmd_js . substr ( 0 , startIndex ) + lmd_js . substr ( endIndex + endLength ) ; } break ; } endIndex ++ ; } return true ; }


Input: Create stylesheet link [CODESPLIT] function ( e ) { if ( isNotLoaded ) { isNotLoaded = 0 ; // register or cleanup link . removeAttribute ( 'id' ) ; if ( ! e ) { sb . trigger ( '*:request-error' , moduleName , module ) ; } callback ( e ? sb . register ( moduleName , link ) : head . removeChild ( link ) && sb . undefined ) ; // e === undefined if error } }


Input: A method assignment helper for hierarchy subclasses . [CODESPLIT] function d3_layout_hierarchyRebind ( object , hierarchy ) { object . sort = d3 . rebind ( object , hierarchy . sort ) ; object . children = d3 . rebind ( object , hierarchy . children ) ; object . links = d3_layout_hierarchyLinks ; object . value = d3 . rebind ( object , hierarchy . value ) ; // If the new API is used, enabling inlining. object . nodes = function ( d ) { d3_layout_hierarchyInline = true ; return ( object . nodes = object ) ( d ) ; } ; return object ; }


Input: Positions the specified row of nodes . Modifies rect . [CODESPLIT] function position ( row , u , rect , flush ) { var i = - 1 , n = row . length , x = rect . x , y = rect . y , v = u ? round ( row . area / u ) : 0 , o ; if ( u == rect . dx ) { // horizontal subdivision if ( flush || v > rect . dy ) v = v ? rect . dy : 0 ; // over+underflow while ( ++ i < n ) { o = row [ i ] ; o . x = x ; o . y = y ; o . dy = v ; x += o . dx = v ? round ( o . area / v ) : 0 ; } o . z = true ; o . dx += rect . x + rect . dx - x ; // rounding error rect . y += v ; rect . dy -= v ; } else { // vertical subdivision if ( flush || v > rect . dx ) v = v ? rect . dx : 0 ; // over+underflow while ( ++ i < n ) { o = row [ i ] ; o . x = x ; o . y = y ; o . dx = v ; y += o . dy = v ? round ( o . area / v ) : 0 ; } o . z = false ; o . dy += rect . y + rect . dy - y ; // rounding error rect . x += v ; rect . dx -= v ; } }


Input: Lazily construct the package hierarchy from class names . [CODESPLIT] function ( classes ) { var map = { } ; function find ( name , data ) { var node = map [ name ] , i ; if ( ! node ) { node = map [ name ] = data || { name : name , children : [ ] } ; if ( name . length ) { node . parent = find ( "" ) ; node . parent . children . push ( node ) ; node . name = name ; node . key = escapeId ( name ) ; } } return node ; } classes . forEach ( function ( d ) { find ( d . name , d ) ; } ) ; return map [ "" ] ; }


Input: Simple JSON stringify [CODESPLIT] function stringify ( object ) { var properties = [ ] ; for ( var key in object ) { if ( object . hasOwnProperty ( key ) ) { properties . push ( quote ( key ) + ':' + getValue ( object [ key ] ) ) ; } } return "{" + properties . join ( "," ) + "}" ; }


Input: At initialization we bind to the relevant events on the Todos collection when items are added or changed . Kick things off by loading any preexisting todos that might be saved in * localStorage * . [CODESPLIT] function ( ) { this . input = this . $ ( '#new-todo' ) ; this . allCheckbox = this . $ ( '#toggle-all' ) [ 0 ] ; this . $footer = this . $ ( '#footer' ) ; this . $main = this . $ ( '#main' ) ; todos . on ( 'add' , this . addOne , this ) ; todos . on ( 'reset' , this . addAll , this ) ; todos . on ( 'change:completed' , this . filterOne , this ) ; todos . on ( "filter" , this . filterAll , this ) ; todos . on ( 'all' , this . render , this ) ; todos . fetch ( ) ; }


Input: Re - rendering the App just means refreshing the statistics -- the rest of the app doesn t change . [CODESPLIT] function ( ) { var completed = todos . completed ( ) . length ; var remaining = todos . remaining ( ) . length ; if ( todos . length ) { this . $main . show ( ) ; this . $footer . show ( ) ; this . $footer . html ( this . template ( { completed : completed , remaining : remaining } ) ) ; this . $ ( '#filters li a' ) . removeClass ( 'selected' ) . filter ( '[href="#/' + ( common . TodoFilter || '' ) + '"]' ) . addClass ( 'selected' ) ; } else { this . $main . hide ( ) ; this . $footer . hide ( ) ; } this . allCheckbox . checked = ! remaining ; }


Input: If you hit return in the main input field create new ** Todo ** model persisting it to * localStorage * . [CODESPLIT] function ( e ) { if ( e . which !== common . ENTER_KEY || ! this . input . val ( ) . trim ( ) ) { return ; } todos . create ( this . newAttributes ( ) ) ; this . input . val ( '' ) ; }


Input: Generic function for counting a line . It generates a lineId from the line number and the block name ( in minified files there are more logical lines on the same file line ) and adds a function call before the actual line of code . [CODESPLIT] function countLine ( ) { var ret ; // skip first line if ( isFirstLine ) { isFirstLine = false ; return ret ; } if ( this [ 0 ] . start && analyzing . indexOf ( this ) < 0 ) { giveNameToAnonymousFunction . call ( this ) ; var lineId = this [ 0 ] . start . line + lineOffset + '' ; //this[0].name + ':' + this[0].start.line + ":" + this[0].start.pos; rememberStatement ( lineId ) ; analyzing . push ( this ) ; ret = [ "splice" , [ [ "stat" , [ "call" , [ "dot" , [ "name" , "require" ] , "coverage_line" ] , [ [ "string" , moduleName ] , [ "string" , lineId ] ] ] ] , walker . walk ( this ) ] ] ; analyzing . pop ( this ) ; } return ret ; }


Input: Walker for if nodes . It overrides countLine because we want to instrument conditions . [CODESPLIT] function countIf ( ) { var self = this , ret ; if ( self [ 0 ] . start && analyzing . indexOf ( self ) < 0 ) { var decision = self [ 1 ] ; var lineId = self [ 0 ] . name + ':' + ( self [ 0 ] . start . line + lineOffset ) ; self [ 1 ] = wrapCondition ( decision , lineId ) ; // We are adding new lines, make sure code blocks are actual blocks if ( self [ 2 ] && self [ 2 ] [ 0 ] . start && self [ 2 ] [ 0 ] . start . value != "{" ) { self [ 2 ] = [ "block" , [ self [ 2 ] ] ] ; } if ( self [ 3 ] && self [ 3 ] [ 0 ] . start && self [ 3 ] [ 0 ] . start . value != "{" ) { self [ 3 ] = [ "block" , [ self [ 3 ] ] ] ; } } ret = countLine . call ( self ) ; if ( decision ) { analyzing . pop ( decision ) ; } return ret ; }


Input: This is the key function for condition coverage as it wraps every condition in a function call . The condition id is generated fron the lineId ( [CODESPLIT] function wrapCondition ( decision , lineId , parentPos ) { if ( options . condition === false ) { // condition coverage is disabled return decision ; } if ( isSingleCondition ( decision ) ) { var pos = getPositionStart ( decision , parentPos ) ; var condId = lineId + ":" + pos ; analyzing . push ( decision ) ; allConditions . push ( condId ) ; return [ "call" , [ "dot" , [ "name" , "require" ] , "coverage_condition" ] , [ [ "string" , moduleName ] , [ "string" , condId ] , decision ] ] ; } else { decision [ 2 ] = wrapCondition ( decision [ 2 ] , lineId , getPositionStart ( decision , parentPos ) ) ; decision [ 3 ] = wrapCondition ( decision [ 3 ] , lineId , getPositionEnd ( decision , parentPos ) ) ; return decision ; } }


Input: Wheter or not the if decision has only one boolean condition [CODESPLIT] function isSingleCondition ( decision ) { if ( decision [ 0 ] . start && decision [ 0 ] . name != "binary" ) { return true ; } else if ( decision [ 1 ] == "&&" || decision [ 1 ] == "||" ) { return false ; } else { return true ; } }


Input: Label nodes need special treatment as well . [CODESPLIT] function countLabel ( ) { var ret ; if ( this [ 0 ] . start && analyzing . indexOf ( this ) < 0 ) { var content = this [ 2 ] ; if ( content [ 0 ] . name == "for" && content [ 4 ] && content [ 4 ] . name != "block" ) { content [ 4 ] = [ "block" , [ content [ 4 ] ] ] ; } analyzing . push ( content ) ; var ret = countLine . call ( this ) ; analyzing . pop ( content ) ; } return ret ; }


Input: Instrumenting function strictly needed for statement coverage only in case of defun ( function definition ) however the block function does not correspond to a new statement . This method allows to track every function call ( function coverage ) . [CODESPLIT] function countFunction ( ) { var ret ; if ( isFirstLine ) { isFirstLine = false ; return ret ; } if ( this [ 0 ] . start && analyzing . indexOf ( this ) < 0 ) { var defun = this [ 0 ] . name === "defun" ; var lineId = this [ 0 ] . start . line + lineOffset + '' ; //this[0].name + ":" + this[0].start.line + ":" + this[0].start.pos; var fnName = this [ 1 ] || this [ 0 ] . anonymousName || "(?)" ; var fnId = fnName + ':' + ( this [ 0 ] . start . line + lineOffset ) + ":" + this [ 0 ] . start . pos ; var body = this [ 3 ] ; analyzing . push ( this ) ; // put a new function call inside the body, works also on empty functions if ( options [ "function" ] ) { body . splice ( 0 , 0 , [ "stat" , [ "call" , [ "dot" , [ "name" , "require" ] , "coverage_function" ] , [ [ "string" , moduleName ] , [ "string" , fnId ] ] ] ] ) ; // It would be great to instrument the 'exit' from a function // but it means tracking all return statements, maybe in the future... rememberFunction ( fnId ) ; } if ( defun ) { // 'defun' should also be remembered as statements rememberStatement ( lineId ) ; ret = [ "splice" , [ [ "stat" , [ "call" , [ "dot" , [ "name" , "require" ] , "coverage_line" ] , [ [ "string" , moduleName ] , [ "string" , lineId ] ] ] ] , walker . walk ( this ) ] ] ; } else { ret = walker . walk ( this ) ; } analyzing . pop ( this ) ; } return ret ; }


Input: This function tries to extract the name of anonymous functions depending on where they are defined . [CODESPLIT] function giveNameToAnonymousFunction ( ) { var node = this ; if ( node [ 0 ] . name == "var" || node [ 0 ] . name == "object" ) { node [ 1 ] . forEach ( function ( assignemt ) { if ( assignemt [ 1 ] ) { if ( assignemt [ 1 ] [ 0 ] . name === "function" ) { assignemt [ 1 ] [ 0 ] . anonymousName = assignemt [ 0 ] ; } else if ( assignemt [ 1 ] [ 0 ] . name === "conditional" ) { if ( assignemt [ 1 ] [ 2 ] [ 0 ] && assignemt [ 1 ] [ 2 ] [ 0 ] . name === "function" ) { assignemt [ 1 ] [ 2 ] [ 0 ] . anonymousName = assignemt [ 0 ] ; } if ( assignemt [ 1 ] [ 3 ] [ 0 ] && assignemt [ 1 ] [ 3 ] [ 0 ] . name === "function" ) { assignemt [ 1 ] [ 3 ] [ 0 ] . anonymousName = assignemt [ 0 ] ; } } } } ) ; } else if ( node [ 0 ] . name == "assign" && node [ 1 ] === true ) { if ( node [ 3 ] [ 0 ] . name === "function" ) { node [ 3 ] [ 0 ] . anonymousName = getNameFromAssign ( node ) ; } else if ( node [ 3 ] [ 0 ] === "conditional" ) { if ( node [ 3 ] [ 2 ] [ 0 ] && node [ 3 ] [ 2 ] [ 0 ] . name === "function" ) { node [ 3 ] [ 2 ] [ 0 ] . anonymousName = getNameFromAssign ( node ) ; } if ( node [ 3 ] [ 3 ] [ 0 ] && node [ 3 ] [ 3 ] [ 0 ] . name === "function" ) { node [ 3 ] [ 3 ] [ 0 ] . anonymousName = getNameFromAssign ( node ) ; } } } }


Input: This function wraps ternary conditionals in order to have condition coverage [CODESPLIT] function wrapConditionals ( ) { if ( options . condition === false ) { // condition coverage is disabled return ; } var self = this , ret ; if ( self [ 0 ] . start && analyzing . indexOf ( self ) < 0 ) { analyzing . push ( self ) ; var lineId = self [ 0 ] . name + ':' + ( self [ 0 ] . start . line + lineOffset ) ; self [ 1 ] = wrapCondition ( self [ 1 ] , lineId ) ; self [ 2 ] = walker . walk ( self [ 2 ] ) ; self [ 3 ] = walker . walk ( self [ 3 ] ) ; analyzing . pop ( self ) ; return self ; } else if ( self [ 1 ] ) { self [ 1 ] = wrapCondition ( self [ 1 ] , lineId ) ; } }


Input: RequireJS & AMD - style define [CODESPLIT] function ( name , deps , module ) { switch ( arguments . length ) { case 1 : // define(function () {}) module = name ; deps = name = sb . undefined ; break ; case 2 : // define(['a', 'b'], function () {}) module = deps ; deps = name ; name = sb . undefined ; break ; case 3 : // define('name', ['a', 'b'], function () {}) } if ( typeof module !== "function" ) { amdModules [ currentModule ] = module ; return ; } var output = { 'exports' : { } } ; if ( ! deps ) { deps = [ "require" , "exports" , "module" ] ; } for ( var i = 0 , c = deps . length ; i < c ; i ++ ) { switch ( deps [ i ] ) { case "require" : deps [ i ] = currentRequire ; break ; case "module" : deps [ i ] = output ; break ; case "exports" : deps [ i ] = output . exports ; break ; default : deps [ i ] = currentRequire && currentRequire ( deps [ i ] ) ; } } module = module . apply ( this , deps ) || output . exports ; amdModules [ currentModule ] = module ; }


Input: Calculate coverage total [CODESPLIT] function stats_calculate_coverage ( moduleName ) { var stats = sb . trigger ( '*:stats-get' , moduleName , null ) [ 1 ] , total , covered , lineId , lineNum , parts ; var lineReport = { } ; if ( ! stats . lines ) { return ; } stats . coverage = { } ; covered = 0 ; total = stats . lines . length ; for ( lineId in stats . runLines ) { if ( stats . runLines [ lineId ] > 0 ) { covered ++ ; } else { lineNum = lineId ; if ( ! lineReport [ lineNum ] ) { lineReport [ lineNum ] = { } ; } lineReport [ lineNum ] . lines = false ; } } stats . coverage . lines = { total : total , covered : covered , percentage : 100.0 * ( total ? covered / total : 1 ) } ; covered = 0 ; total = stats . functions . length ; for ( lineId in stats . runFunctions ) { if ( stats . runFunctions [ lineId ] > 0 ) { covered ++ ; } else { parts = lineId . split ( ':' ) ; lineNum = parts [ 1 ] ; if ( ! lineReport [ lineNum ] ) { lineReport [ lineNum ] = { } ; } if ( ! lineReport [ lineNum ] . functions ) { lineReport [ lineNum ] . functions = [ ] ; } lineReport [ lineNum ] . functions . push ( parts [ 0 ] ) ; } } stats . coverage . functions = { total : total , covered : covered , percentage : 100.0 * ( total ? covered / total : 1 ) } ; covered = 0 ; total = stats . conditions . length ; for ( lineId in stats . runConditions ) { if ( stats . runConditions [ lineId ] [ 1 ] > 0 ) { covered += 1 ; } if ( stats . runConditions [ lineId ] [ 1 ] === 0 ) { parts = lineId . split ( ':' ) ; lineNum = parts [ 1 ] ; if ( ! lineReport [ lineNum ] ) { lineReport [ lineNum ] = { } ; } if ( ! lineReport [ lineNum ] . conditions ) { lineReport [ lineNum ] . conditions = [ ] ; } lineReport [ lineNum ] . conditions . push ( stats . runConditions [ lineId ] ) ; } } stats . coverage . conditions = { total : total , covered : covered , percentage : 100.0 * ( total ? covered / total : 1 ) } ; stats . coverage . report = lineReport ; }


Input:
require ( undefined ) [CODESPLIT] function Roster ( element ) { element . innerHTML += this . renderWrapper ( ) ; var contactsHtml = [ ] ; for ( var i = 100 ; i -- > 0 ; ) { contactsHtml . push ( this . renderItem ( ) ) ; } $ ( '.b-roster' ) . innerHTML = contactsHtml . join ( '' ) ; $ ( '.b-roster' ) . addEventListener ( 'click' , function ( e ) { // Preload talk for dialog using parallel resource loading
 require . async ( [ 'js/lmd/modules/b-dialog.min.js' , 'js/lmd/modules/b-talk.min.js' ] , function ( Dialog ) { new Dialog ( element ) ; } ) ; } , false ) ; }


Input: / * wrapped by builder LMD require . js () and shortcuts example [CODESPLIT] function renderMap ( ) { var $map = $ ( '#map' ) ; // @see http://api.yandex.ru/maps/jsbox/geolocation_ip ymaps . ready ( function ( ) { // IP based geolocation var geolocation = ymaps . geolocation , coords = [ geolocation . latitude , geolocation . longitude ] , myMap = new ymaps . Map ( $map [ 0 ] , { center : coords , zoom : 10 } ) ; myMap . geoObjects . add ( new ymaps . Placemark ( coords , { // add balloon balloonContentHeader : geolocation . country , balloonContent : geolocation . city , balloonContentFooter : geolocation . region } ) ) ; } ) ; }


Input: It uses _ . template to interpolate config strings { output : index - <% = version % > . js version : 1 . 0 . 1 } [CODESPLIT] function interpolateConfigStrings ( config , data ) { data = data || config ; for ( var key in config ) { var value = config [ key ] ; if ( typeof value === "object" ) { config [ key ] = interpolateConfigStrings ( value , data ) ; } else if ( typeof value === "string" ) { var currentInterpolation = 0 ; while ( templateParts . test ( value ) ) { currentInterpolation ++ ; if ( currentInterpolation > maxInterpolateRecursion ) { break ; } config [ key ] = value = template ( value , data ) ; } } } return config ; }


Input: Merges mixins with config [CODESPLIT] function ( config , mixins ) { if ( Array . isArray ( config . mixins ) && Array . isArray ( mixins ) ) { config . mixins . push . apply ( config . mixins , mixins ) ; return config ; } return deepDestructableMerge ( config , { mixins : mixins } ) ; }


Input: Config files deep merge [CODESPLIT] function ( left , right ) { for ( var prop in right ) { if ( right . hasOwnProperty ( prop ) ) { if ( typeof left [ prop ] === "object" ) { deepDestructableMerge ( left [ prop ] , right [ prop ] ) ; } else { left [ prop ] = right [ prop ] ; } } } return left ; }


Input: Merges all config files in module s lineage [CODESPLIT] function ( config , configDir ) { config = config || { } ; if ( typeof config . extends !== "string" ) { return config ; } var parentConfig = tryExtend ( readConfig ( configDir , config . extends ) , configDir ) ; return deepDestructableMerge ( parentConfig , config ) ; }


Input: Returns depends config file of this module [CODESPLIT] function ( modulePath , dependsFileMask ) { modulePath = [ ] . concat ( modulePath ) ; return modulePath . map ( function ( modulePath ) { var fileName = modulePath . replace ( / ^.*\/|\.[a-z0-9]+$ / g , '' ) ; return path . join ( path . dirname ( modulePath ) , dependsFileMask . replace ( '*' , fileName ) ) ; } ) ; }


Input: Merges configs flags [CODESPLIT] function ( configA , configB , flagsNames , isMasterConfig ) { // Apply Flags flagsNames . forEach ( function ( optionsName ) { // if master -> B if ( typeof configB [ optionsName ] === "undefined" ) { return ; } if ( isMasterConfig ) { configA [ optionsName ] = configB [ optionsName ] ; } else { // if A literal B array -> B if ( configB [ optionsName ] instanceof Array && ! ( configA [ optionsName ] instanceof Array ) ) { configA [ optionsName ] = configB [ optionsName ] ; } else if ( configB [ optionsName ] instanceof Array && configA [ optionsName ] instanceof Array ) { // if A array B array -> A concat B configA [ optionsName ] = configA [ optionsName ] . concat ( configB [ optionsName ] ) ; } else { // if A literal B literal -> union // if A array B literal -> A configA [ optionsName ] = configA [ optionsName ] || configB [ optionsName ] ; } // else {} } } ) ; }


Input: Merges configs [CODESPLIT] function ( configA , configB , flagsNames , inheritableFields , isMasterConfig , context ) { if ( isMasterConfig ) { // Apply master fields inheritableFields . forEach ( function ( fieldName ) { if ( typeof configB [ fieldName ] !== "undefined" ) { configA [ fieldName ] = configB [ fieldName ] ; if ( FILED_ALIASES . hasOwnProperty ( fieldName ) ) { configA [ FILED_ALIASES [ fieldName ] ] = configB [ fieldName ] ; } } } ) ; } // Save errors configA . errors = configA . errors || [ ] ; configB . errors = configB . errors || [ ] ; configA . errors = configA . errors . concat ( configB . errors ) ; // Apply Flags mergeFlags ( configA , configB , flagsNames , isMasterConfig ) ; // Apply Modules configA . modules = configA . modules || { } ; configB . modules = configB . modules || { } ; for ( var moduleName in configB . modules ) { // Warn if module exists an its not a master config if ( ! isMasterConfig && configA . modules [ moduleName ] ) { if ( ! isModulesEqual ( configA . modules [ moduleName ] , configB . modules [ moduleName ] ) ) { configA . errors . push ( 'Name conflict! Module **"' + moduleName + '"** will be overwritten by ' + context ) ; } } configA . modules [ moduleName ] = configB . modules [ moduleName ] ; } // Apply styles configA . styles = configA . styles || [ ] ; configB . styles = configB . styles || [ ] ; configA . styles = configA . styles . concat ( configB . styles ) ; // Apply Bundles configA . bundles = configA . bundles || { } ; configB . bundles = configB . bundles || { } ; for ( var bundleName in configB . bundles ) { if ( configB . bundles [ bundleName ] ) { if ( ! configA . bundles [ bundleName ] ) { configA . bundles [ bundleName ] = { } ; } // Bundle is not exists if ( configB . bundles [ bundleName ] instanceof Error ) { configA . bundles [ bundleName ] = configB . bundles [ bundleName ] ; } else { mergeConfigs ( configA . bundles [ bundleName ] , configB . bundles [ bundleName ] , flagsNames , MASTER_FIELDS , true , context ) ; } } } // Apply User Plugins configA . plugins = configA . plugins || { } ; configB . plugins = configB . plugins || { } ; for ( var pluginName in configB . plugins ) { // Warn if module exists an its not a master if ( ! isMasterConfig && configA . plugins [ pluginName ] ) { configA . errors . push ( 'Name conflict! User plugin **"' + pluginName + '"** will be overwritten by ' + context ) ; } configA . plugins [ pluginName ] = configB . plugins [ pluginName ] ; } return configA ; // not rly need... }


Input: Creates LMD config : applies depends and extends [CODESPLIT] function ( rawConfig , configFile , configDir , flagsNames , extraOptions , usedConfigs ) { flagsNames = flagsNames || Object . keys ( LMD_PLUGINS ) ; var isFirstRun = typeof usedConfigs === "undefined" ; usedConfigs = usedConfigs || { } ; usedConfigs [ configFile ] = true ; // mark config as used var configs = [ ] , resultConfig = { modules : { } , errors : [ ] , plugins_depends : { } } ; if ( extraOptions && extraOptions . mixins ) { rawConfig = mergeMixins ( rawConfig , extraOptions . mixins ) ; } if ( extraOptions && extraOptions . styles ) { rawConfig = deepDestructableMerge ( rawConfig , { styles : extraOptions . styles } ) ; } // collect modules and module options var modules = collectModules ( rawConfig , configDir ) ; if ( rawConfig . depends ) { var /*dependsMask = rawConfig.depends === true ? DEFAULT_DEPENDS_MASK : rawConfig.depends,*/ dependsConfigPath , dependsMask ; for ( var moduleName in modules ) { if ( ! modules [ moduleName ] . is_shortcut && ! modules [ moduleName ] . is_ignored ) { dependsMask = modules [ moduleName ] . depends ; dependsConfigPath = getDependsConfigOf ( modules [ moduleName ] . path , dependsMask ) ; dependsConfigPath . forEach ( function ( dependsConfigPath ) { if ( fileExists ( dependsConfigPath ) ) { if ( ! usedConfigs [ dependsConfigPath ] ) { configs . unshift ( { context : 'depends config **' + dependsConfigPath + '**' , config : assembleLmdConfig ( dependsConfigPath , flagsNames , null , usedConfigs ) } ) ; } } } ) ; } } } // extend parent config if ( typeof rawConfig [ 'extends' ] === "string" ) { var parentConfigFile = fs . realpathSync ( configDir + '/' + rawConfig [ 'extends' ] ) ; if ( ! usedConfigs [ parentConfigFile ] ) { var parentConfig = assembleLmdConfig ( parentConfigFile , flagsNames , null , usedConfigs ) ; } } var processedConfig = { modules : modules , styles : collectStyles ( rawConfig , configDir ) , bundles : collectBundles ( rawConfig , configDir ) , plugins : collectUserPlugins ( rawConfig , configDir ) } ; // keep fields MASTER_FIELDS . forEach ( function ( fieldName ) { processedConfig [ fieldName ] = rawConfig [ fieldName ] ; if ( FILED_ALIASES . hasOwnProperty ( fieldName ) ) { processedConfig [ FILED_ALIASES [ fieldName ] ] = rawConfig [ fieldName ] ; } } ) ; // keep flags flagsNames . forEach ( function ( fieldName ) { processedConfig [ fieldName ] = rawConfig [ fieldName ] ; } ) ; if ( parentConfig ) { mergeConfigs ( resultConfig , parentConfig , flagsNames , INHERITABLE_FIELDS , true , 'parent config **' + parentConfigFile + '**' ) ; } for ( var i = 0 , c = configs . length , dependsMainModuleName ; i < c ; i ++ ) { // Cleanup main module from depends dependsMainModuleName = configs [ i ] . config . main || "main" ; if ( configs [ i ] . config . modules ) { delete configs [ i ] . config . modules [ dependsMainModuleName ] ; } mergeConfigs ( resultConfig , configs [ i ] . config , flagsNames , [ ] , false , configs [ i ] . context ) ; } mergeConfigs ( resultConfig , processedConfig , flagsNames , MASTER_FIELDS , true , 'main config **' + configFile + '**' ) ; if ( isFirstRun ) { // Apply mixins var mixins = resultConfig . mixins ; if ( Array . isArray ( mixins ) ) { mixins . forEach ( function ( mixinName ) { var mixinConfigFile = fs . realpathSync ( configDir + '/' + mixinName ) , processedMixin = assembleLmdConfig ( mixinConfigFile , flagsNames , null , usedConfigs ) ; mergeConfigs ( resultConfig , processedMixin , flagsNames , INHERITABLE_FIELDS , true , 'mixin config **' + mixinConfigFile + '**' ) ; } ) ; } if ( extraOptions ) { extraOptions . modules = collectModules ( extraOptions , configDir ) ; extraOptions . bundles = collectBundles ( extraOptions , configDir ) ; extraOptions . styles = collectStyles ( extraOptions , configDir ) ; mergeConfigs ( resultConfig , extraOptions , flagsNames , EXTRA_OPTIONS_FIELDS , true , 'CLI options' ) ; } reapplyModuleOptions ( resultConfig ) ; addPluginsFromBundles ( resultConfig ) ; addPluginsDepends ( resultConfig ) ; flattenBundles ( resultConfig ) ; resolveStyles ( resultConfig ) ; bundlesInheritFieldsFromPackage ( resultConfig ) ; removeIgnoredModules ( resultConfig ) ; } return resultConfig ; }


Input: Creates LMD config : applies depends and extends [CODESPLIT] function ( configFile , flagsNames , extraOptions , usedConfigs ) { var configDir = path . dirname ( configFile ) , rawConfig = readConfig ( configFile ) ; configFile = fs . realpathSync ( configFile ) ; return assembleLmdConfigAsObject ( rawConfig , configFile , configDir , flagsNames , extraOptions , usedConfigs ) ; }


Input: For now add plugins from build to bundle [CODESPLIT] function addPluginsFromBundles ( resultConfig ) { if ( resultConfig . bundles ) { var bundles = Object . keys ( resultConfig . bundles ) , lmdPlugins = Object . keys ( LMD_PLUGINS ) ; // Apply flags from bundles bundles . forEach ( function ( bundleName ) { mergeFlags ( resultConfig , resultConfig . bundles [ bundleName ] , lmdPlugins , false ) ; } ) ; // Set bundle plugin if ( bundles . length ) { resultConfig . bundle = true ; } } }


Input: @name LmdModuleStruct @class [CODESPLIT] function ( config , configDir ) { var modules = { } , globalLazy = config . lazy || false , globalDepends = ( config . depends === true ? DEFAULT_DEPENDS_MASK : config . depends ) || false , moduleLazy = false , moduleTypeHint , moduleName , modulePath , moduleRealPath , moduleExists , moduleExports , moduleRequire , moduleBind , moduleFileName , moduleFilePath , moduleDesciptor , wildcardRegex , isMultiPathModule , moduleData , isThirdPartyModule , modulesDirPath = config . root || config . path || '' ; modulesDirPath = path . resolve ( configDir , modulesDirPath ) ; // grep paths for ( moduleName in config . modules ) { moduleDesciptor = config . modules [ moduleName ] ; // case "moduleName": null // case "moduleName": "path/to/module.js" if ( moduleDesciptor === null || typeof moduleDesciptor === "string" || Array . isArray ( moduleDesciptor ) ) { moduleTypeHint = false ; moduleExports = false ; moduleRequire = false ; moduleBind = false ; modulePath = moduleDesciptor ; moduleLazy = globalLazy ; } else { // case "moduleName": {"path": "path/to/module.js", "lazy": false} moduleTypeHint = moduleDesciptor . type || false ; moduleExports = moduleDesciptor . exports || false ; moduleRequire = moduleDesciptor . require || false ; moduleBind = moduleDesciptor . bind || moduleDesciptor [ 'this' ] || false ; modulePath = moduleDesciptor . path ; moduleLazy = moduleDesciptor . lazy || false ; moduleTypeHint = moduleDesciptor . type || false ; } isMultiPathModule = false ; if ( Array . isArray ( modulePath ) ) { // Try to glob // case when ['jquery*.js'] modulePath = modulePath . reduce ( function ( paths , modulePath ) { if ( globPattern . test ( modulePath ) ) { modulePath = glob . sync ( modulePath , { cwd : modulesDirPath , nosort : true } ) || [ ] ; } return paths . concat ( modulePath ) ; } , [ ] ) ; // case when ['jquery.js'] if ( modulePath . length === 1 ) { modulePath = modulePath [ 0 ] ; } else { isMultiPathModule = true ; } } isThirdPartyModule = ! ! moduleExports || ! ! moduleRequire || ! ! moduleBind ; // Override if cache flag = true if ( config . cache ) { moduleLazy = true ; } // its a glob pattern // @see https://github.com/isaacs/node-glob if ( ! isMultiPathModule && globPattern . test ( modulePath ) ) { var globModules = glob . sync ( modulePath , { cwd : modulesDirPath , nosort : true } ) ; // * -> <%= file => for backward capability var moduleNameTemplate = template ( moduleName . replace ( '*' , '<%= file %>' ) ) ; globModules . forEach ( function ( module ) { var moduleRealPath = path . join ( modulesDirPath , module ) , basename = path . basename ( moduleRealPath ) , fileParts = basename . split ( '.' ) , ext = fileParts . pop ( ) , file = fileParts . join ( '.' ) , dir = path . dirname ( moduleRealPath ) . split ( path . sep ) . reverse ( ) , subdir = createSubdirTemplateVariable ( modulesDirPath , moduleRealPath ) ; // modify module name using template var newModuleName = moduleNameTemplate ( { basename : basename , file : file , ext : ext , dir : dir , subdir : subdir } ) ; moduleExists = true ; try { moduleRealPath = fs . realpathSync ( moduleRealPath ) ; } catch ( e ) { moduleExists = false ; } moduleData = { originalModuleDesciptor : moduleDesciptor , name : newModuleName , path : moduleRealPath , originalPath : modulePath , lines : 0 , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : moduleExists , is_third_party : isThirdPartyModule , is_lazy : moduleLazy , is_greedy : true , is_shortcut : false , is_coverage : isCoverage ( config , newModuleName ) , is_ignored : false , is_sandbox : moduleDesciptor . sandbox || false , is_multi_path_module : isMultiPathModule , depends : typeof moduleDesciptor . depends === "undefined" ? globalDepends : moduleDesciptor . depends } ; // wildcard have a low priority // if module was directly named it pass if ( ! ( modules [ newModuleName ] && ! modules [ newModuleName ] . is_greedy ) ) { modules [ newModuleName ] = moduleData ; } } ) ; } else if ( ! isMultiPathModule && / ^@ / . test ( modulePath ) ) { // shortcut modules [ moduleName ] = { originalModuleDesciptor : moduleDesciptor , name : moduleName , originalPath : modulePath , lines : 0 , path : modulePath , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : true , is_third_party : isThirdPartyModule , is_lazy : moduleLazy , is_greedy : false , is_shortcut : true , is_coverage : false , is_ignored : false , is_sandbox : moduleDesciptor . sandbox || false , is_multi_path_module : isMultiPathModule , depends : typeof moduleDesciptor . depends === "undefined" ? globalDepends : moduleDesciptor . depends } ; } else if ( modulePath === null ) { modules [ moduleName ] = { originalModuleDesciptor : moduleDesciptor , name : moduleName , originalPath : modulePath , lines : 0 , path : modulePath , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : true , is_third_party : false , is_lazy : false , is_greedy : false , is_shortcut : false , is_coverage : false , is_ignored : true , is_sandbox : false , is_multi_path_module : false , depends : globalDepends } ; } else { modulePath = [ ] . concat ( modulePath ) ; moduleExists = true ; moduleRealPath = modulePath . map ( function ( modulePath ) { return path . join ( modulesDirPath , modulePath ) ; } ) . map ( function ( moduleRealPath ) { try { return fs . realpathSync ( moduleRealPath ) ; } catch ( e ) { moduleExists = false ; } return moduleRealPath ; } ) ; // normal name // "name": "name.js" modules [ moduleName ] = { originalModuleDesciptor : moduleDesciptor , name : moduleName , path : isMultiPathModule ? moduleRealPath : moduleRealPath [ 0 ] , originalPath : isMultiPathModule ? modulePath : modulePath [ 0 ] , lines : 0 , extra_exports : moduleExports , extra_require : moduleRequire , extra_bind : moduleBind , type_hint : moduleTypeHint , is_exists : moduleExists , is_third_party : isThirdPartyModule , is_lazy : moduleLazy , is_greedy : false , is_shortcut : false , // Cant use code coverage with multi path module is_coverage : ! isMultiPathModule && isCoverage ( config , moduleName ) , is_ignored : false , is_sandbox : moduleDesciptor . sandbox || false , is_multi_path_module : isMultiPathModule , depends : typeof moduleDesciptor . depends === "undefined" ? globalDepends : moduleDesciptor . depends } ; } } return modules ; }


Input: Wrapper for non - lmd modules files [CODESPLIT] function ( code , options ) { var exports = [ ] , requires = [ ] , bind = [ ] , extra_exports = options . extra_exports , extra_require = options . extra_require , extra_bind = options . extra_bind , exportCode , bindModuleName ; // add exports to the module end // extra_exports = {name: code, name: code} if ( typeof extra_exports === "object" ) { for ( var exportName in extra_exports ) { exportCode = extra_exports [ exportName ] ; exports . push ( '    ' + JSON . stringify ( exportName ) + ': ' + exportCode ) ; } code += '\n\n/* added by builder */\nreturn {\n' + exports . join ( ',\n' ) + '\n};' ; } else if ( extra_exports ) { // extra_exports = string code += '\n\n/* added by builder */\nreturn ' + extra_exports + ';' ; } // change context of module (this) // and proxy return value // return function(){}.call({name: require('name')}); if ( typeof extra_bind === "object" ) { for ( var bindName in extra_bind ) { bindModuleName = extra_bind [ bindName ] ; bind . push ( '    ' + JSON . stringify ( bindName ) + ': require(' + JSON . stringify ( bindModuleName ) + ')' ) ; } code = '\nreturn function(){\n\n' + code + '\n}.call({\n' + bind . join ( ',\n' ) + '\n});' ; } else if ( extra_bind ) { // return function(){}.call(require('name')); code = '\nreturn function(){\n\n' + code + '\n}.call(require(' + JSON . stringify ( extra_bind ) + '));' ; } // add require to the module start if ( typeof extra_require === "object" ) { // extra_require = [name, name, name] if ( extra_require instanceof Array ) { for ( var i = 0 , c = extra_require . length , moduleName ; i < c ; i ++ ) { moduleName = extra_require [ i ] ; requires . push ( 'require(' + JSON . stringify ( moduleName ) + ');' ) ; } code = '/* added by builder */\n' + requires . join ( '\n' ) + '\n\n' + code ; } else { // extra_require = {name: name, name: name} for ( var localName in extra_require ) { moduleName = extra_require [ localName ] ; requires . push ( localName + ' = require(' + JSON . stringify ( moduleName ) + ')' ) ; } code = '/* added by builder */\nvar ' + requires . join ( ',\n    ' ) + ';\n\n' + code ; } } else if ( extra_require ) { // extra_require = string code = '/* added by builder */\nrequire(' + JSON . stringify ( extra_require ) + ');\n\n' + code ; } return '(function (require) { /* wrapped by builder */\n' + code + '\n})' ; }


Input: Aggregates all module wrappers [CODESPLIT] function ( code , moduleOptions , moduleType ) { switch ( moduleType ) { case "3-party" : // create lmd module from non-lmd module code = wrap3partyModule ( code , moduleOptions ) ; break ; case "plain" : // wrap plain module code = wrapPlainModule ( code ) ; break ; case "amd" : // AMD RequireJS code = wrapAmdModule ( code ) ; break ; case "fd" : case "fe" : // wipe tail ; code = removeTailSemicolons ( code ) ; } return code ; }


Input: Checks module type [CODESPLIT] function getModuleType ( code ) { var ast ; if ( typeof code === "object" ) { ast = code ; } else { try { JSON . parse ( code ) ; return "json" ; } catch ( e ) { } try { ast = parser . parse ( code ) ; } catch ( e ) { return "string" ; } } // Empty module if ( ast . length === 2 && ! ast [ 1 ] . length && ast [ 0 ] === 'toplevel' ) return "plain" ; // ["toplevel",[["defun","depA",["require"],[]]]] if ( ast && ast . length === 2 && ast [ 1 ] && ast [ 1 ] . length === 1 && ast [ 1 ] [ 0 ] [ 0 ] === "defun" ) { return "fd" ; } // ["toplevel",[["stat",["function",null,["require"],[]]]]] if ( ast && ast . length === 2 && ast [ 1 ] && ast [ 1 ] . length === 1 && ast [ 1 ] [ 0 ] [ 0 ] === "stat" && ast [ 1 ] [ 0 ] [ 1 ] && ast [ 1 ] [ 0 ] [ 1 ] [ 0 ] === "function" ) { return "fe" ; } if ( ast ) { var isAmd = ast [ 1 ] . every ( function ( ast ) { return ast [ 0 ] === "stat" && ast [ 1 ] [ 0 ] === "call" && ast [ 1 ] [ 1 ] [ 0 ] === "name" && ast [ 1 ] [ 1 ] [ 1 ] === "define" ; } ) ; if ( isAmd ) { return "amd" ; } } return "plain" ; }


Input: @param { String } lmdDir @param { String } shortName [CODESPLIT] function getModuleFileByShortName ( lmdDir , shortName ) { var files ; try { files = fs . readdirSync ( lmdDir ) ; } catch ( e ) { return void 0 ; } for ( var i = 0 , c = files . length , fileName ; i < c ; i ++ ) { fileName = files [ i ] ; var fileExtension = ( fileName . match ( reLmdFile ) || 0 ) [ 0 ] ; if ( fileExtension && path . basename ( fileName , fileExtension ) === shortName ) { return fileName ; } } }


Input: Compute x - scale and normalize the first row . Compute shear and make second row orthogonal to first . Compute y - scale and normalize the second row . Finally compute the rotation . [CODESPLIT] function d3_transform ( m ) { var r0 = [ m . a , m . b ] , r1 = [ m . c , m . d ] , kx = d3_transformNormalize ( r0 ) , kz = d3_transformDot ( r0 , r1 ) , ky = d3_transformNormalize ( d3_transformCombine ( r1 , r0 , - kz ) ) ; this . translate = [ m . e , m . f ] ; this . rotate = Math . atan2 ( m . b , m . a ) * d3_transformDegrees ; this . scale = [ kx , ky || 0 ] ; this . skew = ky ? kz / ky * d3_transformDegrees : 0 ; }


Input: Converts the specified array of data into an array of points ( x - y tuples ) by evaluating the specified x and y functions on each data point . The this context of the evaluated functions is the specified self object ; each function is passed the current datum and index . [CODESPLIT] function d3_svg_linePoints ( self , d , x , y ) { var points = [ ] , i = - 1 , n = d . length , fx = typeof x === "function" , fy = typeof y === "function" , value ; if ( fx && fy ) { while ( ++ i < n ) points . push ( [ x . call ( self , value = d [ i ] , i ) , y . call ( self , value , i ) ] ) ; } else if ( fx ) { while ( ++ i < n ) points . push ( [ x . call ( self , d [ i ] , i ) , y ] ) ; } else if ( fy ) { while ( ++ i < n ) points . push ( [ x , y . call ( self , d [ i ] , i ) ] ) ; } else { while ( ++ i < n ) points . push ( [ x , y ] ) ; } return points ; }


Input: TODO Allow control point to be customized . [CODESPLIT] function chord ( d , i ) { var s = subgroup ( this , source , d , i ) , t = subgroup ( this , target , d , i ) ; return "M" + s . p0 + arc ( s . r , s . p1 ) + ( equals ( s , t ) ? curve ( s . r , s . p1 , s . r , s . p0 ) : curve ( s . r , s . p1 , t . r , t . p0 ) + arc ( t . r , t . p1 ) + curve ( t . r , t . p1 , s . r , s . p0 ) ) + "Z" ; }


Input: [ x0 y0 ] [ x1 y1 ] [CODESPLIT] function brush ( g ) { var resizes = x && y ? [ "n" , "e" , "s" , "w" , "nw" , "ne" , "se" , "sw" ] : x ? [ "e" , "w" ] : y ? [ "n" , "s" ] : [ ] ; g . each ( function ( ) { var g = d3 . select ( this ) . on ( "mousedown.brush" , down ) , bg = g . selectAll ( ".background" ) . data ( [ , ] ) , fg = g . selectAll ( ".extent" ) . data ( [ , ] ) , tz = g . selectAll ( ".resize" ) . data ( resizes , String ) , e ; // An invisible, mouseable area for starting a new brush. bg . enter ( ) . append ( "svg:rect" ) . attr ( "class" , "background" ) . style ( "visibility" , "hidden" ) . style ( "pointer-events" , "all" ) . style ( "cursor" , "crosshair" ) ; // The visible brush extent; style this as you like! fg . enter ( ) . append ( "svg:rect" ) . attr ( "class" , "extent" ) . style ( "cursor" , "move" ) ; // More invisible rects for resizing the extent. tz . enter ( ) . append ( "svg:rect" ) . attr ( "class" , function ( d ) { return "resize " + d ; } ) . attr ( "width" , 6 ) . attr ( "height" , 6 ) . style ( "visibility" , "hidden" ) . style ( "pointer-events" , brush . empty ( ) ? "none" : "all" ) . style ( "cursor" , function ( d ) { return d3_svg_brushCursor [ d ] ; } ) ; // Remove any superfluous resizers. tz . exit ( ) . remove ( ) ; // Initialize the background to fill the defined range. // If the range isn't defined, you can post-process. if ( x ) { e = d3_scaleExtent ( x . range ( ) ) ; bg . attr ( "x" , e [ 0 ] ) . attr ( "width" , e [ 1 ] - e [ 0 ] ) ; d3_svg_brushRedrawX ( g , extent ) ; } if ( y ) { e = d3_scaleExtent ( y . range ( ) ) ; bg . attr ( "y" , e [ 0 ] ) . attr ( "height" , e [ 1 ] - e [ 0 ] ) ; d3_svg_brushRedrawY ( g , extent ) ; } } ) ; }


Input: snapshot the local context for subsequent dispatch [CODESPLIT] function start ( ) { d3_behavior_dragEvent = event ; d3_behavior_dragEventTarget = d3 . event . target ; d3_behavior_dragTarget = this ; d3_behavior_dragArguments = arguments ; d3_behavior_dragOrigin = d3_behavior_dragPoint ( ) ; if ( origin ) { d3_behavior_dragOffset = origin . apply ( d3_behavior_dragTarget , d3_behavior_dragArguments ) ; d3_behavior_dragOffset = [ d3_behavior_dragOffset . x - d3_behavior_dragOrigin [ 0 ] , d3_behavior_dragOffset . y - d3_behavior_dragOrigin [ 1 ] ] ; } else { d3_behavior_dragOffset = [ 0 , 0 ] ; } d3_behavior_dragMoved = 0 ; }


Input: snapshot the local context for subsequent dispatch [CODESPLIT] function start ( ) { d3_behavior_zoomXyz = xyz ; d3_behavior_zoomExtent = extent ; d3_behavior_zoomDispatch = event . zoom ; d3_behavior_zoomEventTarget = d3 . event . target ; d3_behavior_zoomTarget = this ; d3_behavior_zoomArguments = arguments ; }


Input: store starting mouse location [CODESPLIT] function mousewheel ( ) { start . apply ( this , arguments ) ; if ( ! d3_behavior_zoomZooming ) d3_behavior_zoomZooming = d3_behavior_zoomLocation ( d3 . svg . mouse ( d3_behavior_zoomTarget ) ) ; d3_behavior_zoomTo ( d3_behavior_zoomDelta ( ) + xyz [ 2 ] , d3 . svg . mouse ( d3_behavior_zoomTarget ) , d3_behavior_zoomZooming ) ; }


Input: doubletap detection [CODESPLIT] function touchstart ( ) { start . apply ( this , arguments ) ; var touches = d3_behavior_zoomTouchup ( ) , touch , now = Date . now ( ) ; if ( ( touches . length === 1 ) && ( now - d3_behavior_zoomLast < 300 ) ) { d3_behavior_zoomTo ( 1 + Math . floor ( xyz [ 2 ] ) , touch = touches [ 0 ] , d3_behavior_zoomLocations [ touch . identifier ] ) ; } d3_behavior_zoomLast = now ; }


Input: detect the pixels that would be scrolled by this wheel event [CODESPLIT] function d3_behavior_zoomDelta ( ) { // mousewheel events are totally broken! // https://bugs.webkit.org/show_bug.cgi?id=40441 // not only that, but Chrome and Safari differ in re. to acceleration! if ( ! d3_behavior_zoomDiv ) { d3_behavior_zoomDiv = d3 . select ( "body" ) . append ( "div" ) . style ( "visibility" , "hidden" ) . style ( "top" , 0 ) . style ( "height" , 0 ) . style ( "width" , 0 ) . style ( "overflow-y" , "scroll" ) . append ( "div" ) . style ( "height" , "2000px" ) . node ( ) . parentNode ; } var e = d3 . event , delta ; try { d3_behavior_zoomDiv . scrollTop = 1000 ; d3_behavior_zoomDiv . dispatchEvent ( e ) ; delta = 1000 - d3_behavior_zoomDiv . scrollTop ; } catch ( error ) { delta = e . wheelDelta || ( - e . detail * 5 ) ; } return delta * .005 ; }


Input: Note : Since we don t rotate it s possible for the touches to become slightly detached from their original positions . Thus we recompute the touch points on touchend as well as touchstart! [CODESPLIT] function d3_behavior_zoomTouchup ( ) { var touches = d3 . svg . touches ( d3_behavior_zoomTarget ) , i = - 1 , n = touches . length , touch ; while ( ++ i < n ) d3_behavior_zoomLocations [ ( touch = touches [ i ] ) . identifier ] = d3_behavior_zoomLocation ( touch ) ; return touches ; }


Input: Cases : ( { main } { modules } { options } ) ( { modules } { options } ) ( { modules } ) [CODESPLIT] function ( _main , _modules , _modules_options ) { if ( typeof _main === "object" ) { _modules_options = _modules ; _modules = _main ; } for ( var moduleName in _modules ) { // if already initialized - skip if ( moduleName in sb . modules ) { continue ; } // declare new modules sb . modules [ moduleName ] = _modules [ moduleName ] ; sb . initialized [ moduleName ] = 0 ; // declare module options if ( _modules_options && moduleName in _modules_options ) { sb . modules_options [ moduleName ] = _modules_options [ moduleName ] ; } } if ( typeof _main === "function" ) { var output = { 'exports' : { } } ; _main ( sb . trigger ( 'lmd-register:decorate-require' , "<bundle:main>" , sb . require ) [ 1 ] , output . exports , output ) ; } }


Input: LMD require . js () and shortcuts example [CODESPLIT] function drawImageOnCanvas ( img ) { var ctx = $ ( 'canvas' ) [ 0 ] . getContext ( '2d' ) ; ctx . drawImage ( img , 0 , 0 ) ; ctx . rotate ( - Math . PI / 12 ) ; ctx . translate ( 0 , 150 ) ; }


Input: Formats lmd config [CODESPLIT] function ( data ) { var config ; // case data is argv string if ( typeof data === "string" ) { // try to parse new version config = parseArgv ( data ) ; // its new config argv string if ( Object . keys ( config ) . length ) { // translate short params to long one config . mode = config . mode || config . m ; config . output = config . output || config . o ; config . log = config . log || config . l ; config . config = config . config || config . c ; config [ 'no-warn' ] = config [ 'no-warn' ] || config [ 'no-w' ] ; config [ 'source-map' ] = config [ 'source-map' ] || config [ 'sm' ] ; config [ 'source-map-root' ] = config [ 'source-map-root' ] || config [ 'sm-root' ] ; config [ 'source-map-www' ] = config [ 'source-map-www' ] || config [ 'sm-www' ] ; config [ 'source-map-inline' ] = config [ 'source-map-inline' ] || config [ 'sm-inline' ] ; } else { // an old argv format, split argv and parse manually data = data . split ( ' ' ) ; // without mode if ( availableModes . indexOf ( data [ 2 ] ) === - 1 ) { config = { mode : 'main' , config : data [ 2 ] , output : data [ 3 ] } ; } else { // with mode config = { mode : data [ 2 ] , config : data [ 3 ] , output : data [ 4 ] } ; } } // case data is config object } else if ( typeof config === "object" ) { // use as is config = data ; // case else } else { // wut? throw new Error ( 'Bad config data' ) ; } config . mode = config . mode || 'main' ; config . warn = ! config [ 'no-warn' ] ; config . sourcemap = config [ 'source-map' ] || false ; config . www_root = config [ 'source-map-root' ] || "" ; config . sourcemap_www = config [ 'source-map-www' ] || "" ; config . sourcemap_inline = config [ 'source-map-inline' ] || false ; config . log = config . log || false ; return config ; }


Input: Return true if the urlNode is still current ( not stale ) by sitemap policy . If both lastmod and changefreq tags are supplied both are used . If only one of lastmod or changefreq are supplied then they are compared against previous output if it exists . If a test fails for any reason it is characterized as stale ( returns false ) . [CODESPLIT] function stillCurrent ( urlNode , options ) { var lesser , greater , oPath ; var now = Date . now ( ) ; var lMod = _ . first ( urlNode . lastmod ) ; var cFreq = _ . first ( urlNode . changefreq ) ? _ . first ( urlNode . changefreq ) . toLowerCase ( ) : null ; // only lastmod specified if ( lMod && ! cFreq ) { // if sitemap is malformed, just blow up oPath = base . outputFile ( options , urlNode . loc [ 0 ] ) ; lesser = now - ( ( fs . existsSync ( oPath ) && fs . statSync ( oPath ) . mtime . getTime ( ) ) || unixStart ) ; greater = now - Date . parse ( lMod ) ; } // only changefreq specified else if ( ! lMod && cFreq ) { // if sitemap is malformed, just blow up oPath = base . outputFile ( options , urlNode . loc [ 0 ] ) ; lesser = now - ( ( fs . existsSync ( oPath ) && fs . statSync ( oPath ) . mtime . getTime ( ) ) || unixStart ) ; greater = changeFreq [ cFreq ] || changeFreq . always ; } // both or neither were specified else { lesser = now - Date . parse ( lMod || unixStart ) ; greater = changeFreq [ cFreq ] || changeFreq . always ; } return lesser <= greater ; }


Input: Parse a sitemap document For each qualifying url element in urlset call base . input Stops processing if an error occurs . [CODESPLIT] function parse ( options , document , callback ) { xml2js . parseString ( document , { trim : true , normalizeTags : true , normalize : true } , function ( err , result ) { var source = options . source ; if ( ! err ) { // Process the url input, but break if base.input returns false. //   In other words, _.find is looking for a non-falsy err. // For now, this can only happen if no outputDir is defined, //   which is a fatal bad option problem and will happen immediately. _ . find ( // if the sitemap is malformed, just blow up result . urlset . url , function ( urlNode ) { // optionally ignore current urls by sitemap policy var url , process = ! options . sitemapPolicy || ! stillCurrent ( urlNode , options ) ; if ( process ) { // if sitemap is malformed, just blow up url = urlm . parse ( urlNode . loc [ 0 ] ) ; if ( ! base . input ( _ . extend ( { } , options , { protocol : url . protocol , auth : url . auth , hostname : url . hostname , port : url . port } ) , urlNode . loc [ 0 ] ) ) { source = urlNode . loc [ 0 ] ; err = base . generatorError ( ) ; } } return err ; } ) ; } callback ( common . prependMsgToErr ( err , source , true ) ) ; } ) ; }


Input: Convert Buffer input call next or callback with error [CODESPLIT] function convert ( options , buffer , next , callback ) { var gunzip = path . extname ( options . source ) === ".gz" ; if ( gunzip ) { zlib . gunzip ( buffer , function ( err , result ) { if ( err ) { callback ( common . prependMsgToErr ( err , options . source , true ) ) ; } else { next ( options , result && result . toString ( ) , callback ) ; } } ) ; } else { next ( options , buffer . toString ( ) , callback ) ; } }


Input: Retrieve the sitemap from a url and call to parse it . [CODESPLIT] function getUrl ( options , parseFn , callback ) { request ( { url : options . source , encoding : null , timeout : options . timeout ( ) // get the default timeout } , function ( err , res , body ) { var error = err || common . checkResponse ( res , [ "text/xml" , "application/xml" ] ) ; if ( error ) { callback ( common . prependMsgToErr ( error , options . source , true ) ) ; } else { convert ( options , body , parseFn , callback ) ; } } ) ; }


Input: Retrieve the sitemap from a file and call to parse it . [CODESPLIT] function getFile ( options , parseFn , callback ) { fs . readFile ( options . source , function ( err , data ) { if ( err ) { callback ( common . prependMsgToErr ( err , options . source , true ) ) ; } else { convert ( options , data , parseFn , callback ) ; } } ) ; }


Input: command line argument handling for selector based snapshot scripts args : PHANTOM_SCRIPT OUTPUTFILE URL SELECTOR [ TIMEOUT INTERVAL USEJQUERY FILTER ] [CODESPLIT] function ( ) { var options = { } ; var defaults = { // outputFile (required) // The file to write the snapshot to // encoding is the same as served from url outputFile : "snapshot.html" , // url (required) // The url to produce the snapshot from url : "http://localhost/" , // selector (required) // The selector to wait for before taking the snapshot // When the selector is visible, this defines document readiness selector : "body" , // timeout (optional) // The maximum amount of time (ms) to wait before giving up on the snapshot timeout : 10000 , // checkInterval (optional) // The frequency (ms) to check for document readiness checkInterval : 250 , // useJQuery (optional) // flag to indicate use jQuery selector or not. jQuery must already exist in page. useJQuery : false , // verbose (optional) // flag to indicate verbose output is desired. verbose : false // module (optional) // An external module to load // (default undefined) } ; if ( system . args . length < 4 ) { globals . exit ( 3 , "phantomjs script '" + system . args [ 0 ] + "' expected these arguments: OUTPUTFILE URL SELECTOR [TIMEOUT INTERVAL JQUERY MODULE]" ) ; } else { options . outputFile = system . args [ 1 ] ; options . url = system . args [ 2 ] ; options . selector = system . args [ 3 ] ; if ( system . args [ 4 ] ) { options . timeout = parseInt ( system . args [ 4 ] , 10 ) ; } if ( system . args [ 5 ] ) { options . checkInterval = parseInt ( system . args [ 5 ] , 10 ) ; } if ( system . args [ 6 ] ) { var useJQuery = system . args [ 6 ] . toLowerCase ( ) ; options . useJQuery = ( useJQuery === "true" || useJQuery === "yes" || useJQuery === "1" ) ; } if ( system . args [ 7 ] ) { var verbose = system . args [ 7 ] . toLowerCase ( ) ; options . verbose = ( verbose === "true" || verbose === "yes" || verbose === "1" ) ; } if ( system . args [ 8 ] && system . args [ 8 ] !== "undefined" ) { options . module = system . args [ 8 ] ; } // ensure defaults, replaces false with false in two cases (useJQuery, verbose) Object . keys ( defaults ) . forEach ( function ( prop ) { if ( ! options [ prop ] ) { options [ prop ] = defaults [ prop ] ; } } ) ; } return options ; }


Input: Ensures that options at least contains propties and values from must if they re not already defined and not null . Differs from underscore by replacing undefined * or null * falsies and only one defaults source allowed . [CODESPLIT] function ( options , must ) { if ( must ) { for ( var prop in must ) { if ( options [ prop ] === void 0 || options [ prop ] === null ) { options [ prop ] = must [ prop ] ; } } } return options ; }


Input: Prepend a message to an Error message . [CODESPLIT] function ( error , message , quoteInput ) { var result , prepend , empty = "" , quote = "'" ; if ( error ) { if ( message ) { prepend = quoteInput ? empty . concat ( quote , message , quote ) : message ; } // Force Error instance, coerce given error to a string error = error instanceof Error ? error : new Error ( empty + error ) ; // If message supplied, prepend it error . message = prepend ? empty . concat ( prepend , ": " , error . message ) : error . message ; result = error ; } return result ; }


Input: Simple response checker for remote files . Expected use in robots . txt or sitemap . xml only . [CODESPLIT] function ( res , mediaTypes ) { var contentTypeOk , result = "status: '" + res . statusCode + "', GET failed." ; mediaTypes = ! Array . isArray ( mediaTypes ) ? [ mediaTypes ] : mediaTypes ; if ( res . statusCode === 200 ) { // if content-type exists, and media type found then contentTypeOk contentTypeOk = res . headers [ "content-type" ] && // empty array and none found return true ! mediaTypes . every ( function ( mediaType ) { // flip -1 to 0 and NOT, so that true == NOT found, found stops loop w/false return ! ~ res . headers [ "content-type" ] . indexOf ( mediaType ) ; } ) ; result = contentTypeOk ? "" : "content-type not one of '" + mediaTypes . join ( "," ) + "'" ; } return result ; }


Input:
Utility to promisify a Node function [CODESPLIT] function nodeCall ( nodeFunc /* args... */ ) { var nodeArgs = Array . prototype . slice . call ( arguments , 1 ) ; return new Promise ( function ( resolve , reject ) { /**
     * Resolve a node callback
     */ function nodeResolver ( err , value ) { if ( err ) { reject ( err ) ; } else { resolve ( value ) ; } } nodeArgs . push ( nodeResolver ) ; nodeFunc . apply ( nodeFunc , nodeArgs ) ; } ) ; }


Input: Make sure path exists so a sitemap write can succeed . [CODESPLIT] function prepareWrite ( outputPath , callback ) { var path = pathLib . parse ( outputPath ) ; var dir = pathLib . join ( path . root , path . dir ) ; mkdirp ( dir , callback ) ; }


Input: Parse a sitemap generate input and optionally update the local file for sitemapPolicy purposes . This writes the sitemap files out EVEN IF sitemapPolicy is false . The thinking is that it s better / cheaper to do this b / c if sitemapPolicy is enabled later then there is something to compare against for more savings . [CODESPLIT] function processSitemap ( options , document , callback ) { smLib . parse ( options , document , function ( err ) { var sitemapIndexOpts = options . __sitemapIndex ; var outputPath = base . outputFile ( sitemapIndexOpts , options . source ) ; if ( ! err && sitemapIndexOpts . sitemapOutputDir ) { prepareWrite ( outputPath , function ( err ) { if ( ! err ) { fs . writeFile ( outputPath , document , callback ) ; } else { callback ( common . prependMsgToErr ( err , outputPath , true ) ) ; } } ) ; } else { callback ( err ) ; } } ) ; }


Input: Parse a sitemap index document For each qualifying sitemap element download parse the sitemap . Stops processing if an error occurs . [CODESPLIT] function parse ( options , document , callback ) { xml2js . parseString ( document , { trim : true , normalizeTags : true , normalize : true } , function ( err , result ) { var sitemapUrls = [ ] ; var sitemapIndexOptions = Object . assign ( { } , options , { outputPath : undefined } ) ; if ( ! err ) { // Check if we should process each sitemap in the index. _ . forEach ( // if the sitemap index is malformed, just blow up result . sitemapindex . sitemap , function ( sitemapNode ) { // optionally ignore current sitemaps by sitemap policy var shouldProcess = ! options . sitemapPolicy || ! smLib . stillCurrent ( sitemapNode , sitemapIndexOptions ) ; if ( shouldProcess ) { // if sitemap index is malformed, just blow up sitemapUrls . push ( sitemapNode . loc [ 0 ] ) ; } } ) ; // Edge case message for clarity if ( sitemapUrls . length === 0 ) { console . log ( "[*] No sitemaps qualified for processing" ) ; } // Get all the sitemaps, parse them, and generate input for each Promise . all ( sitemapUrls . map ( function ( sitemapUrl ) { var sitemapOptions = Object . assign ( { } , options , { source : sitemapUrl , input : "sitemap" , sitemapOutputDir : false , __sitemapIndex : sitemapIndexOptions } ) ; console . log ( "[+] Loading the sitemap: '" + sitemapUrl + "'" ) ; return nodeCall ( smLib . getUrl , sitemapOptions , processSitemap ) ; } ) ) . then ( function ( ) { // Ignore the array of results to this function callback ( ) ; } ) . catch ( callback ) ; } else { callback ( err ) ; } } ) ; }


Input: generateInput [CODESPLIT] function generateInput ( options ) { return nodeCall ( common . isUrl ( options . source ) ? smLib . getUrl : smLib . getFile , options , parse ) . catch ( function ( err ) { options . _abort ( err ) ; } ) . then ( function ( ) { base . EOI ( sitemapIndex ) ; } ) ; }


Input: Generate the input arguments for snapshots from a robots . txt file . Each input argument generated calls the listener passing the input object . [CODESPLIT] function ( options , listener ) { var opts = Object . assign ( { } , base . defaults ( defaults ) , options ) ; return base . run ( opts , generateInput , listener ) ; }


Input: Generate the snapshot arguments from a line oriented text file . Each line contains a single url we need a snapshot for . [CODESPLIT] function generateInput ( options ) { return nodeCall ( fs . readFile , options . source ) . catch ( function ( err ) { options . _abort ( err ) ; } ) . then ( function ( data ) { var error ; if ( data ) { data . toString ( ) . split ( '\n' ) . every ( function ( line ) { var page = line . replace ( / ^\s+|\s+$ / g , "" ) ; if ( ! base . input ( options , page ) ) { error = common . prependMsgToErr ( base . generatorError ( ) , page , true ) ; return false ; } return true ; } ) ; if ( error ) { console . error ( error ) ; options . _abort ( error ) ; } } base . EOI ( textfile ) ; } ) ; }


Input: Generate the snapshot arguments from an array of pages . Stops processing if one fails . [CODESPLIT] function generateInput ( options ) { var result = new Promise ( function ( resolve , reject ) { var all ; if ( Array . isArray ( options . source ) ) { all = options . source . every ( function ( sourceUrl ) { var url = urlm . parse ( sourceUrl ) ; var opts = Object . assign ( { } , options , { protocol : url . protocol , auth : url . auth , hostname : url . hostname , port : url . port } ) ; if ( ! base . input ( opts , sourceUrl ) ) { reject ( common . prependMsgToErr ( base . generatorError ( ) , sourceUrl , true ) ) ; return false ; } return true ; } ) ; if ( all ) { resolve ( ) ; } } else { reject ( new Error ( "options.source must be an array" ) ) ; } } ) ; return result . catch ( function ( error ) { options . _abort ( error ) ; } ) . then ( function ( ) { base . EOI ( array ) ; } ) ; }