Input: Build a Redux compatible wrapper around a Feathers service . [CODESPLIT] function reduxifyService ( app , route ) { var _handleActions ; var name = arguments . length > 2 && arguments [ 2 ] !== undefined ? arguments [ 2 ] : route ; var options = arguments . length > 3 && arguments [ 3 ] !== undefined ? arguments [ 3 ] : { } ; var debug = ( 0 , _debug2 . default ) ( 'reducer:' + name ) ; debug ( 'route ' + route ) ; var defaults = { isError : 'isError' , isLoading : 'isLoading' , isSaving : 'isSaving' , isFinished : 'isFinished' , data : 'data' , queryResult : 'queryResult' , store : 'store' , PENDING : 'PENDING' , FULFILLED : 'FULFILLED' , REJECTED : 'REJECTED' } ; var opts = Object . assign ( { } , defaults , options ) ; var SERVICE_NAME = 'SERVICES_' + name . toUpperCase ( ) + '_' ; var service = app . service ( route ) ; if ( ! service ) { debug ( 'redux: Feathers service \'' + route + ' does not exist.' ) ; throw Error ( 'Feathers service \'' + route + ' does not exist.' ) ; } var reducerForServiceMethod = function reducerForServiceMethod ( actionType , ifLoading , isFind ) { var _ref ; return _ref = { } , _defineProperty ( _ref , actionType + '_' + opts . PENDING , function undefined ( state , action ) { var _extends2 ; debug ( 'redux:' + actionType + '_' + opts . PENDING , action ) ; return _extends ( { } , state , ( _extends2 = { } , _defineProperty ( _extends2 , opts . isError , null ) , _defineProperty ( _extends2 , opts . isLoading , ifLoading ) , _defineProperty ( _extends2 , opts . isSaving , ! ifLoading ) , _defineProperty ( _extends2 , opts . isFinished , false ) , _defineProperty ( _extends2 , opts . data , null ) , _defineProperty ( _extends2 , opts . queryResult , state [ opts . queryResult ] || null ) , _extends2 ) ) ; } ) , _defineProperty ( _ref , actionType + '_' + opts . FULFILLED , function undefined ( state , action ) { var _extends3 ; debug ( 'redux:' + actionType + '_' + opts . FULFILLED , action ) ; return _extends ( { } , state , ( _extends3 = { } , _defineProperty ( _extends3 , opts . isError , null ) , _defineProperty ( _extends3 , opts . isLoading , false ) , _defineProperty ( _extends3 , opts . isSaving , false ) , _defineProperty ( _extends3 , opts . isFinished , true ) , _defineProperty ( _extends3 , opts . data , ! isFind ? action . payload : null ) , _defineProperty ( _extends3 , opts . queryResult , isFind ? action . payload : state [ opts . queryResult ] || null ) , _extends3 ) ) ; } ) , _defineProperty ( _ref , actionType + '_' + opts . REJECTED , function undefined ( state , action ) { var _extends4 ; debug ( 'redux:' + actionType + '_' + opts . REJECTED , action ) ; return _extends ( { } , state , ( _extends4 = { } , _defineProperty ( _extends4 , opts . isError , action . payload ) , _defineProperty ( _extends4 , opts . isLoading , false ) , _defineProperty ( _extends4 , opts . isSaving , false ) , _defineProperty ( _extends4 , opts . isFinished , true ) , _defineProperty ( _extends4 , opts . data , null ) , _defineProperty ( _extends4 , opts . queryResult , isFind ? null : state [ opts . queryResult ] || null ) , _extends4 ) ) ; } ) , _ref ; } ; // ACTION TYPES var FIND = SERVICE_NAME + 'FIND' ; var GET = SERVICE_NAME + 'GET' ; var CREATE = SERVICE_NAME + 'CREATE' ; var UPDATE = SERVICE_NAME + 'UPDATE' ; var PATCH = SERVICE_NAME + 'PATCH' ; var REMOVE = SERVICE_NAME + 'REMOVE' ; var RESET = SERVICE_NAME + 'RESET' ; var STORE = SERVICE_NAME + 'STORE' ; return { // ACTION CREATORS // Note: action.payload in reducer will have the value of .data below find : ( 0 , _reduxActions . createAction ) ( FIND , function ( p ) { return { promise : service . find ( p ) , data : undefined } ; } ) , get : ( 0 , _reduxActions . createAction ) ( GET , function ( id , p ) { return { promise : service . get ( id , p ) } ; } ) , create : ( 0 , _reduxActions . createAction ) ( CREATE , function ( d , p ) { return { promise : service . create ( d , p ) } ; } ) , update : ( 0 , _reduxActions . createAction ) ( UPDATE , function ( id , d , p ) { return { promise : service . update ( id , d , p ) } ; } ) , patch : ( 0 , _reduxActions . createAction ) ( PATCH , function ( id , d , p ) { return { promise : service . patch ( id , d , p ) } ; } ) , remove : ( 0 , _reduxActions . createAction ) ( REMOVE , function ( id , p ) { return { promise : service . remove ( id , p ) } ; } ) , reset : ( 0 , _reduxActions . createAction ) ( RESET ) , store : ( 0 , _reduxActions . createAction ) ( STORE , function ( store ) { return store ; } ) , on : function on ( event , data , fcn ) { return function ( dispatch , getState ) { fcn ( event , data , dispatch , getState ) ; } ; } , // REDUCER reducer : ( 0 , _reduxActions . handleActions ) ( Object . assign ( { } , reducerForServiceMethod ( FIND , true , true ) , reducerForServiceMethod ( GET , true ) , reducerForServiceMethod ( CREATE , false ) , reducerForServiceMethod ( UPDATE , false ) , reducerForServiceMethod ( PATCH , false ) , reducerForServiceMethod ( REMOVE , false ) , // reset status if no promise is pending _defineProperty ( { } , RESET , function ( state , action ) { var _extends5 ; debug ( 'redux:' + RESET , action ) ; if ( state [ opts . isLoading ] || state [ opts . isSaving ] ) { return state ; } return _extends ( { } , state , ( _extends5 = { } , _defineProperty ( _extends5 , opts . isError , null ) , _defineProperty ( _extends5 , opts . isLoading , false ) , _defineProperty ( _extends5 , opts . isSaving , false ) , _defineProperty ( _extends5 , opts . isFinished , false ) , _defineProperty ( _extends5 , opts . data , null ) , _defineProperty ( _extends5 , opts . queryResult , action . payload ? state [ opts . queryResult ] : null ) , _defineProperty ( _extends5 , opts . store , null ) , _extends5 ) ) ; } ) , // update store _defineProperty ( { } , STORE , function ( state , action ) { debug ( 'redux:' + STORE , action ) ; return _extends ( { } , state , _defineProperty ( { } , opts . store , action . payload ) ) ; } ) ) , ( _handleActions = { } , _defineProperty ( _handleActions , opts . isError , null ) , _defineProperty ( _handleActions , opts . isLoading , false ) , _defineProperty ( _handleActions , opts . isSaving , false ) , _defineProperty ( _handleActions , opts . isFinished , false ) , _defineProperty ( _handleActions , opts . data , null ) , _defineProperty ( _handleActions , opts . queryResult , null ) , _defineProperty ( _handleActions , opts . store , null ) , _handleActions ) ) } ; }


Input: Compiles down an example . Async examples call an imaginary done function once they re done . [CODESPLIT] function getExampleCode ( comment ) { var expectedResult = comment . expectedResult ; var isAsync = comment . isAsync ; var testCase = comment . testCase ; if ( isAsync ) { return '\nfunction cb(err, result) {' + 'if(err) return done(err);' + 'result.should.eql(' + expectedResult + ');' + 'done();' + '}\n' + 'var returnValue = ' + testCase + ';' + 'if(returnValue && returnValue.then && typeof returnValue.then === \'function\') {' + 'returnValue.then(cb.bind(null, null), cb);' + '}' ; } else { return '(' + testCase + ').should.eql(' + expectedResult + ');' ; } }


Input: HMAC - based Extract - and - Expand Key Derivation Function ( HKDF ) [CODESPLIT] function hkdf ( ikm , length , { salt = '' , info = '' , hash = 'SHA-256' } = { } ) { hash = hash . toLowerCase ( ) . replace ( '-' , '' ) ; // 0. Hash length const hash_len = hash_length ( hash ) ; // 1. extract const prk = hkdf_extract ( hash , hash_len , ikm , salt ) ; // 2. expand return hkdf_expand ( hash , hash_len , prk , length , info ) ; }


Input: A simple wrapper around node s http ( s ) request . [CODESPLIT] function request ( method , path , body , callback ) { var stream ; // Body is optional if ( typeof body === 'function' && typeof callback === 'undefined' ) { callback = body ; body = undefined ; } // Return a stream if no callback is specified if ( ! callback ) { stream = new EventEmitter ( ) ; stream . setEncoding = function ( ) { throw new Error ( "This stream is always utf8" ) ; } ; } function errorHandler ( err ) { if ( callback ) { callback ( err ) ; } if ( stream ) { stream . emit ( 'error' , err ) ; } } var headers = { "Host" : uri . host } ; // add the authorization header if provided and using https if ( uri . auth ) { headers [ "Authorization" ] = "Basic " + new Buffer ( uri . auth , "ascii" ) . toString ( "base64" ) ; } if ( body ) { body = JSON . stringify ( body ) ; headers [ "Content-Length" ] = Buffer . byteLength ( body ) ; headers [ "Content-Type" ] = "application/json" ; } var options = { host : uri . hostname , method : method , path : path , port : uri . port , headers : headers } ; var request = uri . protocolHandler . request ( options , function ( response ) { response . setEncoding ( 'utf8' ) ; var body = "" ; response . on ( 'data' , function ( chunk ) { if ( callback ) { body += chunk ; } if ( stream ) { stream . emit ( 'data' , chunk ) ; } } ) ; response . on ( 'end' , function ( ) { if ( callback ) { try { var parsedBody = JSON . parse ( body ) ; callback ( null , parsedBody ) ; } catch ( err ) { callback ( err ) ; } } if ( stream ) { stream . emit ( 'end' ) ; } } ) ; response . on ( 'error' , errorHandler ) ; } ) ; request . on ( 'error' , errorHandler ) ; if ( body ) { request . write ( body , 'utf8' ) ; } request . end ( ) ; return stream ; }


Input: Class to implement inner working of plugin . [CODESPLIT] function ( options ) { "use strict" ; if ( ( options . setter && options . setter . indexOf ( '.' ) > - 1 ) || ( options . getter && options . getter . indexOf ( '.' ) > - 1 ) ) { throw new Error ( 'Getter (' + options . getter + ') and setter (' + options . setter + ') methods cannot be nested, so they cannot contain dot(.)' ) ; } this . options = Joi . attempt ( options , optionsSchema ) ; this . locales = this . getAvailableLocales ( ) ; this . default = this . options . default || this . locales [ 0 ] ; //this.callback   = this.getCallback(this.options.callback); }


Input: Checks synchroniously if given file or directory exists . Returns true or false . [CODESPLIT] function fileExists ( path , shouldBeDir ) { "use strict" ; try { var lstat = fs . lstatSync ( path ) ; if ( shouldBeDir && lstat . isDirectory ( ) ) { return true ; } if ( ! shouldBeDir && lstat . isFile ( ) ) { return true ; } } catch ( err ) { return false ; } return false ; }


Input:
Hapi plugin function which adds i18n support to request and response objects . [CODESPLIT] async function ( server , options ) { try { var internal = new Internal ( options ) ; } catch ( err ) { throw new Boom ( err ) ; } /**
         * @module exposed
         * @description
         * Exposed functions and attributes are listed under exposed name.
         * To access those attributes `request.server.plugins['hapi-locale']` can be used.
         * @example
         * var locales = request.server.plugins['hapi-locale'].getLocales(); // ['tr_TR', 'en_US'] etc.
         */ /**
         * Returns all available locales as an array.
         * @name getLocales
         * @function
         * @returns {Array.<string>}    - Array of locales.
         * @example
         * var locales = request.server.plugins['hapi-locale'].getLocales(); // ['tr_TR', 'en_US'] etc.
         */ server . expose ( 'getLocales' , function getLocales ( ) { return internal . locales ; } ) ; /**
         * Returns default locale.
         * @name getDefaultLocale
         * @function
         * @returns {string}    - Default locale
         */ server . expose ( 'getDefaultLocale' , function getDefaultLocale ( ) { return internal . default ; } ) ; /**
         * Returns requested language.
         * @name getLocale
         * @function
         * @param {Object}      request - Hapi.js request object
         * @returns {string}    Locale
         */ server . expose ( 'getLocale' , function getLocale ( request ) { try { return lodash . get ( request , internal . options . getter ) ( ) ; } catch ( err ) { return null ; } } ) ; server . ext ( internal . options . onEvent , internal . processRequest , { bind : internal } ) ; }


Input: build a dependency tree from the flat mdeps list by recursing [CODESPLIT] function ( currDeps , loc ) { loc . deps = loc . deps || [ ] ; var covered = [ ] ; // only cover unique paths once to avoid stack overflow currDeps . forEach ( function ( obj ) { if ( covered . indexOf ( obj . path ) < 0 ) { covered . push ( obj . path ) ; // cover unique paths only once per level var key = obj . name , isRelative = ( [ '\\' , '/' , '.' ] . indexOf ( key [ 0 ] ) >= 0 ) , notCovered = notCoveredInArray ( loc . deps , key ) , isRecorded = ( ! isRelative || opts . showLocal ) && notCovered , res = isRecorded ? { name : key } : loc ; if ( isRecorded ) { // NB: !isRecorded => only inspect the file for recorded deps res . path = obj . path ; loc . deps . push ( res ) ; } // recurse (!isRecorded => keep adding to previous location) traverse ( lookup [ obj . path ] || [ ] , res ) ; } } ) ; }


Input: given a modules array with cycles - trim dependencies in each cycle [CODESPLIT] function ( ms , cycles ) { var removed = { } ; cycles . forEach ( function ( c ) { var last = c [ c . length - 1 ] ; // last id in cycle //console.log('will try to trim from', last, ms[last]); // need to find a dependency in the cycle var depsInCycle = ms [ last ] . filter ( function ( deps ) { return deps . path && c . indexOf ( deps . path ) >= 0 ; } ) ; if ( ! depsInCycle . length ) { throw new Error ( "logic fail2" ) ; // last thing in a cycle should have deps } var depToRemove = depsInCycle [ 0 ] . path ; //console.log('deps in cycle', depsInCycle); for ( var i = 0 ; i < ms [ last ] . length ; i += 1 ) { var dep = ms [ last ] [ i ] ; if ( dep . path && dep . path === depToRemove ) { //console.log('removing', depToRemove); removed [ last ] = dep . name ; ms [ last ] . splice ( i , 1 ) ; } } //console.log('after remove', ms[last]); } ) ; return removed ; }


Input: @module @lobsangnet / lobsang - formatter - matrix / schema Library to get a schema for the given topic . [CODESPLIT] function schema ( topic ) { if ( topic === constants . LOBSANG_CONTENT_TOPIC ) { return wrapper . fetch ( constants . LOBSANG_CONTENT_SCHEMA_URL ) } return Promise . reject ( new Error ( 'Topic is not supported' ) ) }


Input: Create a times series that you can report to . [CODESPLIT] function ( options ) { // Validate options assert ( options , "options are required" ) ; assert ( options . name , "Series must be named" ) ; options = _ . defaults ( { } , options , { columns : { } , additionalColumns : null } ) ; // Store options this . _options = options ; }


Input: define the action [CODESPLIT] function whenRead ( args ) { let value = getValue ( args ) if ( value && typeof value . then === 'function' ) { value . then ( ( val ) => whenTest ( args , val ) ) . catch ( ( error ) => { console . error ( ` ${ action . displayName } ` , error ) } ) } else { whenTest ( args , value ) } }


Input:
Is value an * AsyncFunction * [CODESPLIT] function isAsyncFunction ( value ) { if ( ! value ) return false ; const afcText = value . toString ( ) . toLocaleLowerCase ( ) . replace ( / \n / g , '' ) . replace ( /   / g , '' ) ; return _testConstructor ( 'AsyncFunction' , value ) || ( ( _testConstructor ( 'Function' , value ) && ( afcText . slice ( afcText . indexOf ( '{' ) ) . indexOf ( 'returnnewpromise(function($return,$error)' ) === 1 ) ) ) ; //fast-async monkey-support
 }


Input: Is value iterable ( * object * or * Array * with not zero length ) [CODESPLIT] function isIterable ( value ) { return ( isObject ( value ) ? ! ! Object . keys ( value ) . length : false ) || ( isArray ( value ) ? ! ! value . length : false ) ; }


Input: Is value a JSON and can be decoded as * object * [CODESPLIT] function isJSON ( value ) { if ( ! isString ( value ) ) return false ; try { const obj = JSON . parse ( value ) ; return ! ! obj && typeof obj === 'object' ; } catch ( e ) { } return false ; }


Input: [[ include : TAnyArray - to - object . md ]] [CODESPLIT] function arrayToObject ( value , toKeys ) { return ( iterate ( value , ( row , idx , iter ) => { if ( toKeys ) { if ( isInteger ( row ) || isString ( row ) ) iter . key ( idx + 1 ) ; return row ; } else { iter . key ( row ) ; return idx + 1 ; } } , { } ) ) ; }


Input: [[ include : object - to - TAnyArray . md ]] [CODESPLIT] function objectToArray ( value , toKeys ) { return iterate ( value , ( val , key ) => toKeys ? key : val , [ ] ) ; }


Input: [[ include : set - defaults . md ]] [CODESPLIT] function setDefaults ( obj , name , value ) { if ( isUndefined ( obj [ name ] ) ) { obj [ name ] = value ; } return obj ; }


Input: [[ include : iterate . md ]] [CODESPLIT] function iterate ( value , callback , accumulate , assign ) { let breakFlag = false ; function newIteration ( index ) { let instance = { 'break' : ( ) => breakFlag = true , accKeyName : index , key : ( name ) => instance . accKeyName = name } ; return instance ; } let iterateInstanceAsync = async ( callback , val , index ) => { let iteration = newIteration ( index ) ; pushRet ( await callback ( val , index , iteration ) , iteration ) ; } ; let iterateInstance = ( callback , val , index ) => { let iteration = newIteration ( index ) ; pushRet ( callback ( val , index , iteration ) , iteration ) ; } ; let ret = isObject ( accumulate ) ? accumulate : isArray ( accumulate ) ? accumulate : accumulate === true ? false : value ; let pushRet = ( val , iteration ) => { if ( isUndefined ( val ) ) return ; if ( isObject ( accumulate ) ) { ret [ iteration . accKeyName ] = assign ? Object . assign ( ret [ iteration . accKeyName ] || { } , val ) : val ; } if ( isArray ( accumulate ) ) ret . push ( val ) ; if ( accumulate === true ) ret = ret || val ; } ; return isAsyncFunction ( callback ) ? new Promise ( async ( resolve ) => { if ( isArray ( value ) ) { for ( let index = 0 ; index < value . length ; ++ index ) { if ( breakFlag ) break ; await iterateInstanceAsync ( callback , value [ index ] , index ) ; } resolve ( ret ) ; } if ( isObject ( value ) ) { await iterate ( Object . keys ( value ) , async ( index , _ , iteration ) => { if ( breakFlag ) iteration . break ( ) ; await iterateInstanceAsync ( callback , value [ index ] , index ) ; } ) ; resolve ( ret ) ; } if ( isInteger ( value ) ) { for ( let index = 0 ; index < value ; ++ index ) { if ( breakFlag ) break ; await iterateInstanceAsync ( callback , index , index ) ; } resolve ( ret ) ; } resolve ( false ) ; } ) : ( ( ) => { if ( isArray ( value ) ) { for ( let index = 0 ; index < value . length ; ++ index ) { if ( breakFlag ) break ; iterateInstance ( callback , value [ index ] , index ) ; } return ret ; } if ( isObject ( value ) ) { iterate ( Object . keys ( value ) , ( index , _ , iteration ) => { if ( breakFlag ) iteration . break ( ) ; iterateInstance ( callback , value [ index ] , index ) ; } ) ; return ret ; } if ( isInteger ( value ) ) { for ( let index = 0 ; index < value ; ++ index ) { if ( breakFlag ) break ; iterateInstance ( callback , index , index ) ; } return ret ; } return false ; } ) ( ) ; }


Input: [[ include : iterate - keys . md ]] [CODESPLIT] function iterateKeys ( value , callback , accumulate ) { return isAsyncFunction ( callback ) ? ( async ( ) => await iterate ( value , async ( row , key , iteration ) => await callback ( key , row , iteration ) , accumulate ) ) ( ) : iterate ( value , ( row , key , iteration ) => callback ( key , row , iteration ) , accumulate ) ; }


Input: [[ include : iterate - parallel . md ]] [CODESPLIT] async function iterateParallel ( value , callback ) { return Promise . all ( iterate ( value , ( val , key , iter ) => ( async ( ) => await callback ( val , key , iter ) ) ( ) , [ ] ) ) ; }


Input: Finds and deletes first encounter of value in target [CODESPLIT] function findAndDelete ( target , value ) { if ( ! isIterable ( target ) ) return false ; if ( isArray ( target ) ) { for ( let i = 0 ; i < target . length ; i ++ ) { if ( deep_equal_1 . default ( target [ i ] , value ) ) { target . splice ( i , 1 ) ; return true ; } } } else if ( isObject ( target ) ) { const keys = Object . keys ( target ) ; for ( let i = 0 ; i < keys . length ; i ++ ) { if ( deep_equal_1 . default ( target [ keys [ i ] ] , value ) ) { delete target [ keys [ i ] ] ; return true ; } } } return false ; }


Input: Finds and deletes all encounters of value in target [CODESPLIT] function findAndDeleteAll ( target , value ) { let flag = false ; while ( findAndDelete ( target , value ) ) { flag = true ; } return flag ; }


Input: AppSrv Logic [CODESPLIT] function SignAgreement ( data ) { var d = { 'a_name' : data . a_name , 'a_dob' : data . a_dob } ; XForm . prototype . XExecutePost ( '../agreement/_sign' , d , function ( rslt ) { if ( '_success' in rslt ) { window . location . href = jsh . _BASEURL + 'agreement/welcome/' ; } } ) ; }


Input: TODO : remove [CODESPLIT] function start ( instance ) { console . log ( 'start called!' ) ; var chatClient = instance ( ) , // If messages are going to a specific user, store that here. activeBuddylistEntry , buddylist , input ; document . getElementById ( 'msg-input' ) . focus ( ) ; function clearLog ( ) { var log = document . getElementById ( 'messagelist' ) ; log . innerHTML = "" ; } function appendLog ( elt ) { var log = document . getElementById ( 'messagelist' ) , br ; //Trim old messages while ( log . childNodes . length > 36 ) { log . removeChild ( log . firstChild ) ; } log . appendChild ( elt ) ; br = document . createElement ( 'br' ) ; log . appendChild ( br ) ; br . scrollIntoView ( ) ; } function makeDisplayString ( buddylistEntry ) { return buddylistEntry . name && buddylistEntry . name !== buddylistEntry . clientId ? buddylistEntry . name + ' (' + buddylistEntry . clientId + ')' : buddylistEntry . clientId ; } function redrawBuddylist ( ) { var onClick = function ( buddylistEntry , child ) { console . log ( "Messages will be sent to: " + buddylistEntry . clientId ) ; activeBuddylistEntry = buddylistEntry ; redrawBuddylist ( ) ; document . getElementById ( 'msg-input' ) . focus ( ) ; } , buddylistDiv = document . getElementById ( 'buddylist' ) , clientId , child ; // Remove all elements in there now buddylistDiv . innerHTML = "<b>Buddylist</b>" ; // Create a new element for each buddy for ( clientId in buddylist ) { if ( buddylist . hasOwnProperty ( clientId ) ) { child = document . createElement ( 'div' ) ; if ( activeBuddylistEntry === buddylist [ clientId ] ) { child . innerHTML = "[" + makeDisplayString ( buddylist [ clientId ] ) + "]" ; } else { child . innerHTML = makeDisplayString ( buddylist [ clientId ] ) ; } // If the user clicks on a buddy, change our current destination for messages child . addEventListener ( 'click' , onClick . bind ( this , buddylist [ clientId ] , child ) , true ) ; buddylistDiv . appendChild ( child ) ; } } } // on changes to the buddylist, redraw entire buddylist chatClient . on ( 'recv-buddylist' , function ( val ) { buddylist = val ; theBuddylist = buddylist ; console . log ( 'got buddylist' , buddylist ) ; redrawBuddylist ( ) ; } ) ; // On new messages, append it to our message log chatClient . on ( 'recv-message' , function ( data ) { // Show the name instead of the clientId, if it's available. var clientId = data . from . clientId , displayName = buddylist [ clientId ] . name || clientId , message = displayName + ": " + data . message ; appendLog ( document . createTextNode ( message ) ) ; } ) ; // On new messages, append it to our message log chatClient . on ( 'recv-err' , function ( data ) { document . getElementById ( 'uid' ) . textContent = "Error: " + data . message ; } ) ; // Display our own clientId when we get it chatClient . on ( 'recv-uid' , function ( data ) { document . getElementById ( 'uid' ) . textContent = "Logged in as: " + data ; } ) ; // Display the current status of our connection to the Social provider chatClient . on ( 'recv-status' , function ( msg ) { if ( msg && msg === 'online' ) { document . getElementById ( 'msg-input' ) . disabled = false ; } else { document . getElementById ( 'msg-input' ) . disabled = true ; } clearLog ( ) ; var elt = document . createElement ( 'b' ) ; elt . appendChild ( document . createTextNode ( 'Status: ' + msg ) ) ; appendLog ( elt ) ; } ) ; // Listen for the enter key and send messages on return input = document . getElementById ( 'msg-input' ) ; input . onkeydown = function ( evt ) { if ( evt . keyCode === 13 ) { var text = input . value ; input . value = "" ; appendLog ( document . createTextNode ( "You: " + text ) ) ; chatClient . send ( activeBuddylistEntry . clientId , text ) ; } } ; // Just call boot when login is clicked console . log ( 'connecting login!' ) ; var loginButton = document . getElementById ( 'uid' ) ; console . log ( 'loginButton: ' + loginButton ) ; loginButton . addEventListener ( 'click' , function ( ) { console . log ( 'login clicked' ) ; chatClient . login ( ) ; } ) ; }


Input: @module @lobsangnet / lobsang - connect - matrix / connect Connects to a MatrixClient and resolves once connection was established . [CODESPLIT] function connect ( client ) { client . startClient ( ) return new Promise ( ( resolve , reject ) => { client . once ( 'sync' , ( state ) => { if ( wrapper . isSyncState ( state ) ) { return resolve ( client ) } else { return reject ( new Error ( 'Client could not sync' ) ) } } ) } ) }


Input: @module @lobsangnet / lobsang - processor - hostname Library to process the hostname from an URL . [CODESPLIT] function lobsangProcessorHostname ( link ) { let parts try { parts = parseUrl ( link ) } catch ( error ) { return Promise . reject ( error ) } if ( parts . hostname === '' ) { return Promise . reject ( new Error ( 'Not an URL' ) ) } return Promise . resolve ( parts . hostname ) }


Input: Add a frame around strings . [CODESPLIT] function frameOfMind ( string , options = { } ) { const { padding = 1 } = options const l = string . split ( '\n' ) const w = l . reduce ( ( acc , { length } ) => length > acc ? length : acc , 0 ) const ww = w + padding * 2 const bt = ` '─ '.rep e at(ww) } ┐`    const bb = ` '─ '.rep e at(ww) } ┘`    const pp = ' ' . repeat ( padding ) const p = paddys ( string ) . split ( '\n' ) . map ( line => ` pp }$ { li ne}$ { pp }│ `   . join ( '\n' ) return ` ${ bt } \n ${ p } \n ${ bb } ` }


Input: @module @lobsangnet / lobsang - connect - matrix / sync Helper method to check the state against those indicating some sync state . [CODESPLIT] function isSyncState ( state ) { if ( state === CONSTANTS . MATRIX_STATE_PREPARED ) { return true } if ( state === CONSTANTS . MATRIX_STATE_SYNCING ) { return true } return false }


Input: @module @lobsangnet / lobsang - formatter - matrix Library to wrap a message into an object which complies to the given schema . [CODESPLIT] function lobsangFormatterSchema ( message , topic ) { if ( typeof message !== 'string' ) { return Promise . reject ( new Error ( 'Message is not a string' ) ) } return schema ( topic ) . then ( ( schemaObject ) => { const validator = validate ( schemaObject ) const schemaMessage = format ( message ) if ( validator ( schemaMessage ) ) { return Promise . resolve ( schemaMessage ) } return Promise . reject ( validator . errors ) } ) }


Input: ************************************************************************************************* [CODESPLIT] function _resolve ( path , options , mod ) { if ( path ) { var i = path . indexOf ( ':' ) if ( i === - 1 ) { return resolveModule ( path , options , mod ) } else { var namespace = path . substring ( 0 , i ) var p = path . substring ( i + 1 ) if ( namespace === "env" ) { return resolveEnv ( p , options , mod ) } else if ( namespace === "http" || namespace === "https" ) { return resolveHttp ( path , options , mod ) } else if ( namespace === "file" ) { return resolveFile ( p , options , mod ) } else { throw new Error ( "Unable to resolve path: '" + path + "'. Unknown namespace: " + namespace ) } } } }


Input: ************************************************************************************************* [CODESPLIT] function resolveEnv ( path , options , mod ) { var result = undefined if ( path ) { result = ( process [ PRIVATE_ENV ] && process [ PRIVATE_ENV ] [ path ] ) || process . env [ path ] } return result }


Input: ************************************************************************************************* [CODESPLIT] function resolveModule ( path , options , mod ) { // XXX this is ineffecient. must cache var result = null var filepath = resolveFilename ( path , mod ) try { result = mod . require ( filepath ) } catch ( e ) { var error = undefined if ( e instanceof errors . ResolveModuleSyntaxError ) { error = e } else if ( e instanceof SyntaxError ) { error = new errors . ResolveModuleSyntaxError ( e , filepath ) } else { error = new Error ( "Error loading module: " + filepath + " " + e . stack ) } throw error } return result }


Input: ************************************************************************************************* [CODESPLIT] function resolveFilename ( path , mod ) { var result = null ; if ( path ) { try { return Module . _resolveFilename ( path , mod ) // TODO: is this what we want? } catch ( e ) { // XXX really slows this down if ( path && path . length > 1 && path [ 0 ] != '/' ) { pathlist = path . split ( '/' ) if ( pathlist . length > 1 ) { if ( pathlist . indexOf ( "lib" ) == - 1 ) { pathlist . splice ( 1 , 0 , "lib" ) var newpath = pathlist . join ( '/' ) result = Module . _resolveFilename ( newpath , mod ) return result } } } throw ( e ) } } return result }


Input:
************************************************************************************************* [CODESPLIT] function resolveFile ( path , options , mod ) { if ( path ) { var f = Object ( ) Object . defineProperties ( f , { readStream : { enumerable : true , configurable : false , writeable : false , get : function ( ) { return fs . createReadStream ( path ) } } , writeStream : { enumerable : true , configurable : false , writeable : false , get : function ( ) { return fs . createWriteStream ( path , { flags : "a" } ) } } , content : { enumerable : true , configurable : false , writeable : false , get : function ( ) { return fs . readFile . sync ( path ) . toString ( ) } } } ) f . toString = function ( ) { return this . content } /* open(flags[, mode][, callback])
     */ f . open = function ( ) { if ( ! arguments || arguments . length < 1 ) { throw ( Error ( "flags argument is required" ) ) } var flags = arguments [ 0 ] var mode = null var cb = null if ( arguments . length > 2 ) { mode = arguments [ 1 ] cb = arguments [ 2 ] } else if ( arguments . length > 1 ) { if ( typeof arguments [ 1 ] === "number" ) { mode = arguments [ 1 ] } else { cb = arguments [ 1 ] } } if ( cb ) { fs . open ( path , flags , mode , cb ) } else { return fs . openSync ( path , flags , mode ) } } return f } else { throw ( Error ( "File not found: " + path ) ) } }


Input: ************************************************************************************************* [CODESPLIT] function _o ( mod ) { if ( ! ( mod instanceof Module ) ) { throw ( Error ( "Must supply a module to _o: " + mod ) ) } return function ( path , options ) { return _resolve ( path , options , mod ) } }


Input: @module @lobsangnet / lobsang - formatter - matrix / validate Derives a validator from a schema . [CODESPLIT] function validate ( schema ) { const ajv = new Ajv ( ) try { const validator = ajv . compile ( schema ) return Promise . resolve ( validator ) } catch ( error ) { return Promise . reject ( error ) } }


Input: Create an Influx Database Connection [CODESPLIT] function ( options ) { assert ( options , "options are required" ) ; assert ( options . connectionString , "options.connectionString is missing" ) ; assert ( url . parse ( options . connectionString ) . protocol === 'https:' || options . allowHTTP , "InfluxDB connectionString must use HTTPS!" ) ; options = _ . defaults ( { } , options , { maxDelay : 60 * 5 , maxPendingPoints : 250 } ) ; this . _options = options ; this . _pendingPoints = { } ; this . _nbPendingPoints = 0 ; this . _flushTimeout = setTimeout ( this . flush . bind ( this , true ) , options . maxDelay * 1000 ) ; }


Input: Create a handler timer for AMQP messages received through taskcluster - client . Please note that this relies on that messages format . [CODESPLIT] function ( handler , options ) { assert ( handler instanceof Function , "A handler must be provided" ) ; assert ( options , "options required" ) ; assert ( options . drain , "options.drain is required" ) ; assert ( options . component , "options.component is required" ) ; // Create a reporter var reporter = series . HandlerReports . reporter ( options . drain ) ; // Wrap handler and let that be it return function ( message ) { // Create most of the point var point = { component : options . component , duration : undefined , exchange : message . exchange || '' , redelivered : ( message . redelivered ? 'true' : 'false' ) , error : 'false' } ; // Start timer var start = process . hrtime ( ) ; // Handle the message return Promise . resolve ( handler ( message ) ) . then ( function ( ) { // Get duration var d = process . hrtime ( start ) ; // Convert to milliseconds point . duration = d [ 0 ] * 1000 + ( d [ 1 ] / 1000000 ) ; // Send point to reporter reporter ( point ) ; } , function ( err ) { // Get duration var d = process . hrtime ( start ) ; // Convert to milliseconds point . duration = d [ 0 ] * 1000 + ( d [ 1 ] / 1000000 ) ; // Flag and error point . error = 'true' ; // Send point to reporter reporter ( point ) ; // Re-throw the error throw err ; } ) ; } ; }


Input: Monitor CPU and memory for this instance . [CODESPLIT] function ( options ) { // Validate options assert ( options , "Options are required" ) ; assert ( options . drain , "A drain for the measurements must be provided!" ) ; assert ( options . component , "A component must be specified" ) ; assert ( options . process , "A process name must be specified" ) ; // Provide default options options = _ . defaults ( { } , options , { interval : 60 } ) ; // Clear reporting if already started if ( _processUsageReportingInterval ) { debug ( "WARNING: startProcessUsageReporting() already started!" ) ; clearInterval ( _processUsageReportingInterval ) ; _processUsageReportingInterval = null ; } // Lazy load the usage monitor module var usage = require ( 'usage' ) ; // Create reporter var reporter = series . UsageReports . reporter ( options . drain ) ; // Set interval to report usage at interval _processUsageReportingInterval = setInterval ( function ( ) { // Lookup usage for the current process usage . lookup ( process . pid , { keepHistory : true } , function ( err , result ) { // Check for error if ( err ) { debug ( "Failed to get usage statistics, err: %s, %j" , err , err , err . stack ) ; return ; } // Report usage reporter ( { component : options . component , process : options . process , cpu : result . cpu , memory : result . memory } ) ; } ) ; } , options . interval * 1000 ) ; }


Input: Create a stats handler for taskcluster - client clients which takes an option stats as function that will be call after an API call . [CODESPLIT] function ( options ) { options = _ . defaults ( { } , options || { } , { tags : { } , drain : undefined } ) ; assert ( options . drain , "options.drain is required" ) ; assert ( typeof options . tags === 'object' , "options.tags is required" ) ; assert ( _ . intersection ( _ . keys ( options . tags ) , series . APIClientCalls . columns ( ) ) . length === 0 , "Can't used reserved tag names!" ) ; // Create a reporter return series . APIClientCalls . reporter ( options . drain , options . tags ) ; }


Input: @module @lobsangnet / lobsang - connect - matrix / check Checks the message on type etc . [CODESPLIT] function check ( message ) { if ( ! message ) { return Promise . reject ( new Error ( 'Argument must not be falsy!' ) ) } if ( typeof message !== 'string' ) { return Promise . reject ( new Error ( 'Argument must be a string!' ) ) } return Promise . resolve ( message ) }


Input: Generate help [CODESPLIT] function generateHelp ( params ) { var output = '' ; if ( params . usage ) { var usage = result ( params , 'usage' ) ; output += EOL ; output += format ( 'Usage: %s' , usage ) ; output += EOL ; } if ( params . desc ) { var desc = result ( params , 'desc' ) ; output += EOL ; output += desc ; output += EOL ; } if ( is . object ( params . options ) && objectLength ( params . options ) > 0 ) { var options = buildOptions ( params . options ) ; output += EOL ; output += 'Options:' ; output += EOL ; output += EOL ; output += indent ( options , ' ' , 2 ) ; output += EOL ; } if ( is . array ( params . commands ) && params . commands . length > 0 ) { var commands = buildCommands ( params . commands ) ; output += EOL ; output += 'Commands:' ; output += EOL ; output += EOL ; output += indent ( commands , ' ' , 2 ) ; output += EOL ; } output += EOL ; return indent ( output , ' ' , 2 ) ; }


Input: Helpers Output option list [CODESPLIT] function buildOptions ( options ) { var result = [ ] ; var keys = Object . keys ( options ) ; keys . forEach ( function ( key ) { var props = options [ key ] ; // convert short to long form if ( is . string ( props ) ) { props = { type : props } ; } // all names of an option // aliases come first // full name comes last var name = [ format ( '--%s' , dasherize ( key ) ) ] ; // accept both string and array var aliases = props . alias || props . aliases || [ ] ; if ( is . not . array ( aliases ) ) { aliases = [ aliases ] ; } // aliases are prefixed with "-" aliases . forEach ( function ( alias ) { alias = format ( '-%s' , alias ) ; name . unshift ( alias ) ; } ) ; result . push ( [ name . join ( ', ' ) , props . desc || '' ] ) ; } ) ; return table ( result ) ; }


Input: Output command list [CODESPLIT] function buildCommands ( commands ) { var result = [ ] ; commands . forEach ( function ( command ) { result . push ( [ command . name , command . desc || '' ] ) ; } ) ; return table ( result ) ; }


Input: ========================================================================== DEFAULT NOTIFICATIONS ========================================================================== [CODESPLIT] function initGrowlStatus ( ) { grunt . util . hooker . hook ( grunt . log , 'write' , function ( msg ) { if ( grunt . log . uncolor ( msg ) . match ( / Waiting... / ) ) { flushMessages ( 'ok' ) ; } } ) ; grunt . util . hooker . hook ( grunt . log , 'header' , function ( msg ) { msg = grunt . log . uncolor ( msg ) ; if ( ignoreWatch && msg . match ( / "watch" task / ) ) { return ; } if ( msg . match ( / ".+:.+" / ) ) { return ; } if ( ! ignoreWatch && msg . match ( / "watch" task / ) ) { msg += ' for ' + path . basename ( process . cwd ( ) ) ; ignoreWatch = true ; } messages . push ( msg ) ; } ) ; grunt . util . hooker . hook ( grunt . log , 'ok' , function ( msg ) { if ( typeof msg === 'string' ) { messages . push ( grunt . log . uncolor ( msg ) ) ; } } ) ; grunt . util . hooker . hook ( grunt , 'warn' , function ( error ) { var warning = [ ] ; if ( typeof error !== 'undefined' ) { warning . push ( messages [ 0 ] ) ; warning . push ( messages [ messages . length - 1 ] ) ; warning . push ( String ( error . message || error ) ) ; messages = warning ; flushMessages ( 'error' ) ; } } ) ; grunt . util . hooker . hook ( grunt . log , 'error' , function ( msg ) { if ( typeof msg === 'string' ) { messages . push ( grunt . log . uncolor ( msg ) ) ; flushMessages ( 'error' ) ; } } ) ; }


Input: @module @lobsangnet / lobsang - formatter - matrix Library to wrap a message into an object which can be sent to matrix . [CODESPLIT] function lobsangFormatterMatrix ( message ) { if ( typeof message !== 'string' ) { return Promise . reject ( new Error ( 'Message is not a string' ) ) } const formattedMessage = { body : message , msgtype : CONSTANTS . MATRIX_NOTICE_TYPE } return Promise . resolve ( formattedMessage ) }


Input: Module main constructor [CODESPLIT] function Router ( options ) { const logPrefix = topLogPrefix + 'Router() - ' ; const that = this ; let defaultRouteFound = false ; that . options = options || { } ; if ( ! that . options . paths ) { that . options . paths = { 'controller' : { 'path' : 'controllers' , 'exts' : 'js' } , 'static' : { 'path' : 'public' , 'exts' : false } , 'template' : { 'path' : 'public/templates' , 'exts' : [ 'tmpl' , 'tmp' , 'ejs' , 'pug' ] } } ; } if ( ! that . options . routes ) that . options . routes = [ ] ; if ( ! that . options . basePath ) that . options . basePath = process . cwd ( ) ; if ( ! that . options . log ) { const lUtils = new LUtils ( ) ; that . options . log = new lUtils . Log ( ) ; } for ( const key of Object . keys ( that . options . paths ) ) { if ( ! Array . isArray ( that . options . paths [ key ] . exts ) && that . options . paths [ key ] . exts !== false ) { that . options . paths [ key ] . exts = [ that . options . paths [ key ] . exts ] ; } } if ( ! that . options . lfs ) { that . options . lfs = new Lfs ( { 'basePath' : that . options . basePath , 'log' : that . options . log } ) ; } for ( let i = 0 ; that . options . routes [ i ] !== undefined ; i ++ ) { if ( that . options . routes [ i ] . regex === '^/$' ) { defaultRouteFound = true ; break ; } } // We should always have a default route, so if none exists, create one if ( defaultRouteFound === false ) { that . options . routes . push ( { 'regex' : '^/$' , 'controllerPath' : 'default.js' , 'templatePath' : 'default.tmpl' } ) ; } for ( const key of Object . keys ( that . options ) ) { that [ key ] = that . options [ key ] ; } that . log . debug ( logPrefix + 'Instantiated with options: ' + JSON . stringify ( that . options ) ) ; }


Input: jsdom window document navigator setup http : // airbnb . io / enzyme / docs / guides / jsdom . html [CODESPLIT] function copyProps ( src , target ) { const props = Object . getOwnPropertyNames ( src ) . filter ( prop => typeof target [ prop ] === 'undefined' ) . reduce ( ( result , prop ) => R . merge ( result , { [ prop ] : Object . getOwnPropertyDescriptor ( src , prop ) } ) , { } ) ; Object . defineProperties ( target , props ) ; }


Input: @module @lobsangnet / lobsang - processor - port Library to process the port from an URL . [CODESPLIT] function lobsangProcessorPort ( link ) { let parts try { parts = parseUrl ( link ) } catch ( error ) { return Promise . reject ( error ) } if ( parts . port === '' ) { return getDefaultPortByProtocol ( parts . protocol ) } // For some reasons, the Promise resolves always to a String (not Number). return Promise . resolve ( String ( parts . port ) ) }


Input: Helper method to look up port by protocol . [CODESPLIT] function getDefaultPortByProtocol ( rawProtocol ) { // port-numbers expect no trailing colon const protocol = rawProtocol . endsWith ( ':' ) ? rawProtocol . slice ( 0 , - 1 ) : rawProtocol // e.g. mailto has no port associated // example return value: // { port: 80, protocol: 'tcp', description: 'World Wide Web HTTP' } const portByProtocol = portNumbers . getPort ( protocol ) return portByProtocol ? Promise . resolve ( String ( portByProtocol . port ) ) : Promise . reject ( new Error ( 'Has no port' ) ) }


Input: Replace scripts with ... and prune empty scripts [CODESPLIT] function clearScripts ( node ) { var rslt = { } ; for ( var key in node ) { var val = node [ key ] ; if ( _ . isString ( val ) ) { if ( val . trim ( ) ) rslt [ key ] = "..." ; } else { var childScripts = clearScripts ( val ) ; if ( ! _ . isEmpty ( childScripts ) ) rslt [ key ] = childScripts ; } } return rslt ; }


Input: holds functions and error handlers [CODESPLIT] function ( obj , array ) { if ( ! Array . prototype . indexOf ) { for ( var i = 0 ; i < array . length ; i ++ ) { if ( array [ i ] === obj ) { return i ; } } return - 1 ; } else { return array . indexOf ( obj ) ; } }


Input: @module @lobsangnet / lobsang - formatter - matrix / schema Library to format a message into a schemaMessage [CODESPLIT] function format ( message , topic ) { const now = new Date ( ) const license = constants . LOBSANG_DEFAULT_LICENSE const id = 'toBeAdapted' const issuer = 'toBeAdapted' return { content : message , topic , license , contentType : null , created : now . toISOString ( ) , derivedFrom : null , id , issuer } }


Input: / * jslint moz : true [CODESPLIT] function setupListeners ( chat , displayWorker ) { chat . on ( displayWorker . port . emit . bind ( displayWorker . port ) ) ; displayWorker . port . on ( 'login' , function ( ) { chat . login ( ) ; } ) ; displayWorker . port . on ( 'logout' , function ( ) { chat . logout ( ) ; } ) ; displayWorker . port . on ( 'send' , function ( data ) { chat . send ( data . to , data . msg ) ; } ) ; displayWorker . port . on ( 'test' , function ( data ) { console . log ( 'Test message: ' + data ) ; } ) ; }


Input: / * Functional map with sugar . [CODESPLIT] function factory ( fn , options ) { var settings = options || { } var key = settings . key var indices = settings . indices var gapless = settings . gapless if ( typeof settings === 'string' ) { key = settings } if ( indices == null ) { indices = true } return all function all ( values ) { var results = [ ] var parent = values var index = - 1 var length var result if ( key ) { if ( array ( values ) ) { parent = null } else { values = parent [ key ] } } length = values . length while ( ++ index < length ) { if ( indices ) { result = fn . call ( this , values [ index ] , index , parent ) } else { result = fn . call ( this , values [ index ] , parent ) } if ( ! gapless || result != null ) { results . push ( result ) } } return results } }


Input: Get the element values of a given node list . [CODESPLIT] function getElementValues ( nodeList , initialScope ) { const valueList = [ ] for ( let i = 0 ; i < nodeList . length ; ++ i ) { const elementNode = nodeList [ i ] if ( elementNode == null ) { valueList . length = i + 1 } else if ( elementNode . type === "SpreadElement" ) { const argument = getStaticValueR ( elementNode . argument , initialScope ) if ( argument == null ) { return null } valueList . push ( ... argument . value ) } else { const element = getStaticValueR ( elementNode , initialScope ) if ( element == null ) { return null } valueList . push ( element . value ) } } return valueList }


Input: Get the value of a given node if it s a static value . [CODESPLIT] function getStaticValueR ( node , initialScope ) { if ( node != null && Object . hasOwnProperty . call ( operations , node . type ) ) { return operations [ node . type ] ( node , initialScope ) } return null }


Input: Check whether a given variable is modified or not . [CODESPLIT] function isModifiedGlobal ( variable ) { return ( variable == null || variable . defs . length !== 0 || variable . references . some ( r => r . isWrite ( ) ) ) }


Input: Define the output configuration . [CODESPLIT] function config ( ext ) { return { input : "src/index.js" , output : { file : ` ${ ext } ` , format : ext === ".mjs" ? "es" : "cjs" , sourcemap : true , sourcemapFile : ` ${ ext } ` , strict : true , banner : ` ` , } , plugins : [ sourcemaps ( ) ] , external : Object . keys ( require ( "./package.json" ) . dependencies ) , } }


Input: Check whether a given character is escaped or not . [CODESPLIT] function isEscaped ( str , index ) { let escaped = false for ( let i = index - 1 ; i >= 0 && str . charCodeAt ( i ) === 0x5c ; -- i ) { escaped = ! escaped } return escaped }


Input:
Replace a given string by a given matcher . [CODESPLIT] function replaceS ( matcher , str , replacement ) { const chunks = [ ] let index = 0 /** @type {RegExpExecArray} */ let match = null /**
     * @param {string} key The placeholder.
     * @returns {string} The replaced string.
     */ function replacer ( key ) { switch ( key ) { case "$$" : return "$" case "$&" : return match [ 0 ] case "$`" : return str . slice ( 0 , match . index ) case "$'" : return str . slice ( match . index + match [ 0 ] . length ) default : { const i = key . slice ( 1 ) if ( i in match ) { return match [ i ] } return key } } } for ( match of matcher . execAll ( str ) ) { chunks . push ( str . slice ( index , match . index ) ) chunks . push ( replacement . replace ( placeholder , replacer ) ) index = match . index + match [ 0 ] . length } chunks . push ( str . slice ( index ) ) return chunks . join ( "" ) }


Input: eslint - disable - next - line valid - jsdoc Replace a given string by a given matcher . [CODESPLIT] function replaceF ( matcher , str , replace ) { const chunks = [ ] let index = 0 for ( const match of matcher . execAll ( str ) ) { chunks . push ( str . slice ( index , match . index ) ) chunks . push ( String ( replace ( ... match , match . index , match . input ) ) ) index = match . index + match [ 0 ] . length } chunks . push ( str . slice ( index ) ) return chunks . join ( "" ) }


Input: Get the left parenthesis of the parent node syntax if it exists . E . g . if ( a ) {} then the ( . [CODESPLIT] function getParentSyntaxParen ( node , sourceCode ) { const parent = node . parent switch ( parent . type ) { case "CallExpression" : case "NewExpression" : if ( parent . arguments . length === 1 && parent . arguments [ 0 ] === node ) { return sourceCode . getTokenAfter ( parent . callee , isOpeningParenToken ) } return null case "DoWhileStatement" : if ( parent . test === node ) { return sourceCode . getTokenAfter ( parent . body , isOpeningParenToken ) } return null case "IfStatement" : case "WhileStatement" : if ( parent . test === node ) { return sourceCode . getFirstToken ( parent , 1 ) } return null case "SwitchStatement" : if ( parent . discriminant === node ) { return sourceCode . getFirstToken ( parent , 1 ) } return null case "WithStatement" : if ( parent . object === node ) { return sourceCode . getFirstToken ( parent , 1 ) } return null default : return null } }


Input: https : // dev . twitch . tv / docs / v5 / guides / PubSub / [CODESPLIT] function psOpen ( ) { _event ( 'dev' , 'pubsub - connected successfully' ) ; let frame = { type : 'LISTEN' , nonce : 'listenToTopics' , data : { topics : [ 'channel-bits-events-v1.' + state . channel_id , // 'channel-subscribe-events-v1.' + state.channel_id, 'chat_moderator_actions.' + state . id + '.' + state . channel_id , 'whispers.' + state . id , ] , auth_token : state . oauth , } , } ; send ( JSON . stringify ( frame ) ) ; ping ( ) ; }


Input: this provides some preventative error handling because the pubsub edge seems to be unstable [CODESPLIT] function send ( msg ) { switch ( ps . readyState ) { case 0 : // CONNECTING setTimeout ( function ( ) { send ( msg ) ; } , 1000 ) ; break ; case 2 : // CLOSING case 3 : // CLOSED _event ( 'dev' , 'pubsub - reconnect: send() - closing/closed state' ) ; connect ( ) ; setTimeout ( function ( ) { send ( msg ) ; } , 2000 ) ; break ; case 1 : // OPEN try { ps . send ( msg ) ; } catch ( err ) { console . error ( err ) ; setTimeout ( function ( ) { send ( msg ) ; } , 1500 ) ; } break ; default : break ; } }


Input: data is message . data so it should have msg . topic and msg . message [CODESPLIT] function parseMessage ( data ) { switch ( data . topic ) { // https://dev.twitch.tv/docs/v5/guides/PubSub/ case 'channel-bits-events-v1.' + state . channel_id : bits ( ) ; break ; // https://discuss.dev.twitch.tv/t/in-line-broadcaster-chat-mod-logs/7281/12 case 'chat_moderator_actions.' + state . id + '.' + state . id : moderation ( ) ; break ; case 'whispers.' + state . id : whisper ( ) ; break ; // case 'channel-subscribe-events-v1.' + state.channel_id: //   sub(); //   break; default : break ; } function bits ( ) { let bits = JSON . parse ( data . message ) ; _event ( 'bits' , bits ) ; } function moderation ( ) { let moderation = JSON . parse ( data . message ) . data ; _event ( 'moderation' , moderation ) ; } function whisper ( ) { let message = JSON . parse ( data . message ) . data_object ; // TODO: figure out why some whispers are dropped... // _event('whisper', message); } // function sub() { //   // TODO: https://discuss.dev.twitch.tv/t/subscriptions-beta-changes/10023 // } }


Input: JWT - Class representing a JSON Web Token it s payload and it s status [CODESPLIT] function JWT ( secret , options ) { this . token = '' ; this . payload = { } ; this . secret = secret ; this . options = options ; this . valid = false ; this . expired = false ; this . stale = true ; }


Input: sign - generate a new token from the payload [CODESPLIT] function ( payload ) { payload . stales = Date . now ( ) + this . options . stales ; this . payload = payload ; this . token = utils . sign ( this . payload , this . secret , this . options . signOptions ) ; this . valid = true ; this . expired = false ; this . stale = false ; return this ; }


Input: store - stores the JWT in the cookie [CODESPLIT] function ( res ) { if ( this . options . cookies ) { res . cookie ( this . options . cookie , this . token , this . options . cookieOptions ) ; } return this ; }


Input: toJSON - this function is called when the jwt is passed through JSON . stringify we don t want the secret or options to be stringified [CODESPLIT] function ( ) { return { token : this . token , payload : this . payload , valid : this . valid , expired : this . expired , stale : this . stale } ; }


Input: verify - verifies the JWT s token [CODESPLIT] function ( token ) { this . token = token || '' ; try { this . payload = utils . verify ( this . token , this . secret , this . options . verifyOptions ) ; this . valid = true ; } catch ( err ) { this . payload = utils . decode ( this . token ) || { } ; if ( err . name == 'TokenExpiredError' ) { this . expired = true ; } } if ( this . valid && ! this . options . verify ( this ) ) { this . valid = false ; } if ( this . payload . stales && Date . now ( ) <= this . payload . stales ) { this . stale = false ; } return this ; }


Input: / * create - creates a JWT without storing it [CODESPLIT] function ( secret , payload ) { if ( ! secret ) { throw new ReferenceError ( 'secret must be defined' ) ; } if ( typeof secret == 'string' ) { var _secret = secret ; secret = function ( payload ) { return _secret } ; } var jwt = new JWT ( secret ( payload ) , this . options ) ; return jwt . sign ( payload ) ; }


Input:
init - initialize jwt - express [CODESPLIT] function ( secret , options ) { if ( ! secret ) { throw new ReferenceError ( 'secret must be defined' ) ; } if ( typeof secret == 'string' ) { var _secret = secret ; secret = function ( req ) { return _secret } ; } options = options || { } ; var defaults = { cookie : 'jwt-express' , cookieOptions : { httpOnly : true } , cookies : true , refresh : true , reqProperty : 'jwt' , revoke : function ( jwt ) { } , signOptions : { } , stales : 900000 , verify : function ( jwt ) { return true } , verifyOptions : { } } ; for ( var key in defaults ) { this . options [ key ] = options [ key ] !== undefined ? options [ key ] : defaults [ key ] ; } return function ( req , res , next ) { var token ; if ( this . options . cookies ) { token = req . cookies [ this . options . cookie ] ; } else if ( req . headers . authorization ) { // Authorization: Bearer abc.abc.abc token = req . headers . authorization . split ( ' ' ) [ 1 ] ; } var jwt = new JWT ( secret ( req ) , this . options ) ; req [ this . options . reqProperty ] = jwt . verify ( token ) ; if ( jwt . valid && ! jwt . stale && jwt . options . refresh ) { jwt . resign ( ) . store ( res ) ; } /**
             * jwt - Creates and signs a new JWT. If cookies are in use, it stores
             *     the JWT in the cookie as well.
             * @param object payload The payload of the JWT
             * @return JWT
             */ res . jwt = function ( payload ) { var jwt = new JWT ( secret ( req ) , this . options ) ; return jwt . sign ( payload ) . store ( res ) ; } . bind ( this ) ; this . clear = function ( ) { if ( this . options . cookies ) { res . clearCookie ( this . options . cookie ) ; } } . bind ( this ) ; next ( ) ; } . bind ( this ) ; }


Input: require - requires that data in the JWT s payload meets certain requirements If only the key is passed it simply checks that payload [ key ] == true [CODESPLIT] function ( key , operator , value ) { if ( ! key ) { throw new ReferenceError ( 'key must be defined' ) ; } if ( operator && [ '==' , '===' , '!=' , '!==' , '<' , '<=' , '>' , '>=' ] . indexOf ( operator ) === - 1 ) { throw new JWTExpressError ( 'Invalid operator: ' + operator ) ; } return function ( req , res , next ) { var jwt = req [ this . options . reqProperty ] || { payload : { } } , data = jwt . payload [ key ] , ok ; if ( ! operator ) { ok = ! ! data ; } else if ( operator == '==' ) { ok = data == value ; } else if ( operator == '===' ) { ok = data === value ; } else if ( operator == '!=' ) { ok = data != value ; } else if ( operator == '!==' ) { ok = data !== value ; } else if ( operator == '<' ) { ok = data < value ; } else if ( operator == '<=' ) { ok = data <= value ; } else if ( operator == '>' ) { ok = data > value ; } else if ( operator == '>=' ) { ok = data >= value ; } if ( ! ok ) { var err = new JWTExpressError ( 'JWT is insufficient' ) ; err . key = key ; err . data = data ; err . operator = operator ; err . value = value ; next ( err ) ; } else { next ( ) ; } } . bind ( this ) ; }


Input: valid - requires that a JWT is valid [CODESPLIT] function ( ) { return function ( req , res , next ) { var jwt = req [ this . options . reqProperty ] || { } ; if ( ! jwt . valid ) { next ( new JWTExpressError ( 'JWT is invalid' ) ) ; } else { next ( ) ; } } . bind ( this ) ; }


Input: setupComponent - Assumes it has been called in the context of a jasmine spec . - Creates a new HTML element and attaches to it an instance of this . Component - If a fixture is provided the fixture will serve as the component root . [CODESPLIT] function setupComponent ( fixture , options ) { // tear down any existing component instance if ( this . component ) { this . component . teardown ( ) ; this . $node . remove ( ) ; } if ( fixture instanceof jQuery || typeof fixture === 'string' ) { // use the fixture to create component root node this . $node = $ ( fixture ) . addClass ( 'component-root' ) ; } else { // create an empty component root node this . $node = $ ( '<div class="component-root" />' ) ; options = fixture ; fixture = null ; } // append component root node to body $ ( 'body' ) . append ( this . $node ) ; // normalize options options = options === undefined ? { } : options ; // instantiate component on component root node this . component = ( new this . Component ( ) ) . initialize ( this . $node , options ) ; }


Input: describeComponentFactory loads the specified amd component / mixin before executing specDefinitions provides this . setupComponent Component instances created with this . setupComponent are torn down after each spec [CODESPLIT] function describeComponentFactory ( componentPath , specDefinitions , isMixin ) { return function ( ) { beforeEach ( function ( done ) { // reset member variables this . Component = this . component = this . $node = null ; // bind setupComponent to the current context this . setupComponent = setupComponent . bind ( this ) ; var requireCallback = function ( registry , defineComponent , Component ) { // reset the registry registry . reset ( ) ; if ( isMixin ) { // mix the mixin in to an anonymous, component this . Component = defineComponent ( function ( ) { } , Component ) ; } else { this . Component = Component ; } // let Jasmine know we're good to continue with the tests done ( ) ; } . bind ( this ) ; require ( [ 'flight/lib/registry' , 'flight/lib/component' , componentPath ] , requireCallback ) ; } ) ; afterEach ( function ( done ) { // remove the component root node if ( this . $node ) { this . $node . remove ( ) ; this . $node = null ; } var requireCallback = function ( defineComponent ) { // reset local member variables this . component = null ; this . Component = null ; // teardown all flight components defineComponent . teardownAll ( ) ; done ( ) ; } . bind ( this ) ; require ( [ 'flight/lib/component' ] , requireCallback ) ; } ) ; specDefinitions . apply ( this ) ; } ; }


Input: Load amd module before executing specDefinitions [CODESPLIT] function describeModuleFactory ( modulePath , specDefinitions ) { return function ( ) { beforeEach ( function ( done ) { this . module = null ; var requireCallback = function ( module ) { this . module = module ; done ( ) ; } . bind ( this ) ; require ( [ modulePath ] , requireCallback ) ; } ) ; specDefinitions . apply ( this ) ; } ; }


Input: apply a function to all values should only be used for side effects ( fn ) - > prom [CODESPLIT] function each ( fn ) { assert . equal ( typeof fn , 'function' ) return function ( arr ) { arr = Array . isArray ( arr ) ? arr : [ arr ] return arr . reduce ( function ( prev , curr , i ) { return prev . then ( function ( ) { return fn ( curr , i , arr . length ) } ) } , Promise . resolve ( ) ) . then ( function ( ) { return arr } ) } }


Input: Middleware constructor function [CODESPLIT] function consul ( options , resilient ) { defineResilientOptions ( params , options ) return { // Incoming traffic middleware 'in' : function inHandler ( err , res , next ) { if ( err ) return next ( ) // resilient.js sometimes calls the middleware function more than once, with the output // of the previous invokation; checking here the type of the items in the response to // only call `mapServers` with service objects, not URLs (strings) if ( Array . isArray ( res . data ) && Object ( res . data [ 0 ] ) === res . data [ 0 ] ) { res . data = mapServers ( res . data ) } next ( ) } , // Outgoing traffic middleware 'out' : function outHandler ( options , next ) { options . params = options . params || { } if ( params . datacenter ) { options . params . dc = params . datacenter } if ( params . onlyHealthy ) { options . params . passing = true } if ( params . tag ) { options . params . tag = params . tag } next ( ) } } }


Input: Incoming traffic middleware [CODESPLIT] function inHandler ( err , res , next ) { if ( err ) return next ( ) // resilient.js sometimes calls the middleware function more than once, with the output // of the previous invokation; checking here the type of the items in the response to // only call `mapServers` with service objects, not URLs (strings) if ( Array . isArray ( res . data ) && Object ( res . data [ 0 ] ) === res . data [ 0 ] ) { res . data = mapServers ( res . data ) } next ( ) }


Input: Outgoing traffic middleware [CODESPLIT] function outHandler ( options , next ) { options . params = options . params || { } if ( params . datacenter ) { options . params . dc = params . datacenter } if ( params . onlyHealthy ) { options . params . passing = true } if ( params . tag ) { options . params . tag = params . tag } next ( ) }


Input: API [CODESPLIT] function parsePrice ( input ) { var str = String ( input ) var decimalPart = '00' var decimalSymbol = getDecimalSymbol ( str ) if ( decimalSymbol ) { decimalPart = str . split ( decimalSymbol ) [ 1 ] } var integerPart = str . split ( decimalSymbol ) [ 0 ] return Number ( filterNumbers ( integerPart ) + '.' + filterNumbers ( decimalPart ) ) }


Input: / * Notice : It s a Scrollable best practice to use plain functions instead of React bound methods . Read more about why on the minimal example . [CODESPLIT] function handler ( x , y , self , items , scroller ) { var transitionPixels = 100 ; var ratio = 6 ; var headerPos = Math . max ( transitionPixels - y , 0 ) / ratio ; if ( y < 0 ) { headerPos = transitionPixels / ratio ; } switch ( self . props . name ) { case "content" : return { zIndex : 3 , y : - y + items . background . rect . height , } ; case "white" : return { // this rounding to 0.001 and 0.9999 should not be needed. // some browsers were causing re-paint. So I will leave this here // as documentation opacity : Math . max ( 0.001 , Math . min ( 1 / transitionPixels * y , 0.9999 ) ) , zIndex : 5 , y : headerPos , } ; case "transparent" : return { zIndex : 4 , y : headerPos , } ; case "background" : return { scale : Math . max ( 1 , 1 - ( y / 400 ) ) , zIndex : 2 , y : Math . min ( 0 , - y ) , } ; default : // during development, if I create a new <ScrollItem> this is handy // as it will sticky this element to the bottom of the <Scroller> return { zIndex : 10 , y : scroller . rect . height - self . rect . height , } ; } }


Input: / * Notice : It s a Scrollable best practice to use plain functions instead of React bound methods . Read more about why on the minimal example . [CODESPLIT] function consumptionBars ( x , y , self , items , scroller ) { // All calculations are made for top handler, then inverted in the end // if this call refers to the bottom handler // If we are in the middle of the content and scrolled past the swipe origin // keeps reseting origin until user scrolls down. Effectively this means the // first time user scrolls down starts hiding the bars again. if ( y > 0 && y < scroller . origin && scroller . consuming ) { scroller . origin = y ; } // if we are near the top, force topBar to show if ( y <= self . rect . height && ! scroller . consuming ) { scroller . consuming = true ; scroller . origin = 0 ; } var pos ; if ( scroller . consuming ) { pos = Math . min ( scroller . origin - y , 0 ) ; } else { pos = - self . rect . height ; // offscreen } // As the top bar moves offscreen, it should be locked offscreen if ( pos <= - self . rect . height ) { scroller . consuming = false ; } // If this was called from botbar, make it work from bottom of the viewport. if ( self === items . botbar ) { pos = scroller . rect . height - self . rect . height - pos ; } return { y : pos , zIndex : 5 , } ; }


Input: constructor [CODESPLIT] function Pipe2Pam ( ) { if ( ! ( this instanceof Pipe2Pam ) ) { return new Pipe2Pam ( ) ; } //set readableObjectMode to true so that we can push objects out //set writableObjectMode to false since we only support receiving buffer Transform . call ( this , { writableObjectMode : false , readableObjectMode : true } ) ; //parsing first chunk should be looking for image header info this . _parseChunk = this . _findHeaders ; }


Input: / * cleanupStyles ------------- Used for removing all prefixed versions added by server - side rendering . There is a lot of edge - cases in browsers with vendor prefixes so the only strategy that works consistently is let React render all prefixed styles at all times then having this cleanup phase that removes all styles then adds back the styles that we should keep . [CODESPLIT] function cleanupStyles ( item ) { var prop ; var reactProps ; if ( item . props . style ) { reactProps = { } ; for ( prop in item . props . style ) { reactProps [ prop ] = item . _node . style [ prop ] ; } } item . _node . removeAttribute ( 'style' ) ; if ( reactProps ) { for ( prop in reactProps ) { item . _node . style [ prop ] = reactProps [ prop ] ; } } if ( item . _prevStyles ) { for ( prop in item . _prevStyles ) { item . _node . style [ prop ] = item . _prevStyles [ prop ] ; } } }


Input: Retrieves a list of image search results from Google @param ( String ) searchTerm @param ( Function ) callback ( function to call once results are processed ) @param ( Number ) - optional - start ( starting from what result ) @param ( Number ) - optional - num ( how many results to return 1 - 10 ) [CODESPLIT] function getImageSearchResults ( searchTerm , callback , start , num ) { start = start < 0 || start > 90 || typeof ( start ) === 'undefined' ? 0 : start ; num = num < 1 || num > 10 || typeof ( num ) === 'undefined' ? 10 : num ; if ( ! searchTerm ) { console . error ( 'No search term' ) ; } var parameters = '&q=' + encodeURIComponent ( searchTerm ) ; parameters += '&searchType=image' ; parameters += start ? '&start=' + start : '' ; parameters += '&num=' + num ; var options = { host : 'www.googleapis.com' , path : '/customsearch/v1?key=' + process . env . CSE_API_KEY + '&cx=' + process . env . CSE_ID + parameters } ; var result = '' ; https . get ( options , function ( response ) { response . setEncoding ( 'utf8' ) ; response . on ( 'data' , function ( data ) { result += data ; } ) ; response . on ( 'end' , function ( ) { var data = JSON . parse ( result ) ; var resultsArray = [ ] ; // check for usage limits (contributed by @ryanmete) // This handles the exception thrown when a user's Google CSE quota has been exceeded for the day. // Google CSE returns a JSON object with a field called "error" if quota is exceed. if ( data . error && data . error . errors ) { resultsArray . push ( data . error . errors [ 0 ] ) ; // returns the JSON formatted error message in the callback callback ( resultsArray ) ; } else if ( data . items ) { // search returned results data . items . forEach ( function ( item ) { resultsArray . push ( item ) ; } ) ; callback ( resultsArray ) ; } else { callback ( [ ] ) ; } } ) ; } ) ; }


Input: When listing all categories and user taps on a given category [CODESPLIT] function ( categoryId , event ) { event . preventDefault ( ) ; this . refs . scroller . prepareAnimationSync ( ) ; this . setState ( { mode : 'single' , selected : categoryId , previousScrollPosition : this . refs . scroller . scrollTop , } , function ( ) { this . refs . scroller . animateAndResetScroll ( 0 , 0 ) ; } ) ; }


Input: When showing a single category and user taps the stack [CODESPLIT] function ( event ) { event . preventDefault ( ) ; this . setState ( { mode : 'all' , selected : null , } , function ( ) { this . refs . scroller . animateAndResetScroll ( 0 , this . state . previousScrollPosition ) ; } ) ; }


Input: ms [CODESPLIT] function handlePositionWhenShowingAllCategories ( x , y , self , items , scroller ) { var order = Data . categoryIds . indexOf ( self . props . categoryId ) ; var multiplier = Math . max ( 1 , 1 - ( y / friction ) ) ; // stretch effect var pos = Math . max ( 0 , order * multiplier * itemSizeDuringListMode - y ) ; return { height : scroller . rect . height - spaceAtBottom + 'px' , zIndex : 2 + order , y : pos , } ; }


Input: Service represents a set of grouped values necessary to provide a logical function . For instance a Door Lock Mechanism service might contain two values one for the desired lock state and one for the current lock state . A particular Service is distinguished from others by its type which is a UUID . HomeKit provides a set of known Service UUIDs defined in HomeKitTypes . js along with a corresponding concrete subclass that you can instantiate directly to setup the necessary values . These natively - supported Services are expected to contain a particular set of Characteristics . [CODESPLIT] function Service ( displayName , UUID , subtype ) { if ( ! UUID ) throw new Error ( "Services must be created with a valid UUID." ) ; this . displayName = displayName ; this . UUID = UUID ; this . subtype = subtype ; this . iid = null ; // assigned later by our containing Accessory this . characteristics = [ ] ; this . optionalCharacteristics = [ ] ; // every service has an optional Characteristic.Name property - we'll set it to our displayName // if one was given // if you don't provide a display name, some HomeKit apps may choose to hide the device. if ( displayName ) { // create the characteristic if necessary var nameCharacteristic = this . getCharacteristic ( Characteristic . Name ) || this . addCharacteristic ( Characteristic . Name ) ; nameCharacteristic . setValue ( displayName ) ; } }


Input: Characteristic represents a particular typed variable that can be assigned to a Service . For instance a Hue Characteristic might store a float value of type arcdegrees . You could add the Hue Characteristic to a Service in order to store that value . A particular Characteristic is distinguished from others by its UUID . HomeKit provides a set of known Characteristic UUIDs defined in HomeKitTypes . js along with a corresponding concrete subclass . [CODESPLIT] function Characteristic ( displayName , UUID , props ) { this . displayName = displayName ; this . UUID = UUID ; this . iid = null ; // assigned by our containing Service this . value = null ; this . props = props || { format : null , unit : null , minValue : null , maxValue : null , minStep : null , perms : [ ] } ; }


Input: Bridge is a special type of HomeKit Accessory that hosts other Accessories behind it . This way you can simply publish () the Bridge ( with a single HAPServer on a single port ) and all bridged Accessories will be hosted automatically instead of needed to publish () every single Accessory as a separate server . [CODESPLIT] function Bridge ( displayName , serialNumber ) { Accessory . call ( this , displayName , serialNumber ) ; this . _isBridge = true ; // true if we are a Bridge (creating a new instance of the Bridge subclass sets this to true) this . bridgedAccessories = [ ] ; // If we are a Bridge, these are the Accessories we are bridging }


Input: Processes the schema descriptors to upgrade the database schema to the greatest version specified . [CODESPLIT] function migrateDatabase ( nativeDatabase , nativeTransaction , schemaDescriptors , currentVersion ) { let descriptorsToProcess = schemaDescriptors . filter ( ( descriptor ) => { return descriptor . version > currentVersion } ) if ( ! descriptorsToProcess . length ) { return PromiseSync . resolve ( undefined ) } return migrateDatabaseVersion ( nativeDatabase , nativeTransaction , descriptorsToProcess [ 0 ] ) . then ( ( ) => { return migrateDatabase ( nativeDatabase , nativeTransaction , descriptorsToProcess , descriptorsToProcess [ 0 ] . version ) } ) }


Input: Performs a single - version database migration to the schema described by the provided database schema descriptor . [CODESPLIT] function migrateDatabaseVersion ( nativeDatabase , nativeTransaction , descriptor ) { let fetchPromise if ( descriptor . fetchBefore && descriptor . fetchBefore . length ) { let fetcher = new RecordFetcher ( ) let objectStores = normalizeFetchBeforeObjectStores ( descriptor . fetchBefore ) fetchPromise = fetcher . fetchRecords ( nativeTransaction , objectStores ) } else { fetchPromise = PromiseSync . resolve ( { } ) } return fetchPromise . then ( ( recordsMap ) => { let versionMigrator = new DatabaseVersionMigrator ( nativeDatabase , nativeTransaction , descriptor . objectStores ) return versionMigrator . executeMigration ( descriptor . after || ( ( ) => { } ) , recordsMap ) } ) }


Input: Normalizes the provided array of object store fetch descriptors to process before upgrading the database schema . [CODESPLIT] function normalizeFetchBeforeObjectStores ( objectStores ) { return objectStores . map ( ( objectStore ) => { if ( typeof objectStore === "string" ) { return { objectStore , preprocessor : record => record } } else if ( ! objectStore . preprocessor ) { return { objectStore : objectStore . objectStore , preprocessor : record => record } } else { return objectStore } } ) }


Input: Validates the types of the provided schema descriptors . [CODESPLIT] function checkSchemaDescriptorTypes ( schemaDescriptors ) { let onlyPlainObjects = schemaDescriptors . every ( ( descriptor ) => { return descriptor . constructor === Object } ) if ( onlyPlainObjects ) { return } if ( ! ( schemaDescriptors [ 0 ] instanceof DatabaseSchema ) ) { throw new TypeError ( "The schema descriptor of the lowest described " + ` ${ schemaDescriptors [ 0 ] . version } ` + "DatabaseSchema instance, or all schema descriptors must be plain " + "objects" ) } schemaDescriptors . slice ( 1 ) . forEach ( ( descriptor ) => { if ( ! ( descriptor instanceof UpgradedDatabaseSchema ) ) { throw new TypeError ( "The schema descriptors of the upgraded database " + "versions must be UpgradedDatabaseSchema instances, but the " + ` ${ descriptor . version } ` + "UpgradedDatabaseSchema instance, or all schema descriptors must " + "be plain objects" ) } } ) }


Input: Creates a promise that resolves to a record list containing the first page of records matching the provided filter . [CODESPLIT] function list ( storage , keyRange , filter , direction , unique , pageSize , storageFactory ) { return new Promise ( ( resolve , reject ) => { let items = [ ] storage . createCursorFactory ( keyRange , direction ) ( ( cursor ) => { if ( ! filter || filter ( cursor . record , cursor . primaryKey , cursor . key ) ) { if ( items . length === pageSize ) { finalize ( true , cursor . key , cursor . primaryKey ) return } else { items . push ( cursor . record ) } } cursor . continue ( ) } ) . then ( ( ) => finalize ( false , null , null ) ) . catch ( error => reject ( error ) ) function finalize ( hasNextPage , nextKey , nextPrimaryKey ) { resolve ( new RecordList ( items , storageFactory , nextKey , nextPrimaryKey , direction , unique , filter , pageSize , hasNextPage ) ) } } ) }


Input: Normalizes the provided compound key represented as an object into a compound key representation compatible with the Indexed DB . [CODESPLIT] function normalizeCompoundObjectKey ( keyPaths , key ) { let normalizedKey = [ ] keyPaths . forEach ( ( keyPath ) => { let keyValue = key keyPath . split ( "." ) . forEach ( ( fieldName ) => { if ( ! keyValue . hasOwnProperty ( fieldName ) ) { throw new Error ( ` ${ keyPath } ` + "provided compound key" ) } keyValue = keyValue [ fieldName ] } ) normalizedKey . push ( keyValue ) } ) return normalizedKey }


Input: Iterates the cursor to which the provided Indexed DB request resolves . The method will iterate the cursor over the records in this storage within the range specified when the cursor was opened until the provided callback does not request iterating to the next record or the last matching record is reached . [CODESPLIT] function iterateCursor ( request , cursorConstructor , recordCallback ) { return new PromiseSync ( ( resolve , reject ) => { let traversedRecords = 0 let canIterate = true request . onerror = ( ) => reject ( request . error ) request . onsuccess = ( ) => { if ( ! canIterate ) { console . warn ( "Cursor iteration was requested asynchronously, " + "ignoring the new cursor position" ) return } if ( ! request . result ) { resolve ( traversedRecords ) return } traversedRecords ++ let iterationRequested = handleCursorIteration ( request , cursorConstructor , recordCallback , reject ) if ( ! iterationRequested ) { canIterate = false resolve ( traversedRecords ) } } } ) }


Input: Handles a single iteration of a Indexed DB cursor iterating the records in the storage . [CODESPLIT] function handleCursorIteration ( request , cursorConstructor , recordCallback , reject ) { let iterationRequested = false let cursor = new cursorConstructor ( request , ( ) => { iterationRequested = true } , ( subRequest ) => { return PromiseSync . resolve ( subRequest ) . catch ( ( error ) => { reject ( error ) throw error } ) } ) try { recordCallback ( cursor ) } catch ( error ) { iterationRequested = false reject ( error ) } return iterationRequested }


Input: Fetches all records from the specified object stores using the provided read - write transaction . [CODESPLIT] function fetchAllRecords ( transaction , objectStores ) { return PromiseSync . all ( objectStores . map ( ( descriptor ) => { return fetchRecords ( transaction . getObjectStore ( descriptor . objectStore ) , descriptor . preprocessor ) } ) ) . then ( ( fetchedRecords ) => { let recordsMap = { } for ( let i = 0 ; i < objectStores . length ; i ++ ) { recordsMap [ objectStores [ i ] . objectStore ] = fetchedRecords [ i ] } return recordsMap } ) }


Input: Extracts all records from the provided object store and preprocess them using the provided preprocessor . [CODESPLIT] function fetchRecords ( objectStore , preprocessor ) { return new PromiseSync ( ( resolve , reject ) => { let records = [ ] objectStore . openCursor ( null , CursorDirection . NEXT , ( cursor ) => { let primaryKey = cursor . primaryKey if ( primaryKey instanceof Object ) { Object . freeze ( primaryKey ) } let preprocessedRecord = preprocessor ( cursor . record , primaryKey ) if ( preprocessedRecord === UpgradedDatabaseSchema . DELETE_RECORD ) { cursor . delete ( ) cursor . continue ( ) return } else if ( preprocessedRecord !== UpgradedDatabaseSchema . SKIP_RECORD ) { records . push ( { key : primaryKey , record : preprocessedRecord } ) } else { // SKIP_RECORD returned, do nothing } cursor . continue ( ) } ) . then ( ( ) => resolve ( records ) ) . catch ( error => reject ( error ) ) } ) }


Input: writeFileP Create the directory structure and then create the file . [CODESPLIT] function writeFileP ( outputPath , data , cb ) { outputPath = abs ( outputPath ) ; let dirname = path . dirname ( outputPath ) ; mkdirp ( dirname , err => { if ( err ) { return cb ( err ) ; } let str = data ; if ( typpy ( data , Array ) || typpy ( data , Object ) ) { str = JSON . stringify ( data , null , 2 ) ; } fs . writeFile ( outputPath , str , err => cb ( err , data ) ) ; } ) ; }


Input: Runs the provided transaction operations on the specified object stores obtained from the provided transaction . [CODESPLIT] function runTransaction ( transaction , objectStoreNames , transactionOperations ) { let callbackArguments = objectStoreNames . map ( ( objectStoreName ) => { return transaction . getObjectStore ( objectStoreName ) } ) callbackArguments . push ( ( ) => transaction . abort ( ) ) let resultPromise = transactionOperations ( ... callbackArguments ) return Promise . resolve ( resultPromise ) . then ( ( result ) => { return transaction . completionPromise . then ( ( ) => result ) } ) }


Input: Returns the cursor direction to use with the native Indexed DB API . [CODESPLIT] function toNativeCursorDirection ( direction , unique ) { if ( typeof direction === "string" ) { if ( CURSOR_DIRECTIONS . indexOf ( direction . toUpperCase ( ) ) === - 1 ) { throw new Error ( "When using a string as cursor direction, use NEXT " + ` ${ direction } ` ) ; } } else { direction = direction . value } let cursorDirection = direction . toLowerCase ( ) . substring ( 0 , 4 ) if ( unique ) { cursorDirection += "unique" } return cursorDirection }


Input: Returns { @code true } if the index should be deleted from the object store whether because it is no longer present in the schema or its properties have been updated in the schema . [CODESPLIT] function shouldDeleteIndex ( objectStore , schema , indexName ) { let schemaIndexes = schema . indexes || [ ] let newIndexNames = schemaIndexes . map ( indexSchema => indexSchema . name ) if ( newIndexNames . indexOf ( indexName ) === - 1 ) { return true } let index = objectStore . index ( indexName ) let indexKeyPath = index . keyPath ; if ( indexKeyPath && ( typeof indexKeyPath !== "string" ) ) { indexKeyPath = Array . from ( indexKeyPath ) } let serializedIndexKeyPath = JSON . stringify ( indexKeyPath ) let indexSchema = schemaIndexes . filter ( ( indexSchema ) => { return indexSchema . name === index . name } ) [ 0 ] return ( index . unique !== indexSchema . unique ) || ( index . multiEntry !== indexSchema . multiEntry ) || ( serializedIndexKeyPath !== JSON . stringify ( indexSchema . keyPaths ) ) }


Input: Creates a new index in the provided object store according to the provided index schema . [CODESPLIT] function createIndex ( objectStore , indexSchema ) { let indexNames = Array . from ( objectStore . indexNames ) if ( indexNames . indexOf ( indexSchema . name ) !== - 1 ) { return } objectStore . createIndex ( indexSchema . name , indexSchema . keyPath , { unique : indexSchema . unique , multiEntry : indexSchema . multiEntry } ) }


Input: Fetches the next page of records in a new ready - only transaction and resolves into a record list containing the fetched records . [CODESPLIT] function fetchNextPage ( storageFactory , keyRange , cursorDirection , unique , firstPrimaryKey , filter , pageSize ) { let storage = storageFactory ( ) let nextItems = [ ] return new Promise ( ( resolve , reject ) => { let idb = idbProvider ( ) let cursorFactory = storage . createCursorFactory ( keyRange , cursorDirection , unique ) cursorFactory ( ( cursor ) => { if ( ! unique ) { let shouldSkip = ( ( cursorDirection === CursorDirection . NEXT ) && ( idb . cmp ( firstPrimaryKey , cursor . primaryKey ) > 0 ) ) || ( ( cursorDirection === CursorDirection . PREVIOUS ) && ( idb . cmp ( firstPrimaryKey , cursor . primaryKey ) < 0 ) ) if ( shouldSkip ) { cursor . continue ( ) return } } if ( ! filter || filter ( cursor . record , cursor . primaryKey , cursor . key ) ) { if ( nextItems . length === pageSize ) { finalize ( true , cursor . key , cursor . primaryKey ) return } else { nextItems . push ( cursor . record ) } } cursor . continue ( ) } ) . then ( ( ) => finalize ( false , null , null ) ) . catch ( error => reject ( error ) ) function finalize ( hasNextPage , nextKey , nextPrimaryKey ) { resolve ( new RecordList ( nextItems , storageFactory , nextKey , nextPrimaryKey , cursorDirection , unique , filter , pageSize , hasNextPage ) ) } } ) }


Input: Executes the provided event listeners with the provided parameters . Any errors thrown by the executed event listeners will be caught and logged to the console and then the remaining event listeners will be executed . [CODESPLIT] function executeEventListeners ( listeners , ... parameters ) { listeners . forEach ( ( listener ) => { try { listener . apply ( null , parameters ) } catch ( error ) { console . error ( "An event listener threw an error" , error ) } } ) }


Input: Resolves the provided promise to the specified state and result value . This function has no effect if the provided promise has already been resolved . [CODESPLIT] function resolve ( instance , newState , value ) { if ( instance [ FIELDS . state ] !== STATE . PENDING ) { return } instance [ FIELDS . state ] = newState instance [ FIELDS . value ] = value let listeners if ( newState === STATE . RESOLVED ) { listeners = instance [ FIELDS . fulfillListeners ] } else { listeners = instance [ FIELDS . errorListeners ] } for ( let listener of listeners ) { listener ( ) } }


Input: Executes the specified query using the provided cursor factory . [CODESPLIT] function runQuery ( cursorFactory , filter , comparator , offset , limit , callback ) { let records = [ ] let recordIndex = - 1 return cursorFactory ( ( cursor ) => { if ( ! filter && offset && ( ( recordIndex + 1 ) < offset ) ) { recordIndex = offset - 1 cursor . advance ( offset ) return } let primaryKey = cursor . primaryKey if ( filter && ! filter ( cursor . record , primaryKey ) ) { cursor . continue ( ) return } if ( comparator ) { insertSorted ( records , cursor . record , primaryKey , comparator ) if ( offset || limit ) { if ( records . length > ( offset + limit ) ) { records . pop ( ) } } cursor . continue ( ) return } recordIndex ++ if ( recordIndex < offset ) { cursor . continue ( ) return } callback ( cursor . record , primaryKey ) if ( ! limit || ( ( recordIndex + 1 ) < ( offset + limit ) ) ) { cursor . continue ( ) } } ) . then ( ( ) => { if ( ! comparator ) { return } records = records . slice ( offset ) for ( let { record , primaryKey } of records ) { callback ( record , primaryKey ) } } ) }


Input: Inserts the provided record into the sorted array of records and their primary keys keeping it sorted . [CODESPLIT] function insertSorted ( records , record , primaryKey , comparator ) { let index = findInsertIndex ( records , record , comparator ) records . splice ( index , 0 , { record , primaryKey } ) }


Input: Uses the binary search algorithm to find the index at which the specified record should be inserted into the specified array of records to keep the array sorted according to the provided comparator . [CODESPLIT] function findInsertIndex ( records , record , comparator ) { if ( ! records . length ) { return 0 } if ( records . length === 1 ) { let comparison = comparator ( records [ 0 ] . record , record ) return ( comparison > 0 ) ? 0 : 1 } let comparison = comparator ( records [ 0 ] . record , record ) if ( comparison > 0 ) { return 0 } let bottom = 1 let top = records . length - 1 while ( bottom <= top ) { let pivotIndex = Math . floor ( ( bottom + top ) / 2 ) let comparison = comparator ( records [ pivotIndex ] . record , record ) if ( comparison > 0 ) { let previousElement = records [ pivotIndex - 1 ] . record if ( comparator ( previousElement , record ) <= 0 ) { return pivotIndex } top = pivotIndex - 1 } else { bottom = pivotIndex + 1 } } return records . length }


Input: Prepares the query that uses the specified filter and record order for execution on this storage . [CODESPLIT] function prepareQuery ( thisStorage , filter , order ) { order = normalizeKeyPath ( order ) let expectedSortingDirection = order [ 0 ] . charAt ( 0 ) === "!" let canSortingBeOptimized canSortingBeOptimized = canOptimizeSorting ( expectedSortingDirection , order ) let storages = new Map ( ) storages . set ( normalizeKeyPath ( thisStorage . keyPath ) , { storage : thisStorage , score : 1 // traversing storage is faster than fetching records by index } ) for ( let indexName of thisStorage . indexNames ) { let index = thisStorage . getIndex ( indexName ) if ( ! index . multiEntry ) { storages . set ( normalizeKeyPath ( index . keyPath ) , { storage : index , score : 0 } ) } } let simplifiedOrderFieldPaths = simplifyOrderingFieldPaths ( order ) if ( canSortingBeOptimized ) { prepareSortingOptimization ( storages , simplifiedOrderFieldPaths ) } prepareFilteringOptimization ( storages , filter ) return chooseStorageForQuery ( storages , order , simplifiedOrderFieldPaths , canSortingBeOptimized , expectedSortingDirection ) }


Input: Calculates the best possible sorting optimization for the provided storages updating the provided map with sorting optimization scores for each storage . [CODESPLIT] function prepareSortingOptimization ( storages , simplifiedOrderFieldPaths ) { let idb = idbProvider ( ) for ( let [ keyPath , storageAndScore ] of storages ) { let keyPathSlice = keyPath . slice ( 0 , simplifiedOrderFieldPaths . length ) if ( idb . cmp ( keyPathSlice , simplifiedOrderFieldPaths ) === 0 ) { storageAndScore . score += 4 // optimizing the sorting is more important } } }


Input: Calculates the best possible filtering optimizations for the provided storages updating the provided map with optimized filtering info and optimization score for each storage . [CODESPLIT] function prepareFilteringOptimization ( storages , filter ) { if ( filter instanceof Function ) { for ( let [ keyPath , storageAndScore ] of storages ) { storageAndScore . filter = filter } return } for ( let [ keyPath , storageAndScore ] of storages ) { let normalizedFilter = normalizeFilter ( filter , keyPath ) if ( normalizedFilter instanceof Function ) { let isOptimizableFilter = ( filter instanceof Object ) && ! ( filter instanceof Date ) && ! ( filter instanceof Array ) && ! ( filter instanceof IDBKeyRange ) if ( isOptimizableFilter ) { let partialOptimization = partiallyOptimizeFilter ( filter , keyPath ) storageAndScore . keyRange = partialOptimization . keyRange storageAndScore . filter = partialOptimization . filter if ( partialOptimization . score ) { storageAndScore . score += 1 + partialOptimization . score } } else { storageAndScore . filter = normalizedFilter } } else { storageAndScore . keyRange = normalizedFilter storageAndScore . score += 2 } } }


Input: Selects the storage on which the execute a query that should lead to the best possible performance . The method returns all the data necessary to execute the query . [CODESPLIT] function chooseStorageForQuery ( storages , order , simplifiedOrderFieldPaths , canSortingBeOptimized , expectedSortingDirection ) { let sortedStorages = Array . from ( storages . values ( ) ) sortedStorages . sort ( ( storage1 , storage2 ) => { return storage2 . score - storage1 . score } ) let chosenStorageDetails = sortedStorages [ 0 ] let chosenStorage = chosenStorageDetails . storage let chosenStorageKeyPath = normalizeKeyPath ( chosenStorage . keyPath ) let storageKeyPathSlice = chosenStorageKeyPath . slice ( 0 , simplifiedOrderFieldPaths . length ) let optimizeSorting = canSortingBeOptimized && ( idbProvider ( ) . cmp ( storageKeyPathSlice , simplifiedOrderFieldPaths ) === 0 ) return { storage : chosenStorage , direction : optimizeSorting ? ( CursorDirection [ expectedSortingDirection ? "PREVIOUS" : "NEXT" ] ) : CursorDirection . NEXT , comparator : optimizeSorting ? null : compileOrderingFieldPaths ( order ) , keyRange : chosenStorageDetails . keyRange , filter : chosenStorageDetails . filter } }


Input: Determines whether the sorting of the query result can be done through an index ( provided such index exists ) or the natural order of the records in the object store . [CODESPLIT] function canOptimizeSorting ( expectedSortingDirection , order ) { for ( let orderingFieldPath of order ) { if ( ( orderingFieldPath . charAt ( 0 ) === "!" ) !== expectedSortingDirection ) { return false } } return true }


Input: Preprocess the raw ordering specification into form that can be used in query optimization . [CODESPLIT] function prepareOrderingSpecificationForQuery ( order , keyPath ) { if ( order === null ) { order = CursorDirection . NEXT } let isCursorDirection = ( ( typeof order === "string" ) && ( CURSOR_DIRECTIONS . indexOf ( order . toUpperCase ( ) ) > - 1 ) ) || ( CURSOR_DIRECTIONS . indexOf ( order ) > - 1 ) if ( isCursorDirection && ( typeof order === "string" ) ) { order = CursorDirection [ order . toUpperCase ( ) ] || CursorDirection . PREVIOUS } if ( order instanceof CursorDirection ) { keyPath = normalizeKeyPath ( keyPath ) if ( order === CursorDirection . NEXT ) { return keyPath } else { return keyPath . map ( fieldPath => ` ${ fieldPath } ` ) } } return order }


Input: Handles opening the connection to the database and wraps the whole process in a promise . [CODESPLIT] function openConnection ( databaseName , sortedSchemaDescriptors ) { let version = sortedSchemaDescriptors . slice ( ) . pop ( ) . version let request = NativeDBAccessor . indexedDB . open ( databaseName , version ) return new Promise ( ( resolve , reject ) => { let wasBlocked = false let upgradeTriggered = false let migrationPromiseResolver , migrationPromiseRejector let migrationPromise = new Promise ( ( resolve , reject ) => { migrationPromiseResolver = resolve migrationPromiseRejector = reject } ) // prevent leaking the same error to the console twice migrationPromise . catch ( ( ) => { } ) request . onsuccess = ( ) => { let database = new Database ( request . result ) resolve ( database ) migrationPromiseResolver ( ) } request . onupgradeneeded = ( event ) => { if ( ! wasBlocked ) { upgradeTriggered = true } let database = request . result let transaction = request . transaction if ( wasBlocked ) { transaction . abort ( ) return } upgradeDatabaseSchema ( databaseName , event , migrationPromise , database , transaction , sortedSchemaDescriptors , migrationPromiseResolver , migrationPromiseRejector ) . catch ( ( error ) => { transaction . abort ( ) } ) } request . onerror = ( event ) => { handleConnectionError ( event , request . error , wasBlocked , upgradeTriggered , reject , migrationPromiseRejector ) } request . onblocked = ( ) => { wasBlocked = true let error = new Error ( "A database upgrade was needed, but could not " + "be performed, because the attempt was blocked by a connection " + "that remained opened after receiving the notification" ) reject ( error ) migrationPromiseRejector ( error ) } } ) }


Input: Handles a database error encountered during connection establishing . [CODESPLIT] function handleConnectionError ( event , error , wasBlocked , upgradeTriggered , reject , migrationPromiseRejector ) { if ( wasBlocked || upgradeTriggered ) { event . preventDefault ( ) return } reject ( request . error ) migrationPromiseRejector ( request . error ) }


Input: Handles the provided { @code upgradeneeded } event that occurred during opening a database that was not blocked . The function handles database schema upgrade . [CODESPLIT] function upgradeDatabaseSchema ( databaseName , event , migrationPromise , database , transaction , sortedSchemaDescriptors , migrationPromiseResolver , migrationPromiseRejector ) { executeMigrationListeners ( databaseName , event . oldVersion , event . newVersion , migrationPromise ) let migrator = new DatabaseMigrator ( database , transaction , sortedSchemaDescriptors , event . oldVersion ) return PromiseSync . resolve ( ) . then ( ( ) => { return migrator . executeMigration ( ) } ) . then ( ( ) => { migrationPromiseResolver ( ) } ) . catch ( ( error ) => { migrationPromiseRejector ( error ) throw error } ) }


Input: Executes the currently registered database schema migration listeners with the provided arguments . [CODESPLIT] function executeMigrationListeners ( databaseName , oldVersion , newVersion , completionPromise ) { for ( let listener of migrationListeners ) { try { listener ( databaseName , oldVersion , newVersion , completionPromise ) } catch ( e ) { console . warn ( "A schema migration event listener threw an error" , e ) ; } } }


Input: A sub - routine of the { @linkcode partiallyOptimizeFilter } used to generate optimization result if the storage key path matches the field paths in the filter object . [CODESPLIT] function partiallyOptimizeKeyPathMatchingFilter ( filter , keyPath ) { let keyRange = convertFieldMapToKeyRange ( filter , keyPath ) if ( ! keyRange ) { // at least one of the values is a IDBKeyRange instance return { keyRange : undefined , filter : compileFieldRangeFilter ( filter ) , score : 0 } } return { keyRange , filter : null , score : 1 } }


Input: Splits the provided filter object to two objects according the the provided storage key path . This is used to separate a complex filter object into an object optimizable into a key range and a simpler object that will be compiled into a filter predicate function . [CODESPLIT] function splitFilteringObject ( filter , filterFieldPaths , storageKeyPath ) { let fieldsToOptimize = { } let fieldsToCompile = { } filterFieldPaths . forEach ( ( fieldPath ) => { let value = getFieldValue ( filter , fieldPath ) if ( storageKeyPath . indexOf ( fieldPath ) > - 1 ) { setFieldValue ( fieldsToOptimize , fieldPath , value ) } else { setFieldValue ( fieldsToCompile , fieldPath , value ) } } ) return { fieldsToOptimize , fieldsToCompile } }


Input: Compiles the provided field path to a function that retrieves the value of the field denoted by the field path from the object passed to the function or { @code undefined } if the field does not exist in the object . [CODESPLIT] function compileFieldGetter ( fieldPath ) { let fields = fieldPath . split ( "." ) return ( record ) => { let value = record for ( let field of fields ) { if ( ! ( value instanceof Object ) || ! value . hasOwnProperty ( field ) ) { return undefined } value = value [ field ] } return value } }