Input: Coined [CODESPLIT] function Coined ( options ) { var self = this , dbType , dbDir , dbPath ; if ( ! ( this instanceof Coined ) ) { return new Coined ( options ) ; } EventEmitter . call ( this ) ; options = options || { } ; options . db = options . db || { } ; dbType = options . db . type || 'tiny' ; dbDir = dbType === 'level' ? '.coined.level' : '.coined' ; dbPath = dbType === 'level' ? path . resolve ( process . env . HOME , dbDir ) : path . resolve ( process . env . HOME , dbDir , 'db' ) ; options . db . type = options . db . type || dbType ; options . db . path = options . db . path || dbPath ; if ( options . db . clear ) { cleanup ( options . db . path ) ; } if ( options . db . type === 'level' ) { mkdirp ( options . db . path ) ; this . db = require ( 'levelup' ) ( options . db . path , { db : require ( 'leveldown' ) , valueEncoding : 'json' } ) ; } else if ( options . db . type === 'tiny' ) { mkdirp ( path . resolve ( options . db . path , '..' ) ) ; this . db = require ( 'tiny' ) . json ( { file : options . db . path , saveIndex : false , initialCache : false } ) ; } else { throw new Error ( 'Invalid DB type.' ) ; } this . options = options ; this . socketIndex = 0 ; this . crypto = options . crypto ; this . compressed = options . compressed != null ? options . compressed : true ; this . walletPath = options . walletPath || options . wallet || process . env . HOME + '/.coined/wallet.json' ; this . addr = null ; this . dust = 5460 ; this . fee = 10000 ; mkdirp ( path . dirname ( this . walletPath ) ) ; this . account = null ; this . accounts = [ ] ; this . aaccounts = { } ; this . laccounts = { } ; this . recipients = { } ; if ( options . noPreload ) { this . _clearPreload ( ) ; } this . pool = options . pool || bcoin . pool ( { size : options . size , createConnection : function ( ) { if ( self . socketIndex >= seeds . length ) { self . socketIndex = 0 ; } if ( seeds . length > 3000 ) { seeds = seeds . slice ( 0 , 1500 ) ; self . socketIndex = 0 ; } var addr = seeds [ self . socketIndex ++ ] , parts = addr . split ( ':' ) , host = parts [ 0 ] , port = + parts [ 1 ] || network . port , socket ; socket = net . connect ( port , host ) ; socket . on ( 'connect' , function ( ) { var peers = [ ] . concat ( self . pool . peers . pending , self . pool . peers . block , self . pool . peers . load ) . filter ( Boolean ) ; for ( var i = 0 ; i < peers . length ; i ++ ) { var peer = peers [ i ] ; if ( peer . socket !== socket ) { continue ; } if ( peer . version ) { return self . emit ( 'peer' , peer , socket ) ; } return peer . parser . on ( 'packet' , function callee ( payload ) { if ( payload . cmd !== 'version' ) return ; peer . removeListener ( 'packet' , callee ) ; return setImmediate ( function ( ) { self . emit ( 'peer' , peer , socket ) ; } ) ; } ) ; } self . _log ( 'Connected to %s:%d' , host , port ) ; } ) ; return socket ; } , storage : this . db , startHeight : options . startHeight , fullNode : options . fullNode // relay: options.relay } ) ; this . blockHeight = 0 ; this . on ( 'peer' , function ( peer ) { if ( ! peer . version || ! peer . socket ) { return ; } if ( peer . version . height > self . blockHeight ) { self . blockHeight = peer . version . height ; } self . _log ( 'Connected to %s:%d (%s v%s) height=%d relay=%d' , peer . socket . remoteAddress , peer . socket . remotePort , peer . version . agent , peer . version . v , peer . version . height , peer . version . relay ) ; } ) ; if ( options . noPreload ) { network . preload = network . _preload ; } this . pool . on ( 'error' , function ( err ) { self . _error ( err ) ; } ) ; this . salt = 'coined:' ; this . pending = { } ; this . loadWallet ( null , this . passphrase ) ; if ( ! this . account ) { this . createAccount ( options ) ; } // Keep track of version, handle upgrades. this . version = Coined . version ; this . previousVersion = '0.0.0' ; this . db . get ( 'meta/version' , function ( err , data ) { if ( data ) { self . previousVersion = data . version ; } return self . db . put ( 'meta/version' , { version : self . version } , function ( err ) { if ( err ) return self . _error ( err ) ; self . _log ( 'Version written: %s, previous: %s' , self . version , self . previousVersion ) ; } ) ; } ) ; // Listeners to remove on .destroy(); this . pool . _poolOnTX = null ; this . pool . _poolOnReject = null ; this . pool . _poolOnceFull = null ; this . closed = false ; this . init ( ) ; }


Input: Copyright 2010 James Halliday ( mail [CODESPLIT] function mkdirp ( dir , made ) { var mode = 0777 & ( ~ process . umask ( ) ) ; if ( ! made ) made = null ; dir = path . resolve ( dir ) ; try { fs . mkdirSync ( dir , mode ) ; made = made || dir ; } catch ( err0 ) { switch ( err0 . code ) { case 'ENOENT' : made = mkdirp ( path . dirname ( dir ) , made ) ; mkdirp ( dir , made ) ; break ; default : var stat ; try { stat = fs . statSync ( dir ) ; } catch ( err1 ) { throw err0 ; } if ( ! stat . isDirectory ( ) ) throw err0 ; break ; } } return made ; }


Input: Walker function to iterate though the collection / array / object tree [CODESPLIT] function ( obj ) { if ( _ . isArray ( obj ) ) { for ( var i = 0 ; i < obj . length ; i ++ ) { obj [ i ] = walker ( obj [ i ] ) ; } } else if ( _ . isPlainObject ( obj ) ) { var newObj = { } ; for ( var k in obj ) { if ( ! obj . hasOwnProperty ( k ) ) continue ; var include = true ; if ( options . renameFields [ k ] ) { newObj [ options . renameFields [ k ] ] = obj [ k ] ; include = false ; } for ( var rf in options . removeFields ) { if ( _ . isRegExp ( options . removeFields [ rf ] ) ) { if ( options . removeFields [ rf ] . test ( k ) ) include = false ; } else { // Assume its a function if ( options . removeFields [ rf ] . test ( obj [ k ] , k ) ) include = false ; } if ( ! include ) break ; } if ( include ) newObj [ k ] = walker ( obj [ k ] ) ; } obj = newObj ; } else if ( _ . isObject ( obj ) ) { return obj . toString ( ) ; } return obj ; }


Input: 返回文件名字 + 后缀 [CODESPLIT] function fileext ( type , path ) { if ( ! path ) path = type , type = false ; var file_arr = path . match ( / ([^:\\/]*?)(?:\.([^ :\\/.]*))$ / ) var fileext = file_arr [ 2 ] ; var name = file_arr [ 1 ] ; var new_name = '' switch ( type ) { case "min" : new_name = name + '.min.' + fileext ; break ; case "map" : new_name = name + '.min.map' ; break ; case "gz" : new_name = name + '.min.gz' ; break ; default : new_name = file_arr [ 0 ] ; } return new_name ; }


Input: 换算 [CODESPLIT] function format_number ( size , precision ) { var decimal , factor ; if ( precision == null ) precision = 1 ; factor = Math . pow ( 10 , precision ) ; decimal = Math . round ( size * factor ) % factor ; return parseInt ( size ) + "." + decimal ; }


Input: 输出大小 [CODESPLIT] function report_size ( file ) { return echo ( " › " + c c.x t erm(1 6 1)( f i le)    "  " + ( o rmat_number(f s ize(f i le)  / 1 24))   + " KiB");   }


Input: get the full head system definition ( latest revision ) [CODESPLIT] function ( identifier , target , cb ) { logger . info ( 'get head system: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } _sr . getHead ( systemId , target , cb ) ; }


Input: get the full deployed system definition [CODESPLIT] function ( identifier , target , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } fetchTarget ( systemId , target , function ( err , target ) { if ( err ) { return cb ( err ) ; } logger . info ( { systemId : systemId , target : target } , 'get deployed system' ) ; _sr . getDeployedRevision ( systemId , target , cb ) ; } ) ; }


Input: create a new blank system [CODESPLIT] function ( user , name , namespace , cwd , cb ) { logger . info ( 'create system name: ' + name + ', namespace: ' + namespace + ', cwd: ' + cwd ) ; _sr . createSystem ( user , namespace , name , cwd , cb ) ; }


Input: link a system from local fs [CODESPLIT] function ( user , path , cwd , cb ) { logger . info ( 'link system: ' + path + ', ' + cwd ) ; _sr . linkSystem ( user , path , cwd , cb ) ; }


Input: / * unlink a system from local fs [CODESPLIT] function ( user , identifier , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { return cb ( new Error ( ERR_NOSYSID ) ) ; } logger . info ( 'unlink system: ' + systemId ) ; _sr . unlinkSystem ( user , systemId , cb ) ; }


Input: list all of the available containers in a system [CODESPLIT] function ( identifier , revisionId , out , cb ) { logger . info ( 'list containers: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; var containers = { } ; if ( ! systemId ) { return cb ( new Error ( ERR_NOSYSID ) ) ; } _builder . loadTargets ( systemId , revisionId , function ( err , targets ) { if ( err ) { return cb ( err ) ; } _ . each ( targets , function ( target ) { _ . each ( target . containerDefinitions , function ( cdef ) { containers [ cdef . id ] = cdef ; } ) ; } ) ; cb ( null , _ . values ( containers ) ) ; } ) ; }


Input: build a container [CODESPLIT] function ( user , identifier , containerIdentifier , revision , target , out , cb ) { var containerDef ; var systemId ; systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } var systemRoot = _sr . repoPath ( systemId ) ; out . initProgress ( 9 , '--> finding container' ) ; fetchTarget ( systemId , target , revision , function ( err , target ) { if ( err ) { return cb ( err ) ; } _builder . loadMatchingTargets ( systemId , revision , target , function ( err , targets ) { if ( err ) { return cb ( err ) ; } _builder . findContainer ( systemId , revision , targets , containerIdentifier , function ( err , containerDefId , targets ) { if ( err ) { out . stdout ( err ) ; logger . error ( err ) ; return cb ( err ) ; } if ( ! containerDefId ) { out . stdout ( ERR_NOCDEF ) ; logger . error ( ERR_NOCDEF ) ; return cb ( ERR_NOCDEF ) ; } async . eachSeries ( _ . values ( targets ) , function ( json , cb ) { var root = buildSys ( json ) ; containerDef = root . containerDefByDefId ( containerDefId ) ; json . repoPath = systemRoot ; if ( ! containerDef . specific || ! containerDef . specific . repositoryUrl ) { return _builder . build ( user , systemId , targets , json , containerDef , target , out , cb ) ; } _synchrotron . synch ( json , containerDef , out , function ( err ) { if ( err ) { out . stdout ( err ) ; logger . error ( err ) ; return cb ( err ) ; } _builder . build ( user , systemId , targets , json , containerDef , target , out , cb ) ; } ) ; } , cb ) ; } ) ; } ) ; } ) ; }


Input: build all containers belonging to a system in series [CODESPLIT] function ( user , systemName , revision , target , out , cb ) { var systemId = _sr . findSystem ( systemName ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } logger . info ( { systemId : systemId , revision : revision } , 'building all containers' ) ; fetchTarget ( systemId , target , revision , function ( err , target ) { if ( err ) { return cb ( err ) ; } _builder . loadMatchingTargets ( systemId , revision , target , function ( err , targets ) { if ( err ) { return cb ( err ) ; } out . stdout ( '--> building all containers for ' + targets [ Object . keys ( targets ) [ 0 ] ] . name + ' revision ' + revision + ' target ' + target ) ; var containers = _ . chain ( targets ) . filter ( function ( value , key ) { return target === 'alltargets' || key === target ; } ) . map ( function ( target ) { return _ . map ( target . containerDefinitions , function ( cdef ) { return { id : cdef . id , target : target . topology . name , type : cdef . type } ; } ) ; } ) . flatten ( ) . reduce ( function ( acc , cont ) { var notPresent = ! _ . find ( acc , function ( found ) { return found . id === cont . id && found . type === cont . type ; } ) ; if ( notPresent ) { acc . push ( cont ) ; } return acc ; } , [ ] ) . value ( ) ; async . eachSeries ( containers , function ( cont , next ) { buildContainer ( user , systemId , cont . id , revision , cont . target , out , function ( err ) { if ( err ) { out . stderr ( err ) ; } // so that buildall fails if one build fail next ( err ) ; } ) ; } , cb ) ; } ) ; } ) ; }


Input: Supports target abbreviation [CODESPLIT] function ( systemId , target , revision , cb ) { if ( target === 'alltargets' ) { cb ( null , target ) ; } else { _sr . getDeployedRevisionId ( systemId , target , function ( err , deployedRevId ) { if ( typeof revision === 'function' ) { cb = revision ; if ( ! err ) { revision = deployedRevId ; } else { revision = 'latest' ; } } _builder . loadTargets ( systemId , revision , function ( err , targets ) { if ( err ) { return cb ( err ) ; } var candidates = Object . keys ( targets ) . filter ( function ( candidate ) { return candidate . indexOf ( target ) >= 0 ; } ) ; if ( candidates . length === 0 || candidates . length > 1 ) { logger . error ( ERR_NOTARGET ) ; return cb ( new Error ( ERR_NOTARGET ) ) ; } else { target = candidates [ 0 ] ; } cb ( null , target ) ; } ) ; } ) ; } }


Input: deploy the specified revision to the nominated target handle if file is missing [CODESPLIT] function ( user , identifier , revisionIdentifier , target , mode , out , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } fetchTarget ( systemId , target , revisionIdentifier , function ( err , target ) { if ( err ) { return cb ( err ) ; } _sr . findRevision ( systemId , revisionIdentifier , function ( err , revisionId ) { if ( err ) { out . stdout ( ERR_NOREV ) ; logger . error ( ERR_NOREV ) ; return cb ( ERR_NOREV ) ; } logger . info ( { systemId : systemId , revisionId : revisionId , environment : target } , 'deploy revision' ) ; if ( ! mode ) { mode = 'live' ; } if ( ! revisionId ) { return cb ( new Error ( 'revisionId is needed to deploy' ) ) ; } return createAnalyzeAndDeployTask ( user , systemId , revisionId , target , mode , out , cb ) ; } ) ; } ) ; }


Input: preview a system deploy [CODESPLIT] function ( user , identifier , revisionIdentifier , target , out , cb ) { logger . info ( 'preview revision: ' + identifier + ', ' + revisionIdentifier + ' ' + target ) ; deployRevision ( user , identifier , revisionIdentifier , target , 'preview' , out , function ( err ) { cb ( err , { plan : out . getPlan ( ) , ops : out . operations ( ) } ) ; } ) ; }


Input: get the revision history for a system [CODESPLIT] function ( identifier , cb ) { logger . info ( 'list revisions: ' + identifier ) ; if ( ! identifier ) { return cb ( new Error ( 'no identifier' ) ) ; } var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { return cb ( new Error ( 'system not found' ) ) ; } _sr . listRevisions ( systemId , function ( err , revisions ) { cb ( err , _ . first ( revisions , 20 ) ) ; //cb(err, revisions); } ) ; }


Input: get a specific revision [CODESPLIT] function ( identifier , revisionIdentifier , target , cb ) { logger . info ( 'get revision: ' + identifier + ', ' + revisionIdentifier ) ; var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } fetchTarget ( systemId , target , revisionIdentifier , function ( err , target ) { if ( err ) { return cb ( err ) ; } _sr . findRevision ( systemId , revisionIdentifier , function ( err , revisionId ) { if ( err ) { return cb ( err ) ; } _sr . getRevision ( systemId , revisionId , target , cb ) ; } ) ; } ) ; }


Input: get timeline [CODESPLIT] function ( identifier , cb ) { var systemId = _sr . findSystem ( identifier ) ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } _sr . getTimeline ( systemId , function ( err , timeline ) { cb ( err , { entries : timeline } ) ; } ) ; }


Input: compile the system into the various targets and commit them to the repository [CODESPLIT] function ( user , identifier , comment , out , cb ) { logger . info ( 'compile system: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; var system ; if ( ! systemId ) { logger . error ( ERR_NOSYSID ) ; return cb ( new Error ( ERR_NOSYSID ) ) ; } var repoPath = _sr . repoPath ( systemId ) ; _compiler . compile ( systemId , repoPath , out , function ( err , systems ) { if ( err ) { return cb ( err ) ; } async . eachSeries ( _ . keys ( systems ) , function ( key , next ) { system = systems [ key ] ; _sr . writeFile ( system . id , key + '.json' , JSON . stringify ( system , null , 2 ) , next ) ; } , function ( err ) { cb ( err ) ; } ) ; } ) ; }


Input: commit the system [CODESPLIT] function ( user , identifier , comment , out , cb ) { logger . info ( 'commit system: ' + identifier ) ; var systemId = _sr . findSystem ( identifier ) ; _sr . commitRevision ( user , systemId , comment , function ( err , revisionId ) { _sr . getDeployedTargets ( systemId , function ( err , targets ) { if ( targets ) { async . eachSeries ( targets , function ( target , next ) { if ( target . commit === 'edits' ) { _sr . markDeployedRevision ( user , systemId , revisionId , target . env , function ( ) { next ( ) ; } ) ; } else { next ( ) ; } } , function ( ) { cb ( err , revisionId ) ; } ) ; } else { cb ( err , revisionId ) ; } } ) ; } ) ; }


Input: asynchronous task [CODESPLIT] function ( src , destination ) { grunt . verbose . writeln ( "Adding entries to be coffeeified/browserified: " + src ) ; var browserifyInstance = browserify ( src ) ; return { dest : destination , instance : browserifyInstance } ; }


Input: Finalize the task . [CODESPLIT] function finalizeBuild ( sourceReport ) { // Something went wrong. Fail the build. if ( errorCount > 0 ) { grunt . fail . warn ( "Coffeeification failed." ) ; // The build succeeded. Call done to  // finish the grunt task. } else { done ( "Coffeified " + sourceReport . count + ": " + sourceReport . locations ) ; } }


Input: Inject necessary code into the file app . js [CODESPLIT] function injectCode ( ) { var fullpath = path . join ( rootpath , "app.js" ) ; var source = fs . readFileSync ( fullpath , 'utf8' ) ; var test = / \/\/ALLOY-RESOLVER / . test ( source ) ; logger . trace ( "CODE INJECTED ALREADY: " + test ) ; if ( ! test ) { source = source . replace ( / (var\s+Alloy[^;]+;) / g , "$1\n//ALLOY-RESOLVER\nvar process=require('/process');\nAlloy.resolve=new (require('/resolver'))().resolve;\n" ) ; fs . writeFileSync ( fullpath , source ) ; } }


Input: Fix module resolution in all found javascript files [CODESPLIT] function fixFiles ( ) { logger . trace ( "inside fixFiles()" ) ; _ . each ( registry . files , function ( file ) { var fullpath = path . join ( rootpath , file ) ; var basepath = path . posix . dirname ( file ) ; var basefile = path . posix . resolve ( file ) ; var source = fs . readFileSync ( fullpath , 'utf8' ) ; logger . trace ( "fixing file: " + fullpath ) ; var requireRegex = / (require)\s*\(((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*)\) / g ; var staticRequireRegex = / (require)(?:\(\s*['"])([^'"]+)(?:['"]\s*\)) / g ; source = source . replace ( requireRegex , function ( $1 , $2 , $3 ) { var requestedModule = $2 ; if ( staticRequireRegex . test ( $1 ) ) { var staticRequireSource = $1 ; staticRequireSource = staticRequireSource . replace ( staticRequireRegex , function ( $1 , $2 , $3 ) { var resolved_path = resolver . resolve ( $3 , basepath ) ; return 'require("' + resolved_path + '")' ; } ) ; return staticRequireSource ; } else { return 'require(Alloy.resolve(' + $3 + ', "' + basepath + '"))' ; } } ) ; fs . writeFileSync ( fullpath , source , { mode : 0o755 } ) ; } ) ; }


Input: Replace backslashes for cross - platform usage Adapted from https : // github . com / sindresorhus / slash [CODESPLIT] function replaceBackSlashes ( input ) { var isExtendedLengthPath = / ^\\\\\?\\ / . test ( input ) ; var hasNonAscii = / [^\x00-\x80]+ / . test ( input ) ; if ( isExtendedLengthPath || hasNonAscii ) { return input ; } return input . replace ( / \\ / g , '/' ) ; }


Input: Find all files that match extension criteria [CODESPLIT] function findFiles ( rootpath , patterns ) { logger . trace ( "inside findFiles()" ) ; var patterns = patterns || [ '**' ] ; if ( _ . isString ( patterns ) ) { patterns = [ patterns ] ; } var files = _ . map ( wrench . readdirSyncRecursive ( rootpath ) , function ( filename ) { return path . posix . sep + replaceBackSlashes ( filename ) ; } ) ; var matchedFiles = match ( files , patterns , { nocase : true , matchBase : true , dot : true , } ) ; return _ . filter ( matchedFiles , function ( file ) { return ! fs . statSync ( path . join ( rootpath , file ) ) . isDirectory ( ) ; } ) || [ ] ; }


Input: Find items in array that match a set of patterns Adapted from https : // github . com / sindresorhus / multimatch [CODESPLIT] function match ( list , patterns , options ) { list = list || [ ] ; patterns = patterns || [ ] ; if ( _ . isString ( patterns ) ) { patterns = [ patterns ] ; } if ( list . length === 0 || patterns . length === 0 ) { return [ ] ; } options = options || { } ; return patterns . reduce ( function ( ret , pattern ) { var process = _ . union if ( pattern [ 0 ] === '!' ) { pattern = pattern . slice ( 1 ) ; process = _ . difference ; } return process ( ret , minimatch . match ( list , pattern , options ) ) ; } , [ ] ) ; }


Input: Find and process all files [CODESPLIT] function loadFiles ( ) { logger . trace ( "inside loadFiles()" ) ; var allfiles = findFiles ( rootpath , includes ) ; var filepaths = _ . filter ( allfiles , function ( filepath ) { return ! / .+(package\.json) / . test ( filepath ) ; } ) ; _ . forEach ( filepaths , function ( filepath ) { registry . files . push ( filepath ) ; } ) ; var packagepaths = _ . filter ( allfiles , function ( filepath ) { return ( / .+(package\.json) / . test ( filepath ) ) ; } ) ; _ . forEach ( packagepaths , function ( filepath ) { var content = fs . readFileSync ( path . posix . join ( rootpath , filepath ) , 'utf8' ) ; var json = JSON . parse ( content ) ; if ( json . main ) { registry . directories . push ( { id : path . posix . dirname ( filepath ) , path : path . posix . resolve ( path . posix . join ( path . posix . dirname ( filepath ) , json . main ) ) } ) ; } } ) ; var indexpaths = _ . filter ( allfiles , function ( filepath ) { return ( / .+(index\.js) / . test ( filepath ) ) ; } ) ; _ . forEach ( indexpaths , function ( filepath ) { var existingdir = _ . find ( registry . directories , function ( dir ) { return dir . id === path . posix . dirname ( filepath ) ; } ) ; if ( ! existingdir ) { registry . directories . push ( { id : path . posix . dirname ( filepath ) , path : filepath } ) ; } } ) ; return registry ; }


Input: Write registry file to resolver . js [CODESPLIT] function writeRegistry ( ) { logger . trace ( "inside writeRegistry()" ) ; var filepath = path . join ( rootpath , "resolver.js" ) ; var content = fs . readFileSync ( filepath , 'utf8' ) ; var regex = / (var\s+registry\s+=\s+)[^;]*(;) / g ; var modified = content . replace ( regex , "$1" + JSON . stringify ( registry ) + "$2" ) ; fs . writeFileSync ( filepath , modified ) ; }


Input: -------------------------------------------------------------------------- Public -------------------------------------------------------------------------- Returns the first letter of a string regardless of whitespace [CODESPLIT] function getFirstLetter ( text ) { var matches = text . match ( firstLetterRegex ) ; if ( null === matches ) { return '' ; } // Ignore JSDoc blocks if ( '@' === matches [ 1 ] ) { return '' ; } return matches [ 0 ] ; }


Input: actions [CODESPLIT] function setTheme ( theme ) { const navigationOptions = getNavigationOptions ( theme ) const contentOffset = theme . defaultValues . colors . headerOpacity < 1 ? ( theme . systemValues . isIOS ? theme . systemValues . statusBarHeight : 0 ) + theme . systemValues . navigationBarHeight : 0 return { type : CONSTANTS . theme . setTheme , theme , navigationOptions , // childNavigationOptions, contentOffset , } }


Input: reducer [CODESPLIT] function themeReducer ( state = initialState , action ) { switch ( action . type ) { case CONSTANTS . theme . setTheme : return { ... state , theme : action . theme , navigationOptions : action . navigationOptions , contentOffset : action . contentOffset , } default : return state } }


Input: URI // FUNCTION : uri ( value ) Validates if a value is a URI . [CODESPLIT] function uri ( val ) { var parts , scheme , authority , path ; if ( ! isString ( val ) ) { return false ; } // [1] Check for illegal characters: if ( ILLEGALS . test ( val ) ) { return false ; } // [2] Check for incomplete HEX escapes: if ( HEX1 . test ( val ) || HEX2 . test ( val ) ) { return false ; } // [3] Split the string into various URI components: parts = val . match ( URI ) ; scheme = parts [ 1 ] ; authority = parts [ 2 ] ; path = parts [ 3 ] ; // [4] Scheme is required and must be valid: if ( ! scheme || ! scheme . length || ! SCHEME . test ( scheme . toLowerCase ( ) ) ) { return false ; } // [5] If authority is not present, path must not begin with a '//': if ( ! authority && PATH . test ( path ) ) { return false ; } return true ; }


Input: Build the container and update all instantiations of the container with the new speicific block and replace identifiers for new uuids [CODESPLIT] function build ( mode , system , cdef , out , cb ) { _containers . getHandler ( system , cdef . type , function ( err , container ) { if ( err ) { return cb ( err ) ; } if ( ! container ) { err = new Error ( 'no matching container available for type: ' + cdef . type ) ; logger . error ( err . message ) ; return cb ( err ) ; } if ( container . build ) { out . progress ( '--> executing container specific build for ' + cdef . id ) ; logger . info ( { containerDefinition : cdef . id } , 'executing container specific build' ) ; container . build ( mode , system , cdef , out , function ( err , specific ) { if ( err ) { logger . error ( err ) ; out . stdout ( err ) ; return cb ( err ) ; } out . progress ( '--> ' + cdef . id + ' built' ) ; logger . info ( { containerDefinition : cdef . id } , 'built' ) ; cb ( err ) ; } ) ; } else { out . progress ( '--> no need to build ' + cdef . id ) ; cb ( null , { } ) ; } } ) ; }


Input: find the container in the supplied target files return the container with the highest buildHead number [CODESPLIT] function findContainer ( systemId , revision , targets , containerIdentifier , cb ) { var cdefId ; var types = [ ] ; async . filter ( _ . keys ( targets ) , function ( key , next ) { _sr . findContainer ( systemId , revision , containerIdentifier , key , function ( err , containerDefId , cdef ) { var def ; if ( ! err && containerDefId ) { cdefId = containerDefId ; def = _ . find ( targets [ key ] . containerDefinitions , function ( def ) { return def . id === cdefId ; } ) ; if ( types . indexOf ( def . type ) < 0 ) { types . push ( def . type ) ; return next ( true ) ; } } next ( false ) ; } ) ; } , function ( keys ) { var result = keys . reduce ( function ( acc , key ) { acc [ key ] = targets [ key ] ; return acc ; } , { } ) ; cb ( null , cdefId , result ) ; } ) ; }


Input:
/ * Merge emoji and github - emoji ( punctuation marks symbols and words ) into an EmoticonNode . [CODESPLIT] function mergeEmoji ( child , index , parent ) { var siblings = parent . children var value = toString ( child ) var siblingIndex var node var nodes var subvalue var left var right var leftMatch var rightMatch var start var pos var end var replace var startIndex var nextSibling var nextNextSibling var possibleEmoji var maxSiblingIndex var loopIndex var lastSibling var lastSiblingIndex if ( child . type === 'WordNode' ) { /* 1⃣ — sometimes a unicode emoji is marked as a word. Mark it as
     * an `EmoticonNode`. */ if ( own . call ( unicodes , value ) ) { node = { type : EMOTICON_NODE , value : value } if ( child . position ) { node . position = child . position } siblings [ index ] = node } else { /* ❤ — Sometimes a unicode emoji is split in two.  Remove the last
       * and add its value to the first. */ node = siblings [ index - 1 ] if ( node && own . call ( unicodes , toString ( node ) + value ) ) { node . type = EMOTICON_NODE node . value = toString ( node ) + value if ( child . position && node . position ) { node . position . end = child . position . end } siblings . splice ( index , 1 ) return index } } } else if ( own . call ( unicodes , value ) ) { child . type = EMOTICON_NODE startIndex = index + 1 nextSibling = siblings [ startIndex ] if ( ! nextSibling ) { return } if ( nextSibling . type === 'WordNode' ) { /* 🏌 — Normal emoji. */ if ( ! isVarianceSelector ( nextSibling ) ) { return } possibleEmoji = value + toString ( nextSibling ) maxSiblingIndex = siblings . length loopIndex = startIndex + 1 while ( loopIndex < maxSiblingIndex && loopIndex - startIndex < 5 && siblings [ loopIndex ] . type !== 'WordNode' ) { possibleEmoji += toString ( siblings [ loopIndex ] ) loopIndex ++ } lastSibling = siblings [ loopIndex ] if ( lastSibling && lastSibling . type === 'WordNode' ) { possibleEmoji += toString ( lastSibling ) } /* 🏌♀ — Emoji with variance selector. */ if ( own . call ( unicodes , possibleEmoji ) ) { child . value = possibleEmoji if ( child . position && lastSibling . position ) { child . position . end = lastSibling . position . end } siblings . splice ( index + 1 , loopIndex - index ) return index + 1 } /* 👨❤💋👨 — combined emoji. */ } else if ( nextSibling . type === 'SymbolNode' ) { possibleEmoji = value + toString ( nextSibling ) maxSiblingIndex = siblings . length loopIndex = startIndex + 1 while ( loopIndex < maxSiblingIndex && loopIndex - startIndex < 5 && ( siblings [ loopIndex ] . type === 'SymbolNode' || ( siblings [ loopIndex ] . type === 'WordNode' && isVarianceSelector ( siblings [ loopIndex ] ) ) ) ) { possibleEmoji += toString ( siblings [ loopIndex ] ) loopIndex ++ } if ( own . call ( unicodes , possibleEmoji ) ) { child . value = possibleEmoji lastSiblingIndex = loopIndex - 1 lastSibling = siblings [ lastSiblingIndex ] if ( child . position && lastSibling . position ) { child . position . end = lastSibling . position . end } siblings . splice ( index + 1 , lastSiblingIndex - index ) return index + 1 } } /* 🤽♀ — Combined emoji starting in a symbol. */ } else if ( child . type === 'SymbolNode' ) { nextSibling = siblings [ index + 1 ] nextNextSibling = siblings [ index + 2 ] if ( ! nextSibling || ! nextNextSibling ) { return } if ( ( nextSibling . type === 'SymbolNode' || nextSibling . type === 'WordNode' ) && nextNextSibling && nextNextSibling . type === 'SymbolNode' ) { possibleEmoji = value + toString ( nextSibling ) + toString ( nextNextSibling ) if ( own . call ( unicodes , possibleEmoji ) ) { child . type = EMOTICON_NODE child . value = possibleEmoji if ( child . position && nextNextSibling . position ) { child . position . end = nextNextSibling . position . end } siblings . splice ( index + 1 , 2 ) return index + 1 } } /* :+1: — Gemoji shortcodes. */ } else if ( value . charAt ( 0 ) === ':' ) { nodes = [ ] siblingIndex = index subvalue = value left = null right = null leftMatch = null rightMatch = null if ( subvalue . length === 1 ) { rightMatch = child } else { end = child . position && child . position . end start = end && child . position . start pos = end && { line : start . line , column : start . column + 1 , offset : start . offset + 1 } rightMatch = { type : 'PunctuationNode' , value : ':' } right = { type : 'PunctuationNode' , value : subvalue . slice ( 1 ) } if ( end ) { rightMatch . position = { start : start , end : pos } right . position = { start : pos , end : end } } } while ( siblingIndex -- ) { if ( index - siblingIndex > MAX_GEMOJI_PART_COUNT ) { return } node = siblings [ siblingIndex ] subvalue = toString ( node ) if ( subvalue . charAt ( subvalue . length - 1 ) === ':' ) { leftMatch = node break } if ( node . children ) { nodes = nodes . concat ( node . children . concat ( ) . reverse ( ) ) } else { nodes . push ( node ) } if ( siblingIndex === 0 ) { return } } if ( ! leftMatch ) { return } subvalue = toString ( leftMatch ) if ( subvalue . length !== 1 ) { end = leftMatch . position && leftMatch . position . end start = end && leftMatch . position . start pos = end && { line : end . line , column : end . column - 1 , offset : end . offset - 1 } left = { type : 'PunctuationNode' , value : subvalue . slice ( 0 , - 1 ) } leftMatch = { type : 'PunctuationNode' , value : ':' } if ( end ) { left . position = { start : start , end : pos } leftMatch . position = { start : pos , end : end } } } nodes . push ( leftMatch ) nodes . reverse ( ) . push ( rightMatch ) value = toString ( nodes ) if ( shortcodes . indexOf ( value ) === - 1 ) { return } replace = [ siblingIndex , index - siblingIndex + 1 ] if ( left ) { replace . push ( left ) } child . type = EMOTICON_NODE child . value = value if ( child . position && leftMatch . position ) { child . position . start = leftMatch . position . start } if ( child . position && rightMatch . position ) { child . position . end = rightMatch . position . end } replace . push ( child ) if ( right ) { replace . push ( right ) } ; [ ] . splice . apply ( siblings , replace ) return siblingIndex + 3 } }


Input: / * ==================================================== - returns starting row for Filter fn for a given table id ===================================================== [CODESPLIT] function getStartRow ( id ) { let r ; for ( let j in TblId ) { if ( TblId [ j ] === id ) r = StartRow [ j ] ; } return r ; }


Input: / * ==================================================== - checks passed node is a ELEMENT_NODE nodeType = 1 - removes TEXT_NODE nodeType = 3 ===================================================== [CODESPLIT] function getChildElms ( n ) { if ( n . nodeType == 1 ) { let enfants = n . childNodes ; for ( let i = 0 ; i < enfants . length ; i ++ ) { let child = enfants [ i ] ; if ( child . nodeType == 3 ) n . removeChild ( child ) ; } return n ; } }


Input: / * ==================================================== - filter ( input ) ids are stored in this . SearchFlt array ===================================================== [CODESPLIT] function getFilters ( id ) { SearchFlt = [ ] ; let t = document . getElementById ( id ) ; let tr = t . getElementsByTagName ( "tr" ) [ 0 ] ; let inp = tr . getElementsByTagName ( "input" ) ; for ( let i = 0 ; i < inp . length ; i ++ ) SearchFlt . push ( inp [ i ] . getAttribute ( "id" ) ) ; return SearchFlt ; }


Input: / * ==================================================== - returns number of cells in a row - if nrow param is passed returns number of cells of that specific row ===================================================== [CODESPLIT] function getCellsNb ( id , nrow ) { let t = document . getElementById ( id ) ; let tr ; if ( nrow == undefined ) tr = t . getElementsByTagName ( "tr" ) [ 0 ] ; else tr = t . getElementsByTagName ( "tr" ) [ nrow ] ; let n = getChildElms ( tr ) ; return n . childNodes . length ; }


Input:
a Rollcall 2 . 0 client [CODESPLIT] function ( url , db ) { this . server = new Drowsy . Server ( url ) ; this . db = this . server . database ( db ) ; // User model this . User = this . db . Document ( 'users' ) . extend ( { addTag : function ( tag ) { var tags = _ . clone ( this . get ( 'tags' ) ) ; // if no classes array exists add it if ( ! tags ) { tags = [ ] ; } tags . push ( tag ) ; this . set ( 'tags' , _ . uniq ( tags ) ) ; } , removeTag : function ( tag ) { var tags = this . get ( 'tags' ) ; this . set ( 'tags' , _ . without ( tags , tag ) ) ; } , addCohort : function ( c ) { var classes = _ . clone ( this . get ( 'cohorts' ) ) ; // if no cohorts array exists add it if ( ! cohorts ) { cohorts = [ ] ; } cohorts . push ( c ) ; this . set ( 'cohorts' , _ . uniq ( cohorts ) ) ; } , removeCohort : function ( c ) { var cohorts = this . get ( 'cohorts' ) ; this . set ( 'cohorts' , _ . without ( cohorts , c ) ) ; } , isTeacher : function ( ) { if ( this . get ( 'user_role' ) === 'teacher' ) { return true ; } else { return false ; } } } ) ; this . Users = this . db . Collection ( 'users' ) . extend ( { model : this . User } ) ; /*
     *   Group model
     */ this . Group = this . db . Document ( 'groups' ) . extend ( { addGroup : function ( group ) { var groups = _ . clone ( this . get ( 'groups' ) ) ; groups . push ( group ) ; this . set ( 'groups' , _ . uniq ( group ) ) ; } } ) ; this . Groups = this . db . Collection ( 'groups' ) . extend ( { model : this . Group } ) ; // Run model this . Run = this . db . Document ( 'runs' ) . extend ( { } ) ; this . Runs = this . db . Collection ( 'runs' ) . extend ( { model : this . Run } ) ; /*
     *   Model for Cohorts
     */ this . Cohort = this . db . Document ( 'cohorts' ) . extend ( { addDiscussion : function ( discussionId ) { var discussions = _ . clone ( this . get ( 'discussions' ) ) ; // if no discussions array exists add it if ( ! discussions ) { discussions = [ ] ; } discussions . push ( discussionId ) ; this . set ( 'discussions' , _ . uniq ( discussions ) ) ; } , removeDiscussion : function ( discussionId ) { var discussions = this . get ( 'discussions' ) ; this . set ( 'discussions' , _ . without ( discussions , discussionId ) ) ; } } ) ; this . Cohorts = this . db . Collection ( 'cohorts' ) . extend ( { model : this . Cohort } ) ; /*
     *   Model for Discussions
     */ this . Discussion = this . db . Document ( 'discussions' ) . extend ( { } ) ; this . Discussions = this . db . Collection ( 'discussions' ) . extend ( { model : this . Discussion } ) ; }


Input: Resolves . and .. elements in a path with directory names [CODESPLIT] function normalizeStringPosix ( path , allowAboveRoot ) { var res = '' ; var lastSlash = - 1 ; var dots = 0 ; var code ; for ( var i = 0 ; i <= path . length ; ++ i ) { if ( i < path . length ) code = path . charCodeAt ( i ) ; else if ( code === 47 /*/*/ ) break ; else code = 47 /*/*/ ; if ( code === 47 /*/*/ ) { if ( lastSlash === i - 1 || dots === 1 ) { // NOOP } else if ( lastSlash !== i - 1 && dots === 2 ) { if ( res . length < 2 || res . charCodeAt ( res . length - 1 ) !== 46 /*.*/ || res . charCodeAt ( res . length - 2 ) !== 46 /*.*/ ) { if ( res . length > 2 ) { var start = res . length - 1 ; var j = start ; for ( ; j >= 0 ; -- j ) { if ( res . charCodeAt ( j ) === 47 /*/*/ ) break ; } if ( j !== start ) { if ( j === - 1 ) res = '' ; else res = res . slice ( 0 , j ) ; lastSlash = i ; dots = 0 ; continue ; } } else if ( res . length === 2 || res . length === 1 ) { res = '' ; lastSlash = i ; dots = 0 ; continue ; } } if ( allowAboveRoot ) { if ( res . length > 0 ) res += '/..' ; else res = '..' ; } } else { if ( res . length > 0 ) res += '/' + path . slice ( lastSlash + 1 , i ) ; else res = path . slice ( lastSlash + 1 , i ) ; } lastSlash = i ; dots = 0 ; } else if ( code === 46 /*.*/ && dots !== - 1 ) { ++ dots ; } else { dots = - 1 ; } } return res ; }


Input: path . resolve ( [ from ... ] to ) [CODESPLIT] function resolve ( ) { var resolvedDevice = '' ; var resolvedTail = '' ; var resolvedAbsolute = false ; for ( var i = arguments . length - 1 ; i >= - 1 ; i -- ) { var path ; if ( i >= 0 ) { path = arguments [ i ] ; } else if ( ! resolvedDevice ) { path = process . cwd ( ) ; } else { // Windows has the concept of drive-specific current working // directories. If we've resolved a drive letter but not yet an // absolute path, get cwd for that drive. We're sure the device is not // a UNC path at this points, because UNC paths are always absolute. path = process . env [ '=' + resolvedDevice ] ; // Verify that a drive-local cwd was found and that it actually points // to our drive. If not, default to the drive's root. if ( path === undefined || path . slice ( 0 , 3 ) . toLowerCase ( ) !== resolvedDevice . toLowerCase ( ) + '\\' ) { path = resolvedDevice + '\\' ; } } assertPath ( path ) ; // Skip empty entries if ( path . length === 0 ) { continue ; } var len = path . length ; var rootEnd = 0 ; var code = path . charCodeAt ( 0 ) ; var device = '' ; var isAbsolute = false ; // Try to match a root if ( len > 1 ) { if ( code === 47 /*/*/ || code === 92 /*\*/ ) { // Possible UNC root // If we started with a separator, we know we at least have an // absolute path of some kind (UNC or otherwise) isAbsolute = true ; code = path . charCodeAt ( 1 ) ; if ( code === 47 /*/*/ || code === 92 /*\*/ ) { // Matched double path separator at beginning var j = 2 ; var last = j ; // Match 1 or more non-path separators for ( ; j < len ; ++ j ) { code = path . charCodeAt ( j ) ; if ( code === 47 /*/*/ || code === 92 /*\*/ ) break ; } if ( j < len && j !== last ) { var firstPart = path . slice ( last , j ) ; // Matched! last = j ; // Match 1 or more path separators for ( ; j < len ; ++ j ) { code = path . charCodeAt ( j ) ; if ( code !== 47 /*/*/ && code !== 92 /*\*/ ) break ; } if ( j < len && j !== last ) { // Matched! last = j ; // Match 1 or more non-path separators for ( ; j < len ; ++ j ) { code = path . charCodeAt ( j ) ; if ( code === 47 /*/*/ || code === 92 /*\*/ ) break ; } if ( j === len ) { // We matched a UNC root only device = '\\\\' + firstPart + '\\' + path . slice ( last ) ; rootEnd = j ; } else if ( j !== last ) { // We matched a UNC root with leftovers device = '\\\\' + firstPart + '\\' + path . slice ( last , j ) ; rootEnd = j ; } } } } else { rootEnd = 1 ; } } else if ( code >= 65 /*A*/ && code <= 90 /*Z*/ || code >= 97 /*a*/ && code <= 122 /*z*/ ) { // Possible device root code = path . charCodeAt ( 1 ) ; if ( path . charCodeAt ( 1 ) === 58 /*:*/ ) { device = path . slice ( 0 , 2 ) ; rootEnd = 2 ; if ( len > 2 ) { code = path . charCodeAt ( 2 ) ; if ( code === 47 /*/*/ || code === 92 /*\*/ ) { // Treat separator following drive name as an absolute path // indicator isAbsolute = true ; rootEnd = 3 ; } } } } } else if ( code === 47 /*/*/ || code === 92 /*\*/ ) { // `path` contains just a path separator rootEnd = 1 ; isAbsolute = true ; } if ( device . length > 0 && resolvedDevice . length > 0 && device . toLowerCase ( ) !== resolvedDevice . toLowerCase ( ) ) { // This path points to another device so it is not applicable continue ; } if ( resolvedDevice . length === 0 && device . length > 0 ) { resolvedDevice = device ; } if ( ! resolvedAbsolute ) { resolvedTail = path . slice ( rootEnd ) + '\\' + resolvedTail ; resolvedAbsolute = isAbsolute ; } if ( resolvedDevice . length > 0 && resolvedAbsolute ) { break ; } } // At this point the path should be resolved to a full absolute path, // but handle relative paths to be safe (might happen when process.cwd() // fails) // Normalize the tail path resolvedTail = normalizeStringWin32 ( resolvedTail , ! resolvedAbsolute ) ; return resolvedDevice + ( resolvedAbsolute ? '\\' : '' ) + resolvedTail || '.' ; }


Input: It will solve the relative path from from to to for instance : from = C : \\ orandea \\ test \\ aaa to = C : \\ orandea \\ impl \\ bbb The output of the function should be : .. \\ .. \\ impl \\ bbb [CODESPLIT] function relative ( from , to ) { assertPath ( from ) ; assertPath ( to ) ; if ( from === to ) return '' ; var fromOrig = win32 . resolve ( from ) ; var toOrig = win32 . resolve ( to ) ; if ( fromOrig === toOrig ) return '' ; from = fromOrig . toLowerCase ( ) ; to = toOrig . toLowerCase ( ) ; if ( from === to ) return '' ; // Trim any leading backslashes var fromStart = 0 ; for ( ; fromStart < from . length ; ++ fromStart ) { if ( from . charCodeAt ( fromStart ) !== 92 /*\*/ ) break ; } // Trim trailing backslashes (applicable to UNC paths only) var fromEnd = from . length ; for ( ; fromEnd - 1 > fromStart ; -- fromEnd ) { if ( from . charCodeAt ( fromEnd - 1 ) !== 92 /*\*/ ) break ; } var fromLen = fromEnd - fromStart ; // Trim any leading backslashes var toStart = 0 ; for ( ; toStart < to . length ; ++ toStart ) { if ( to . charCodeAt ( toStart ) !== 92 /*\*/ ) break ; } // Trim trailing backslashes (applicable to UNC paths only) var toEnd = to . length ; for ( ; toEnd - 1 > toStart ; -- toEnd ) { if ( to . charCodeAt ( toEnd - 1 ) !== 92 /*\*/ ) break ; } var toLen = toEnd - toStart ; // Compare paths to find the longest common path from root var length = fromLen < toLen ? fromLen : toLen ; var lastCommonSep = - 1 ; var i = 0 ; for ( ; i <= length ; ++ i ) { if ( i === length ) { if ( toLen > length ) { if ( to . charCodeAt ( toStart + i ) === 92 /*\*/ ) { // We get here if `from` is the exact base path for `to`. // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' return toOrig . slice ( toStart + i + 1 ) ; } else if ( i === 2 ) { // We get here if `from` is the device root. // For example: from='C:\\'; to='C:\\foo' return toOrig . slice ( toStart + i ) ; } } if ( fromLen > length ) { if ( from . charCodeAt ( fromStart + i ) === 92 /*\*/ ) { // We get here if `to` is the exact base path for `from`. // For example: from='C:\\foo\\bar'; to='C:\\foo' lastCommonSep = i ; } else if ( i === 2 ) { // We get here if `to` is the device root. // For example: from='C:\\foo\\bar'; to='C:\\' lastCommonSep = 3 ; } } break ; } var fromCode = from . charCodeAt ( fromStart + i ) ; var toCode = to . charCodeAt ( toStart + i ) ; if ( fromCode !== toCode ) break ; else if ( fromCode === 92 /*\*/ ) lastCommonSep = i ; } // We found a mismatch before the first common path separator was seen, so // return the original `to`. // TODO: do this just for device roots (and not UNC paths)? if ( i !== length && lastCommonSep === - 1 ) { if ( toStart > 0 ) return toOrig . slice ( toStart ) ; else return toOrig ; } var out = '' ; if ( lastCommonSep === - 1 ) lastCommonSep = 0 ; // Generate the relative path based on the path difference between `to` and // `from` for ( i = fromStart + lastCommonSep + 1 ; i <= fromEnd ; ++ i ) { if ( i === fromEnd || from . charCodeAt ( i ) === 92 /*\*/ ) { if ( out . length === 0 ) out += '..' ; else out += '\\..' ; } } // Lastly, append the rest of the destination (`to`) path that comes after // the common path parts if ( out . length > 0 ) return out + toOrig . slice ( toStart + lastCommonSep , toEnd ) ; else { toStart += lastCommonSep ; if ( toOrig . charCodeAt ( toStart ) === 92 /*\*/ ) ++ toStart ; return toOrig . slice ( toStart , toEnd ) ; } }


Input: path . resolve ( [ from ... ] to ) [CODESPLIT] function resolve ( ) { var resolvedPath = '' ; var resolvedAbsolute = false ; var cwd ; for ( var i = arguments . length - 1 ; i >= - 1 && ! resolvedAbsolute ; i -- ) { var path ; if ( i >= 0 ) path = arguments [ i ] ; else { if ( cwd === undefined ) cwd = process . cwd ( ) ; path = cwd ; } assertPath ( path ) ; // Skip empty entries if ( path . length === 0 ) { continue ; } resolvedPath = path + '/' + resolvedPath ; resolvedAbsolute = path . charCodeAt ( 0 ) === 47 /*/*/ ; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeStringPosix ( resolvedPath , ! resolvedAbsolute ) ; if ( resolvedAbsolute ) { if ( resolvedPath . length > 0 ) return '/' + resolvedPath ; else return '/' ; } else if ( resolvedPath . length > 0 ) { return resolvedPath ; } else { return '.' ; } }


Input: / * Gets default options and merges with user options if any . [CODESPLIT] function ( options ) { var defaults = { 'method' : 'get' , 'data' : null , 'needleRetry' : null , 'rule' : { 'second' : 1 } } ; if ( ! options ) { return defaults ; } return R . merge ( defaults , options ) ; }


Input: / * ==================================================== - adds a filter ( input ) for each column ( td ) - adds button on last column ===================================================== [CODESPLIT] function AddRow ( id , n ) { var t = document . getElementById ( id ) ; var fltrow = t . insertRow ( 0 ) ; var inpclass = "flt" ; for ( var i = 0 ; i < n ; i ++ ) { var fltcell = fltrow . insertCell ( i ) ; var inp = document . createElement ( "input" ) ; inp . setAttribute ( "id" , "flt" + i + "_" + id ) ; inp . setAttribute ( "type" , "text" ) ; inp . setAttribute ( "class" , i == n - 1 ? "flt_s" : "flt" ) ; inp . setAttribute ( 'placeholder' , 'Filter' ) ; inp . addEventListener ( 'keyup' , Filter ) ; fltcell . appendChild ( inp ) ; } }


Input: / * ==================================================== - returns text + text of child nodes of a cell ===================================================== [CODESPLIT] function getCellText ( n ) { var s = "" ; var enfants = n . childNodes ; for ( var i = 0 ; i < enfants . length ; i ++ ) { var child = enfants [ i ] ; if ( child . nodeType == 3 ) s += child . data ; else s += getCellText ( child ) ; } return s . toLowerCase ( ) ; }


Input: / * ==================================================== - Checks if id exists and is a table - Calls fn that adds inputs and button ===================================================== [CODESPLIT] function setFilterGrid ( id , ref_row ) { if ( typeof window === 'undefined' || typeof document === 'undefined' ) return ; var tbl = document . getElementById ( id ) ; if ( tbl && tbl . nodeName . toLowerCase ( ) === "table" ) { TblId . push ( id ) ; ref_row = ref_row === undefined ? StartRow . push ( 2 ) : StartRow . push ( ref_row + 2 ) ; //let ncells = getCellsNb(id, ref_row); // AddRow(id, ncells); } }


Input: / * ==================================================== - gets search strings from this . SearchFlt array - retrieves data from each td in every single tr and compares to search string for current column - tr is hidden if all search strings are not found ===================================================== [CODESPLIT] function Filter ( e ) { if ( typeof document === 'undefined' ) return ; var id = e . target . getAttribute ( "id" ) . split ( "_" ) [ 1 ] ; var SearchFlt = getFilters ( id ) ; var t = document . getElementById ( id ) ; var SearchArgs = [ ] ; var ncells = getCellsNb ( id ) ; for ( var i in SearchFlt ) { SearchArgs . push ( document . getElementById ( SearchFlt [ i ] ) . value . toLowerCase ( ) ) ; } var start_row = getStartRow ( id ) ; var row = t . getElementsByTagName ( "tr" ) ; for ( var k = start_row ; k < row . length ; k ++ ) { /*** if table already filtered some rows are not visible ***/ if ( row [ k ] . style . display === "none" ) row [ k ] . style . display = "" ; var cell = getChildElms ( row [ k ] ) . childNodes ; var nchilds = cell . length ; var isRowValid = true ; if ( nchilds === ncells ) { // checks if row has exact cell # var cell_value = [ ] ; var occurence = [ ] ; for ( var j = 0 ; j < nchilds ; j ++ ) // this loop retrieves cell data { var cell_data = getCellText ( cell [ j ] ) ; cell_value . push ( cell_data ) ; if ( SearchArgs [ j ] !== "" ) { occurence [ j ] = cell_data . split ( SearchArgs [ j ] ) . length ; } } //for j for ( var _t = 0 ; _t < ncells ; _t ++ ) { if ( SearchArgs [ _t ] !== "" && occurence [ _t ] < 2 ) { isRowValid = false ; } } //for t } //if if ( isRowValid === false ) row [ k ] . style . display = "none" ; else row [ k ] . style . display = "" ; } // for k }


Input: Set global variables on worker & main threads else node [CODESPLIT] function setAppConsts ( ) { var mergedConstants = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : ( 0 , _seamlessImmutable2 . default ) ( appConsts ) ; // set node app consts if ( typeof self === 'undefined' && typeof global !== 'undefined' ) { global . appConsts = global . appConsts ? _seamlessImmutable2 . default . merge ( global . appConsts , mergedConstants ) : mergedConstants ; return global . appConsts ; } else if ( typeof self !== 'undefined' ) { // set main & worker threads self . appConsts = self . appConsts ? _seamlessImmutable2 . default . merge ( self . appConsts , mergedConstants ) : mergedConstants ; return self . appConsts ; } return { } ; }


Input: Split a string to an array . [CODESPLIT] function splitTo ( ) { let to = arguments . length <= 0 || arguments [ 0 ] === undefined ? '' : arguments [ 0 ] ; if ( / # / . test ( to ) ) { return to . split ( '#' ) ; } return [ ] ; }


Input: Parse the arguments and return an special array . [CODESPLIT] function parseArgs ( ) { for ( var _len = arguments . length , args = Array ( _len ) , _key = 0 ; _key < _len ; _key ++ ) { args [ _key ] = arguments [ _key ] ; } const l = args . length ; const last = args [ l - 1 ] ; let cb , opts , paths ; if ( _lodash2 . default . isFunction ( last ) ) { cb = last ; args . pop ( ) ; // don't remove this semicolon var _parseArgs = parseArgs ( ... args ) ; var _parseArgs2 = _slicedToArray ( _parseArgs , 2 ) ; paths = _parseArgs2 [ 0 ] ; opts = _parseArgs2 [ 1 ] ; } else if ( _lodash2 . default . isObject ( last ) && ! Array . isArray ( last ) ) { opts = last ; args . pop ( ) ; paths = args ; } else if ( ! last && l > 0 ) { args . pop ( ) ; return parseArgs ( ... args ) ; } else { paths = args ; } return [ _lodash2 . default . compact ( _lodash2 . default . flatten ( paths , true ) ) , opts || { } , cb ] ; }


Input: ensures that the system repository is in place creates it if doesn t exist [CODESPLIT] function ( cb ) { fse . readFile ( systemsJsonPath , 'utf8' , function ( err , data ) { if ( err ) { if ( err . code !== 'ENOENT' ) { return cb ( err ) ; } fse . mkdirpSync ( sysRepoPath ) ; fse . writeFileSync ( systemsJsonPath , JSON . stringify ( blank , null , 2 ) , 'utf8' ) ; return git . createRepository ( sysRepoPath , 'system' , 'system@nfd.com' , function ( err_ ) { _systems = blank ; cb ( err_ ) ; } ) ; } _systems = JSON . parse ( data ) ; cb ( ) ; } ) ; }


Input: register a system [CODESPLIT] function ( user , namespace , name , repoName , repoPath , systemId , cb ) { if ( ! _systems [ systemId ] ) { _systems [ systemId ] = { name : name , namespace : namespace , repoName : repoName , repoPath : repoPath } ; fse . writeFileSync ( systemsJsonPath , JSON . stringify ( _systems , null , 2 ) , 'utf8' ) ; git . commit ( sysRepoPath , 'registered system: ' + repoPath , user . name , user . email , cb ) ; } else { cb ( null ) ; } }


Input: unregister a system [CODESPLIT] function ( user , systemId , cb ) { if ( ! _systems [ systemId ] ) { return cb ( ) ; } var newSystems = _ . clone ( _systems ) ; delete newSystems [ systemId ] ; fse . writeFileSync ( systemsJsonPath , JSON . stringify ( newSystems , null , 2 ) , 'utf8' ) ; _systems = newSystems ; git . commit ( sysRepoPath , 'unregistered system: ' + systemId , user . name , user . email , cb ) ; }


Input: convert identifier into full system guid using : 1 ) exact match on key 2 ) partial match on key 3 ) partial match on name [CODESPLIT] function ( identifier ) { identifier = identifier . replace ( / [.+] / g , function ( match ) { return '\\' + match ; } ) ; var re = new RegExp ( '^' + identifier + '.*' , [ 'i' ] ) ; var systemId ; systemId = _ . find ( _ . keys ( _systems ) , function ( system ) { return system === identifier ; } ) ; if ( ! systemId ) { systemId = _ . find ( _ . keys ( _systems ) , function ( system ) { return re . test ( system ) ; } ) ; } if ( ! systemId ) { systemId = _ . find ( _ . keys ( _systems ) , function ( system ) { return re . test ( _systems [ system ] . name ) ; } ) ; } return systemId ; }


Input: Init the object construct and process DOM [CODESPLIT] function ( ) { var domWrapper ; this . _children = [ ] ; this . _createRootHtml ( ) ; domWrapper = utils . html . parseHTML ( this . html ) ; if ( domWrapper . childNodes . length > 1 ) { throw new Error ( "Component should have only one root element" ) ; } this . root = domWrapper . firstChild ; this . processInstance ( ) ; }


Input: Process DOM using defined DOM processors [CODESPLIT] function ( ) { var i , elements , element , value ; if ( this . _root ) { ( this . $meta . domProcessors || [ ] ) . forEach ( function ( processor ) { elements = this . _root . querySelectorAll ( "[" + processor . attribute + "]" ) ; for ( i = 0 ; i < elements . length ; i ++ ) { element = elements [ i ] ; value = element . getAttribute ( processor . attribute ) ; processor . process ( this , element , value ) ; } } , this ) ; } }


Input: Add a child component [CODESPLIT] function ( child ) { this . _validateChild ( child ) ; if ( child . parent ) { child . parent . remove ( child ) ; } child . parent = this ; this . _children . push ( child ) ; this . root . appendChild ( child . root ) ; if ( this . __fastinject__ ) { this . __fastinject__ ( child ) ; } // otherwise it will be injected when __fastinject__ is set }


Input: Remove child component [CODESPLIT] function ( child ) { var index = this . _children . indexOf ( child ) ; if ( index !== - 1 ) { this . _children . splice ( index , 1 ) ; child . root . parentNode . removeChild ( child . root ) ; child . destroy ( ) ; } }


Input: Attaches a component by replacing the provided element . Element must be an element inside the parent component . [CODESPLIT] function ( child , element , root ) { this . _children . push ( child ) ; ( root || this . root ) . insertBefore ( child . root , element ) ; ( root || this . root ) . removeChild ( element ) ; }


Input: ensures that system has all required files [CODESPLIT] function ( repoPath , doc , done ) { generify ( path . join ( __dirname , 'template' ) , repoPath , { name : doc . name , namespace : doc . namespace , id : doc . id } , done ) ; }


Input: checks if a directory is a system ( has all the required files and correct system . json and system . js [CODESPLIT] function ( repoPath ) { var sys ; if ( fse . existsSync ( path . join ( repoPath , 'system.js' ) ) ) { // TODO extract in its own module sys = require ( repoPath + '/system.js' ) ; delete require . cache [ repoPath + '/system.js' ] ; } if ( ! sys ) { return new Error ( 'missing system.js, is this an nscale repository?' ) ; } if ( ! sys . name ) { return new Error ( 'missing name in system.js, correct and try again' ) ; } if ( ! sys . namespace ) { return new Error ( 'missing namespace in system.js, correct and try again' ) ; } if ( ! sys . id ) { return new Error ( 'missing id in system.js, correct and try again' ) ; } }


Input: timeline format [ { user : user ts : new Date () type : entryType details : details } ... custom values can be provided through the details object TODO change the format to include all the details in the main object [CODESPLIT] function ( user , systemId , entryType , details , cb ) { var file = path . join ( options . timelinesRoot , findSystem ( systemId ) ) ; if ( typeof details === 'function' ) { cb = details ; details = { } ; } else if ( ! details ) { details = { } ; } var entry = { v : 0 , user : user , ts : new Date ( ) , type : entryType , details : details } ; fs . writeFile ( file , JSON . stringify ( entry ) + '\n' , { flag : 'a' } , function ( ) { // error is swallowed, as this file does not really matter cb ( ) ; } ) ; }


Input: make a commit to local git repository TODO : implement seperate push functionality TODO : replace with git hub id [CODESPLIT] function ( user , systemId , message , cb ) { logger . info ( 'committing revision: ' + systemId + ', ' + message ) ; var repoPath = _meta . repoPath ( systemId ) ; git . commit ( repoPath , message , user . name , user . email , cb ) ; }


Input: create a new system repository [CODESPLIT] function ( user , namespace , name , cwd , cb ) { var repoName = name ; var doc = _ . extend ( { } , blank ) ; var repoPath = path . join ( cwd , repoName ) ; doc . name = name ; doc . namespace = namespace ; doc . id = uuid . v4 ( ) ; if ( ! fse . existsSync ( repoPath ) ) { fse . mkdirpSync ( repoPath ) ; initNscaleFiles ( repoPath , doc , function ( ) { git . createRepository ( repoPath , user . name , user . email , function ( err ) { if ( err ) { return cb ( err ) ; } _meta . register ( user , namespace , name , repoName , cwd + '/' + repoName , doc . id , function ( err ) { writeTimeline ( user , doc . id , 'create' , 'system created' , function ( ) { // swallow any errors here cb ( err , { id : doc . id , err : err } ) ; } ) ; } ) ; } ) ; } ) ; } else { cb ( null , { id : _meta . repoId ( repoName ) , err : null } ) ; } }


Input: create a new system by linking from local file system [CODESPLIT] function ( user , path_ , cwd , cb ) { var repoPath = path . resolve ( cwd , path_ ) ; var sys ; var validationError = validateSystem ( repoPath ) ; if ( validationError ) { return cb ( validationError ) ; } sys = require ( repoPath + '/system.js' ) ; delete require . cache [ repoPath + '/system.js' ] ; _meta . register ( user , sys . namespace , sys . name , path . basename ( repoPath ) , repoPath , sys . id , function ( err ) { writeTimeline ( user , sys . id , 'link' , 'system linked' , function ( ) { cb ( err , { id : sys . id , err : err } ) ; } ) ; } ) ; }


Input: unlink system from the daemon [CODESPLIT] function ( user , systemId , cb ) { writeTimeline ( user , systemId , 'system unlinked' , function ( ) { // swallow any errors here _meta . unregister ( user , systemId , function ( err ) { cb ( err ) ; } ) ; } ) ; }


Input: commit a new version of the system the head of the commit log may be ahead of the actual deployed version of the system [CODESPLIT] function ( systemId , fileName , contents , cb ) { var repoPath = _meta . repoPath ( systemId ) ; fse . writeFile ( path . join ( repoPath , fileName ) , contents , 'utf8' , cb ) ; }


Input: get the head revision for a system [CODESPLIT] function ( systemId , target , cb ) { listRevisions ( systemId , function ( err , revs ) { if ( err ) { return cb ( err ) ; } getRevision ( systemId , revs [ 0 ] . id , target , cb ) ; } ) ; }


Input: get the head revision id for a system [CODESPLIT] function ( systemId , cb ) { listRevisions ( systemId , function ( err , revs ) { cb ( err , revs && revs [ 0 ] && revs [ 0 ] . id ) ; } ) ; }


Input: get the head revision id for a system [CODESPLIT] function ( systemId , cb ) { listRevisions ( systemId , function ( err , revs ) { if ( revs [ 0 ] . id === EDITS ) { cb ( err , revs && revs [ 1 ] && revs [ 1 ] . id ) ; } else { cb ( err , revs && revs [ 0 ] && revs [ 0 ] . id ) ; } } ) ; }


Input: get a revision from the history with a specific version number [CODESPLIT] function ( systemId , revisionId , target , cb ) { var repoPath = _meta . repoPath ( systemId ) ; git . getFileRevision ( repoPath , revisionId , target + '.json' , function ( err , rev ) { if ( err ) { return cb ( err ) ; } var s ; try { s = JSON . parse ( rev ) ; } catch ( e ) { return cb ( new Error ( 'invalid system definition: ' + e . message ) , null ) ; } cb ( err , s ) ; } ) ; }


Input: get a revision from the history with abbreviation support [CODESPLIT] function ( systemId , revisionId , target , cb ) { if ( revisionId === EDITS ) { _getOnDiskVersion ( systemId , revisionId , target , cb ) ; } else { findRevision ( systemId , revisionId , function ( err , rev ) { if ( err ) { return cb ( err ) ; } if ( rev === EDITS ) { _getOnDiskVersion ( systemId , revisionId , target , cb ) ; } else { _getRevision ( systemId , rev , target , cb ) ; } } ) ; } }


Input: / * tesnt this to fuck and PR and release move onto proxy - must be testing it tomorrow night app dynamics only - load to AJ set the currently deployed revision there will only ever be one deployed revision clear the currently deployed flag and set the deployed flag against the specified revision [CODESPLIT] function ( user , systemId , revisionId , env , cb ) { var repoPath = _meta . repoPath ( systemId ) ; var removeTag ; var addTag ; var revId ; getComittedHeadRevisionId ( systemId , function ( err , comittedHeadId ) { if ( revisionId === EDITS ) { removeTag = baseTag + env ; addTag = editsTag + env ; revId = comittedHeadId ; } else { addTag = baseTag + env ; removeTag = editsTag + env ; revId = revisionId ; } ngit . Repository . open ( repoPath , function ( err , repo ) { if ( err ) { return cb ( err ) ; } ngit . Reference . remove ( repo , removeTag ) ; repo . getCommit ( revId , function ( err , commit ) { if ( err ) { return cb ( err ) ; } var now = Math . round ( Date . now ( ) / 1000 ) ; var author = ngit . Signature . create ( user . name , user . email , now , 0 ) ; ngit . Reference . create ( repo , addTag , commit , 1 , author , 'Tagged ' + addTag ) . then ( function ( ) { writeTimeline ( user , systemId , 'deployed revision' , revisionId , function ( ) { cb ( ) ; } ) ; } ) . catch ( cb ) ; } ) ; } ) ; } ) ; }


Input: get the currently deployed revision [CODESPLIT] function ( systemId , env , cb ) { var repoPath = _meta . repoPath ( systemId ) ; var tagName = baseTag + env ; var editsTagName = editsTag + env ; ngit . Repository . open ( repoPath , function ( err , repo ) { if ( err ) { return cb ( err ) ; } ngit . Reference . nameToId ( repo , tagName , function ( err , head ) { if ( err && ( ! err . message || err . message . indexOf ( 'not found' ) === - 1 ) ) { return cb ( err ) ; } if ( head ) { cb ( null , head . toString ( ) ) ; } else { ngit . Reference . nameToId ( repo , editsTagName , function ( err ) { if ( err ) { return cb ( err ) ; } cb ( null , EDITS ) ; } ) ; } } ) ; } ) ; }


Input: list all of the available revisions in the system [CODESPLIT] function ( systemId , cb ) { var repoPath = _meta . repoPath ( systemId ) ; getDeployedTargets ( systemId , function ( err , targets ) { if ( err ) { return cb ( err ) ; } git . listRevisions ( repoPath , function ( err , revisions ) { revisions . forEach ( function ( revision ) { var deployedTo = _ . find ( targets , function ( target ) { return target . commit === revision . id ; } ) ; if ( deployedTo ) { revision . deployedTo = deployedTo . env ; } } ) ; cb ( err , revisions ) ; } ) ; } ) ; }


Input: find revision id by parital or full identifier [CODESPLIT] function ( systemId , identifier , cb ) { var re = new RegExp ( '^' + identifier + '.*' , [ 'i' ] ) ; var revision ; if ( identifier !== 'head' && identifier !== 'latest' ) { listRevisions ( systemId , function ( err , revisions ) { revision = _ . find ( revisions , function ( revision ) { return re . test ( revision . id ) ; } ) ; if ( revision ) { cb ( err , revision . id ) ; } else { cb ( new Error ( 'revision not found' ) ) ; } } ) ; } else { getHeadRevisionId ( systemId , cb ) ; } }


Input: Import javascript depending on the * mode * . We currently support sprite and data - uri modes ( NO basic image mode ) . [CODESPLIT] function ( app , parentAddon ) { this . _super . included ( app ) ; var target = ( parentAddon || app ) ; target . import ( target . bowerDirectory + '/emojify/dist/js/emojify.js' ) ; if ( _emojiConfig . mode === 'sprites' ) { var destSpriteDir = 'images/sprites' ; var spritePath = '/emojify/dist/images/sprites/' ; target . import ( target . bowerDirectory + spritePath + 'emojify.png' , { destDir : destSpriteDir } ) ; target . import ( target . bowerDirectory + spritePath + 'emojify@2x.png' , { destDir : destSpriteDir } ) ; } }


Input: Allows custom configuration from environment [CODESPLIT] function ( environment , baseConfig ) { if ( 'emoji' in baseConfig ) { if ( ! baseConfig . emoji ) { _emojiConfig = false ; } else { Object . keys ( _defaultEmojiConfig ) . forEach ( function ( key ) { _emojiConfig [ key ] = baseConfig . emoji . hasOwnProperty ( key ) ? baseConfig . emoji [ key ] : _defaultEmojiConfig [ key ] ; } ) ; } } else { _emojiConfig = _defaultEmojiConfig ; } if ( environment === 'development' ) { return { emoji : _emojiConfig , contentSecurityPolicy : { 'script-src' : "'self' 'unsafe-eval' 'unsafe-inline'" } } ; } return { emoji : _emojiConfig } ; }


Input: Import style depending on the * mode * . We currently support sprite and data - uri modes ( NO basic image mode ) . [CODESPLIT] function ( ) { var emojiDataURIPath = path . join ( this . app . bowerDirectory , 'emojify/dist/css/data-uri/emojify.css' ) , emojiSpritesPath = path . join ( this . app . bowerDirectory , 'emojify/dist/css/sprites/emojify.css' ) ; if ( _emojiConfig . mode === 'data-uri' ) { this . app . import ( emojiDataURIPath ) ; } else { this . app . import ( emojiSpritesPath ) ; } }


Input: Determine the target containers - machine containers that have a proxy on them . [CODESPLIT] function ( analyzed ) { var containers = analyzed . topology . containers ; var targets = [ ] ; _ . each ( containers , function ( c ) { if ( c . containerDefinitionId . indexOf ( '__proxy' ) === 0 ) { var cdef = _ . find ( analyzed . containerDefinitions , function ( cdef ) { return cdef . id === c . containerDefinitionId ; } ) ; targets . push ( { containerDef : cdef , container : c } ) ; } } ) ; return targets ; }


Input: / * Function : getCollection Looks for a collection object attached to the current class . If one is not found it traverses the ancestor tree looking for the closest class that has a collection object associated with it and returns that collection . [CODESPLIT] function ( cls ) { if ( this . collection ) { return this . collection ; } cls = ( cls ) ? this . superclass ( cls ) : this ; while ( cls ) { if ( cls . collection ) { this . collection = cls . collection ; return cls . collection ; } } return false ; }


Input: Create a new Relation . [CODESPLIT] function ( model , relation , options ) { var type = ! _ . isString ( relation . type ) ? relation . type : Backbone [ relation . type ] || this . getObjectByName ( relation . type ) ; if ( type && type . prototype instanceof Backbone . Relation ) { new type ( model , relation , options ) ; // Also pushes the new Relation into `model._relations` } else { Backbone . Relational . showWarnings && typeof console !== 'undefined' && console . warn ( 'Relation=%o; missing or invalid relation type!' , relation ) ; } }


Input: Check if the given modelType is registered as another model s subModel . If so add it to the super model s _subModels and set the modelType s _superModel _subModelTypeName and _subModelTypeAttribute . [CODESPLIT] function ( modelType ) { _ . find ( this . _subModels , function ( subModelDef ) { return _ . find ( subModelDef . subModels || [ ] , function ( subModelTypeName , typeValue ) { var subModelType = this . getObjectByName ( subModelTypeName ) ; if ( modelType === subModelType ) { // Set 'modelType' as a child of the found superModel subModelDef . superModelType . _subModels [ typeValue ] = modelType ; // Set '_superModel', '_subModelTypeValue', and '_subModelTypeAttribute' on 'modelType'. modelType . _superModel = subModelDef . superModelType ; modelType . _subModelTypeValue = typeValue ; modelType . _subModelTypeAttribute = subModelDef . superModelType . prototype . subModelTypeAttribute ; return true ; } } , this ) ; } , this ) ; }


Input: Add a reverse relation . Is added to the relations property on model s prototype and to existing instances of model in the store as well . [CODESPLIT] function ( relation ) { var exists = _ . any ( this . _reverseRelations , function ( rel ) { return _ . all ( relation || [ ] , function ( val , key ) { return val === rel [ key ] ; } ) ; } ) ; if ( ! exists && relation . model && relation . type ) { this . _reverseRelations . push ( relation ) ; this . _addRelation ( relation . model , relation ) ; this . retroFitRelation ( relation ) ; } }


Input: Deposit a relation for which the relatedModel can t be resolved at the moment . [CODESPLIT] function ( relation ) { var exists = _ . any ( this . _orphanRelations , function ( rel ) { return _ . all ( relation || [ ] , function ( val , key ) { return val === rel [ key ] ; } ) ; } ) ; if ( ! exists && relation . model && relation . type ) { this . _orphanRelations . push ( relation ) ; } }


Input: Try to initialize any _orphanRelation s [CODESPLIT] function ( ) { // Make sure to operate on a copy since we're removing while iterating _ . each ( this . _orphanRelations . slice ( 0 ) , function ( rel ) { var relatedModel = Backbone . Relational . store . getObjectByName ( rel . relatedModel ) ; if ( relatedModel ) { this . initializeRelation ( null , rel ) ; this . _orphanRelations = _ . without ( this . _orphanRelations , rel ) ; } } , this ) ; }


Input: Add a relation to all existing instances of relation . model in the store [CODESPLIT] function ( relation ) { var coll = this . getCollection ( relation . model , false ) ; coll && coll . each ( function ( model ) { if ( ! ( model instanceof relation . model ) ) { return ; } new relation . type ( model , relation ) ; } , this ) ; }


Input: Find the Store s collection for a certain type of model . [CODESPLIT] function ( type , create ) { if ( type instanceof Backbone . RelationalModel ) { type = type . constructor ; } var rootModel = type ; while ( rootModel . _superModel ) { rootModel = rootModel . _superModel ; } var coll = _ . find ( this . _collections , function ( item ) { return item . model === rootModel ; } ) ; if ( ! coll && create !== false ) { coll = this . _createCollection ( rootModel ) ; } return coll ; }


Input: Find a model type on one of the modelScopes by name . Names are split on dots . [CODESPLIT] function ( name ) { var parts = name . split ( '.' ) , type = null ; _ . find ( this . _modelScopes , function ( scope ) { type = _ . reduce ( parts || [ ] , function ( memo , val ) { return memo ? memo [ val ] : undefined ; } , scope ) ; if ( type && type !== scope ) { return true ; } } , this ) ; return type ; }


Input: Find the attribute that is to be used as the id on a given object [CODESPLIT] function ( type , item ) { var id = _ . isString ( item ) || _ . isNumber ( item ) ? item : null ; if ( id === null ) { if ( item instanceof Backbone . RelationalModel ) { id = item . id ; } else if ( _ . isObject ( item ) ) { id = item [ type . prototype . idAttribute ] ; } } // Make all falsy values `null` (except for 0, which could be an id.. see '/issues/179') if ( ! id && id !== 0 ) { id = null ; } return id ; }


Input: Find a specific model of a certain type in the store [CODESPLIT] function ( type , item ) { var id = this . resolveIdForItem ( type , item ) ; var coll = this . getCollection ( type ) ; // Because the found object could be of any of the type's superModel // types, only return it if it's actually of the type asked for. if ( coll ) { var obj = coll . get ( id ) ; if ( obj instanceof type ) { return obj ; } } return null ; }


Input: Add a model to its appropriate collection . Retain the original contents of model . collection . [CODESPLIT] function ( model ) { var coll = this . getCollection ( model ) ; if ( coll ) { var modelColl = model . collection ; coll . add ( model ) ; this . listenTo ( model , 'destroy' , this . unregister , this ) ; this . listenTo ( model , 'relational:unregister' , this . unregister , this ) ; model . collection = modelColl ; } }


Input: Check if the given model may use the given id [CODESPLIT] function ( model , id ) { var coll = this . getCollection ( model ) , duplicate = coll && coll . get ( id ) ; if ( duplicate && model !== duplicate ) { if ( Backbone . Relational . showWarnings && typeof console !== 'undefined' ) { console . warn ( 'Duplicate id! Old RelationalModel=%o, new RelationalModel=%o' , duplicate , model ) ; } throw new Error ( "Cannot instantiate more than one Backbone.RelationalModel with the same id per type!" ) ; } }


Input: Remove a model from the store . [CODESPLIT] function ( model , collection , options ) { this . stopListening ( model ) ; var coll = this . getCollection ( model ) ; coll && coll . remove ( model , options ) ; }


Input: Check several pre - conditions . [CODESPLIT] function ( ) { var i = this . instance , k = this . key , m = this . model , rm = this . relatedModel , warn = Backbone . Relational . showWarnings && typeof console !== 'undefined' ; if ( ! m || ! k || ! rm ) { warn && console . warn ( 'Relation=%o: missing model, key or relatedModel (%o, %o, %o).' , this , m , k , rm ) ; return false ; } // Check if the type in 'model' inherits from Backbone.RelationalModel if ( ! ( m . prototype instanceof Backbone . RelationalModel ) ) { warn && console . warn ( 'Relation=%o: model does not inherit from Backbone.RelationalModel (%o).' , this , i ) ; return false ; } // Check if the type in 'relatedModel' inherits from Backbone.RelationalModel if ( ! ( rm . prototype instanceof Backbone . RelationalModel ) ) { warn && console . warn ( 'Relation=%o: relatedModel does not inherit from Backbone.RelationalModel (%o).' , this , rm ) ; return false ; } // Check if this is not a HasMany, and the reverse relation is HasMany as well if ( this instanceof Backbone . HasMany && this . reverseRelation . type === Backbone . HasMany ) { warn && console . warn ( 'Relation=%o: relation is a HasMany, and the reverseRelation is HasMany as well.' , this ) ; return false ; } // Check if we're not attempting to create a relationship on a `key` that's already used. if ( i && _ . keys ( i . _relations ) . length ) { var existing = _ . find ( i . _relations , function ( rel ) { return rel . key === k ; } , this ) ; if ( existing ) { warn && console . warn ( 'Cannot create relation=%o on %o for model=%o: already taken by relation=%o.' , this , k , i , existing ) ; return false ; } } return true ; }


Input: Set the related model ( s ) for this relation [CODESPLIT] function ( related ) { this . related = related ; this . instance . acquire ( ) ; this . instance . attributes [ this . key ] = related ; this . instance . release ( ) ; }


Input: Determine if a relation ( on a different RelationalModel ) is the reverse relation of the current one . [CODESPLIT] function ( relation ) { return relation . instance instanceof this . relatedModel && this . reverseRelation . key === relation . key && this . key === relation . reverseRelation . key ; }


Input: Get the reverse relations ( pointing back to this . key on this . instance ) for the currently related model ( s ) . [CODESPLIT] function ( model ) { var reverseRelations = [ ] ; // Iterate over 'model', 'this.related.models' (if this.related is a Backbone.Collection), or wrap 'this.related' in an array. var models = ! _ . isUndefined ( model ) ? [ model ] : this . related && ( this . related . models || [ this . related ] ) ; _ . each ( models || [ ] , function ( related ) { _ . each ( related . getRelations ( ) || [ ] , function ( relation ) { if ( this . _isReverseRelation ( relation ) ) { reverseRelations . push ( relation ) ; } } , this ) ; } , this ) ; return reverseRelations ; }


Input: When this . instance is destroyed cleanup our relations . Get reverse relation call removeRelated on each . [CODESPLIT] function ( ) { this . stopListening ( ) ; if ( this instanceof Backbone . HasOne ) { this . setRelated ( null ) ; } else if ( this instanceof Backbone . HasMany ) { this . setRelated ( this . _prepareCollection ( ) ) ; } _ . each ( this . getReverseRelations ( ) , function ( relation ) { relation . removeRelated ( this . instance ) ; } , this ) ; }


Input: Find related Models . [CODESPLIT] function ( options ) { var related = null ; options = _ . defaults ( { parse : this . options . parse } , options ) ; if ( this . keyContents instanceof this . relatedModel ) { related = this . keyContents ; } else if ( this . keyContents || this . keyContents === 0 ) { // since 0 can be a valid `id` as well var opts = _ . defaults ( { create : this . options . createModels } , options ) ; related = this . relatedModel . findOrCreate ( this . keyContents , opts ) ; } // Nullify `keyId` if we have a related model; in case it was already part of the relation if ( this . related ) { this . keyId = null ; } return related ; }


Input: Normalize and reduce keyContents to an id for easier comparison [CODESPLIT] function ( keyContents ) { this . keyContents = keyContents ; this . keyId = Backbone . Relational . store . resolveIdForItem ( this . relatedModel , this . keyContents ) ; }


Input: Event handler for change : <key > . If the key is changed notify old & new reverse relations and initialize the new relation . [CODESPLIT] function ( model , attr , options ) { // Don't accept recursive calls to onChange (like onChange->findRelated->findOrCreate->initializeRelations->addRelated->onChange) if ( this . isLocked ( ) ) { return ; } this . acquire ( ) ; options = options ? _ . clone ( options ) : { } ; // 'options.__related' is set by 'addRelated'/'removeRelated'. If it is set, the change // is the result of a call from a relation. If it's not, the change is the result of // a 'set' call on this.instance. var changed = _ . isUndefined ( options . __related ) , oldRelated = changed ? this . related : options . __related ; if ( changed ) { this . setKeyContents ( attr ) ; var related = this . findRelated ( options ) ; this . setRelated ( related ) ; } // Notify old 'related' object of the terminated relation if ( oldRelated && this . related !== oldRelated ) { _ . each ( this . getReverseRelations ( oldRelated ) , function ( relation ) { relation . removeRelated ( this . instance , null , options ) ; } , this ) ; } // Notify new 'related' object of the new relation. Note we do re-apply even if this.related is oldRelated; // that can be necessary for bi-directional relations if 'this.instance' was created after 'this.related'. // In that case, 'this.instance' will already know 'this.related', but the reverse might not exist yet. _ . each ( this . getReverseRelations ( ) , function ( relation ) { relation . addRelated ( this . instance , options ) ; } , this ) ; // Fire the 'change:<key>' event if 'related' was updated if ( ! options . silent && this . related !== oldRelated ) { var dit = this ; this . changed = true ; Backbone . Relational . eventQueue . add ( function ( ) { dit . instance . trigger ( 'change:' + dit . key , dit . instance , dit . related , options , true ) ; dit . changed = false ; } ) ; } this . release ( ) ; }


Input: If a new this . relatedModel appears in the store try to match it to the last set keyContents [CODESPLIT] function ( model , coll , options ) { if ( ( this . keyId || this . keyId === 0 ) && model . id === this . keyId ) { // since 0 can be a valid `id` as well this . addRelated ( model , options ) ; this . keyId = null ; } }


Input: Bind events and setup collectionKeys for a collection that is to be used as the backing store for a HasMany . If no collection is supplied a new collection will be created of the specified collectionType option . [CODESPLIT] function ( collection ) { if ( this . related ) { this . stopListening ( this . related ) ; } if ( ! collection || ! ( collection instanceof Backbone . Collection ) ) { var options = _ . isFunction ( this . options . collectionOptions ) ? this . options . collectionOptions ( this . instance ) : this . options . collectionOptions ; collection = new this . collectionType ( null , options ) ; } collection . model = this . relatedModel ; if ( this . options . collectionKey ) { var key = this . options . collectionKey === true ? this . options . reverseRelation . key : this . options . collectionKey ; if ( collection [ key ] && collection [ key ] !== this . instance ) { if ( Backbone . Relational . showWarnings && typeof console !== 'undefined' ) { console . warn ( 'Relation=%o; collectionKey=%s already exists on collection=%o' , this , key , this . options . collectionKey ) ; } } else if ( key ) { collection [ key ] = this . instance ; } } this . listenTo ( collection , 'relational:add' , this . handleAddition ) . listenTo ( collection , 'relational:remove' , this . handleRemoval ) . listenTo ( collection , 'relational:reset' , this . handleReset ) ; return collection ; }


Input: Find related Models . [CODESPLIT] function ( options ) { var related = null ; options = _ . defaults ( { parse : this . options . parse } , options ) ; // Replace 'this.related' by 'this.keyContents' if it is a Backbone.Collection if ( this . keyContents instanceof Backbone . Collection ) { this . _prepareCollection ( this . keyContents ) ; related = this . keyContents ; } // Otherwise, 'this.keyContents' should be an array of related object ids. // Re-use the current 'this.related' if it is a Backbone.Collection; otherwise, create a new collection. else { var toAdd = [ ] ; _ . each ( this . keyContents , function ( attributes ) { if ( attributes instanceof this . relatedModel ) { var model = attributes ; } else { // If `merge` is true, update models here, instead of during update. model = this . relatedModel . findOrCreate ( attributes , _ . extend ( { merge : true } , options , { create : this . options . createModels } ) ) ; } model && toAdd . push ( model ) ; } , this ) ; if ( this . related instanceof Backbone . Collection ) { related = this . related ; } else { related = this . _prepareCollection ( ) ; } // By now, both `merge` and `parse` will already have been executed for models if they were specified. // Disable them to prevent additional calls. related . set ( toAdd , _ . defaults ( { merge : false , parse : false } , options ) ) ; } // Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged') this . keyIds = _ . difference ( this . keyIds , _ . pluck ( related . models , 'id' ) ) ; return related ; }


Input: Normalize and reduce keyContents to a list of ids for easier comparison [CODESPLIT] function ( keyContents ) { this . keyContents = keyContents instanceof Backbone . Collection ? keyContents : null ; this . keyIds = [ ] ; if ( ! this . keyContents && ( keyContents || keyContents === 0 ) ) { // since 0 can be a valid `id` as well // Handle cases the an API/user supplies just an Object/id instead of an Array this . keyContents = _ . isArray ( keyContents ) ? keyContents : [ keyContents ] ; _ . each ( this . keyContents , function ( item ) { var itemId = Backbone . Relational . store . resolveIdForItem ( this . relatedModel , item ) ; if ( itemId || itemId === 0 ) { this . keyIds . push ( itemId ) ; } } , this ) ; } }


Input: Event handler for change : <key > . If the contents of the key are changed notify old & new reverse relations and initialize the new relation . [CODESPLIT] function ( model , attr , options ) { options = options ? _ . clone ( options ) : { } ; this . setKeyContents ( attr ) ; this . changed = false ; var related = this . findRelated ( options ) ; this . setRelated ( related ) ; if ( ! options . silent ) { var dit = this ; Backbone . Relational . eventQueue . add ( function ( ) { // The `changed` flag can be set in `handleAddition` or `handleRemoval` if ( dit . changed ) { dit . instance . trigger ( 'change:' + dit . key , dit . instance , dit . related , options , true ) ; dit . changed = false ; } } ) ; } }


Input: When a model is removed from a HasMany trigger remove on this . instance and notify reverse relations . ( should be HasOne which should be nullified ) [CODESPLIT] function ( model , coll , options ) { //console.debug('handleRemoval called; args=%o', arguments); options = options ? _ . clone ( options ) : { } ; this . changed = true ; _ . each ( this . getReverseRelations ( model ) , function ( relation ) { relation . removeRelated ( this . instance , null , options ) ; } , this ) ; var dit = this ; ! options . silent && Backbone . Relational . eventQueue . add ( function ( ) { dit . instance . trigger ( 'remove:' + dit . key , model , dit . related , options ) ; } ) ; }


Input: Override trigger to queue change and change : * events [CODESPLIT] function ( eventName ) { if ( eventName . length > 5 && eventName . indexOf ( 'change' ) === 0 ) { var dit = this , args = arguments ; Backbone . Relational . eventQueue . add ( function ( ) { if ( ! dit . _isInitialized ) { return ; } // Determine if the `change` event is still valid, now that all relations are populated var changed = true ; if ( eventName === 'change' ) { // `hasChanged` may have gotten reset by nested calls to `set`. changed = dit . hasChanged ( ) || dit . _attributeChangeFired ; dit . _attributeChangeFired = false ; } else { var attr = eventName . slice ( 7 ) , rel = dit . getRelation ( attr ) ; if ( rel ) { // If `attr` is a relation, `change:attr` get triggered from `Relation.onChange`. // These take precedence over `change:attr` events triggered by `Model.set`. // The relation sets a fourth attribute to `true`. If this attribute is present, // continue triggering this event; otherwise, it's from `Model.set` and should be stopped. changed = ( args [ 4 ] === true ) ; // If this event was triggered by a relation, set the right value in `this.changed` // (a Collection or Model instead of raw data). if ( changed ) { dit . changed [ attr ] = args [ 2 ] ; } // Otherwise, this event is from `Model.set`. If the relation doesn't report a change, // remove attr from `dit.changed` so `hasChanged` doesn't take it into account. else if ( ! rel . changed ) { delete dit . changed [ attr ] ; } } else if ( changed ) { dit . _attributeChangeFired = true ; } } changed && Backbone . Model . prototype . trigger . apply ( dit , args ) ; } ) ; } else { Backbone . Model . prototype . trigger . apply ( this , arguments ) ; } return this ; }


Input: Initialize Relations present in this . relations ; determine the type ( HasOne / HasMany ) then creates a new instance . Invoked in the first call so set ( which is made from the Backbone . Model constructor ) . [CODESPLIT] function ( options ) { this . acquire ( ) ; // Setting up relations often also involve calls to 'set', and we only want to enter this function once this . _relations = { } ; _ . each ( _ . result ( this , 'relations' ) || [ ] , function ( rel ) { Backbone . Relational . store . initializeRelation ( this , rel , options ) ; } , this ) ; this . _isInitialized = true ; this . release ( ) ; this . processQueue ( ) ; }


Input: When new values are set notify this model s relations ( also if options . silent is set ) . ( Relation . setRelated locks this model before calling set on it to prevent loops ) [CODESPLIT] function ( options ) { if ( this . _isInitialized && ! this . isLocked ( ) ) { _ . each ( this . _relations , function ( rel ) { // Update from data in `rel.keySource` if data got set in there, or `rel.key` otherwise var val = this . attributes [ rel . keySource ] || this . attributes [ rel . key ] ; if ( rel . related !== val ) { this . trigger ( 'relational:change:' + rel . key , this , val , options || { } ) ; } // Explicitly clear 'keySource', to prevent a leaky abstraction if 'keySource' differs from 'key'. if ( rel . keySource !== rel . key ) { delete rel . instance . attributes [ rel . keySource ] ; } } , this ) ; } }


Input: Retrieve related objects . [CODESPLIT] function ( key , options , refresh ) { // Set default `options` for fetch options = _ . extend ( { update : true , remove : false } , options ) ; var setUrl , requests = [ ] , rel = this . getRelation ( key ) , idsToFetch = rel && ( ( rel . keyIds && rel . keyIds . slice ( 0 ) ) || ( ( rel . keyId || rel . keyId === 0 ) ? [ rel . keyId ] : [ ] ) ) ; // On `refresh`, add the ids for current models in the relation to `idsToFetch` if ( refresh ) { var models = rel . related instanceof Backbone . Collection ? rel . related . models : [ rel . related ] ; _ . each ( models , function ( model ) { if ( model . id || model . id === 0 ) { idsToFetch . push ( model . id ) ; } } ) ; } if ( idsToFetch && idsToFetch . length ) { // Find (or create) a model for each one that is to be fetched var created = [ ] , models = _ . map ( idsToFetch , function ( id ) { var model = Backbone . Relational . store . find ( rel . relatedModel , id ) ; if ( ! model ) { var attrs = { } ; attrs [ rel . relatedModel . prototype . idAttribute ] = id ; model = rel . relatedModel . findOrCreate ( attrs , options ) ; created . push ( model ) ; } return model ; } , this ) ; // Try if the 'collection' can provide a url to fetch a set of models in one request. if ( rel . related instanceof Backbone . Collection && _ . isFunction ( rel . related . url ) ) { setUrl = rel . related . url ( models ) ; } // An assumption is that when 'Backbone.Collection.url' is a function, it can handle building of set urls. // To make sure it can, test if the url we got by supplying a list of models to fetch is different from // the one supplied for the default fetch action (without args to 'url'). if ( setUrl && setUrl !== rel . related . url ( ) ) { var opts = _ . defaults ( { error : function ( ) { var args = arguments ; _ . each ( created , function ( model ) { model . trigger ( 'destroy' , model , model . collection , options ) ; options . error && options . error . apply ( model , args ) ; } ) ; } , url : setUrl } , options ) ; requests = [ rel . related . fetch ( opts ) ] ; } else { requests = _ . map ( models , function ( model ) { var opts = _ . defaults ( { error : function ( ) { if ( _ . contains ( created , model ) ) { model . trigger ( 'destroy' , model , model . collection , options ) ; options . error && options . error . apply ( model , arguments ) ; } } } , options ) ; return model . fetch ( opts ) ; } , this ) ; } } return requests ; }


Input: Convert relations to JSON omits them when required [CODESPLIT] function ( options ) { // If this Model has already been fully serialized in this branch once, return to avoid loops if ( this . isLocked ( ) ) { return this . id ; } this . acquire ( ) ; var json = Backbone . Model . prototype . toJSON . call ( this , options ) ; if ( this . constructor . _superModel && ! ( this . constructor . _subModelTypeAttribute in json ) ) { json [ this . constructor . _subModelTypeAttribute ] = this . constructor . _subModelTypeValue ; } _ . each ( this . _relations , function ( rel ) { var related = json [ rel . key ] , includeInJSON = rel . options . includeInJSON , value = null ; if ( includeInJSON === true ) { if ( related && _ . isFunction ( related . toJSON ) ) { value = related . toJSON ( options ) ; } } else if ( _ . isString ( includeInJSON ) ) { if ( related instanceof Backbone . Collection ) { value = related . pluck ( includeInJSON ) ; } else if ( related instanceof Backbone . Model ) { value = related . get ( includeInJSON ) ; } // Add ids for 'unfound' models if includeInJSON is equal to (only) the relatedModel's `idAttribute` if ( includeInJSON === rel . relatedModel . prototype . idAttribute ) { if ( rel instanceof Backbone . HasMany ) { value = value . concat ( rel . keyIds ) ; } else if ( rel instanceof Backbone . HasOne ) { value = value || rel . keyId ; } } } else if ( _ . isArray ( includeInJSON ) ) { if ( related instanceof Backbone . Collection ) { value = [ ] ; related . each ( function ( model ) { var curJson = { } ; _ . each ( includeInJSON , function ( key ) { curJson [ key ] = model . get ( key ) ; } ) ; value . push ( curJson ) ; } ) ; } else if ( related instanceof Backbone . Model ) { value = { } ; _ . each ( includeInJSON , function ( key ) { value [ key ] = related . get ( key ) ; } ) ; } } else { delete json [ rel . key ] ; } if ( includeInJSON ) { json [ rel . keyDestination ] = value ; } if ( rel . keyDestination !== rel . key ) { delete json [ rel . key ] ; } } ) ; this . release ( ) ; return json ; }


Input: Determines what type of ( sub ) model should be built if applicable . Looks up the proper subModelType in this . _subModels recursing into types until a match is found . Returns the applicable Backbone . Model or null if no match is found . [CODESPLIT] function ( type , attributes ) { if ( type . _subModels && type . prototype . subModelTypeAttribute in attributes ) { var subModelTypeAttribute = attributes [ type . prototype . subModelTypeAttribute ] ; var subModelType = type . _subModels [ subModelTypeAttribute ] ; if ( subModelType ) { return subModelType ; } else { // Recurse into subModelTypes to find a match for ( subModelTypeAttribute in type . _subModels ) { subModelType = this . _findSubModelType ( type . _subModels [ subModelTypeAttribute ] , attributes ) ; if ( subModelType ) { return subModelType ; } } } } return null ; }


Input: Find an instance of this type in Backbone . Relational . store . - If attributes is a string or a number findOrCreate will just query the store and return a model if found . - If attributes is an object and is found in the store the model will be updated with attributes unless options . update is false . Otherwise a new model is created with attributes ( unless options . create is explicitly set to false ) . [CODESPLIT] function ( attributes , options ) { options || ( options = { } ) ; var parsedAttributes = ( _ . isObject ( attributes ) && options . parse && this . prototype . parse ) ? this . prototype . parse ( _ . clone ( attributes ) ) : attributes ; // Try to find an instance of 'this' model type in the store var model = Backbone . Relational . store . find ( this , parsedAttributes ) ; // If we found an instance, update it with the data in 'item' (unless 'options.merge' is false). // If not, create an instance (unless 'options.create' is false). if ( _ . isObject ( attributes ) ) { if ( model && options . merge !== false ) { // Make sure `options.collection` and `options.url` doesn't cascade to nested models delete options . collection ; delete options . url ; model . set ( parsedAttributes , options ) ; } else if ( ! model && options . create !== false ) { model = this . build ( attributes , options ) ; } } return model ; }


Input: Find an instance of this type in Backbone . Relational . store . - If attributes is a string or a number find will just query the store and return a model if found . - If attributes is an object and is found in the store the model will be updated with attributes unless options . update is false . [CODESPLIT] function ( attributes , options ) { options || ( options = { } ) ; options . create = false ; return this . findOrCreate ( attributes , options ) ; }