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);
      });
    });
  }

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
)
;
}
)
;
}
)
;
}

deploy the specified revision to the nominated target
handle if file is missing


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()});
    });
  }

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
(
)
}
)
;
}
)
;
}


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);
    });
  }

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
)
)
;
}
)
;
}


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);
      });
    });
  }

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
)
;
}
)
;
}
)
;
}


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);
        });
    });
  }

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
,
,
2
)
,
next
)
;
}
,
function
(
err
)
{
cb
(
err
)
;
}
)
;
}
)
;
}

compile the system into the various targets and commit them to the repository


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);
        }
      });
    });
  }

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
)
;
}
}
)
;
}
)
;
}


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);
        }
      }

function
finalizeBuild
(
sourceReport
)
{
if
(
errorCount
>
0
)
{
grunt
.
fail
.
warn
(
"Coffeeification failed."
)
;
}
else
{
done
(
"Coffeified "
+
sourceReport
.
count
+
": "
+
sourceReport
.
locations
)
;
}
}


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);
		}
	}

Inject necessary code into the file app.js

Inject necessary code into the file app . js


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 });
		});
	}

Fix module resolution in all found javascript files


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();
		}) || [];

	}

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
(
)
;
}
)
||
[
]
;
}

Find all files that match extension criteria

@param {string} rootpath - Absolute path of the directory from which file search will begin
@param {string[]|string} [patterns="**"] - Pattern(s) to be used when attempting to match files found
@returns {string[]} - Matched file paths


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;
	}

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
;
}


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);
	}

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
)
;
}


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, {});
      }
    });
  }

Build the container and update all instantiations of the container
with the new speicific block and replace identifiers for new uuids


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);
    });
  }

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 ) ; } ) ; }

find the container in the supplied target files, return the container with the highest buildHead number

find the container in the supplied target files return the container with the highest buildHead number


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 {};
}

function setAppConsts ( ) { var mergedConstants = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : ( 0 , _seamlessImmutable2 . default ) ( appConsts ) ; 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' ) { self . appConsts = self . appConsts ? _seamlessImmutable2 . default . merge ( self . appConsts , mergedConstants ) : mergedConstants ; return self . appConsts ; } return { } ; }

Set global variables on worker & main threads, else node
@type {[type]}

Set global variables on worker & main threads else node


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();
    });
  }

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 ( ) ; } ) ; }

ensures that the system repository is in place, creates it if doesn't exist

ensures that the system repository is in place creates it if doesn t exist


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);
    }
  }

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
,
,
2
)
,
'utf8'
)
;
git
.
commit
(
sysRepoPath
,
'registered system: '
+
repoPath
,
user
.
name
,
user
.
email
,
cb
)
;
}
else
{
cb
(
)
;
}
}


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);
  }

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


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();
    }

Init the object, construct and process DOM

Init the object construct and process DOM


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);
        }
    }

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 ) ; } }

Process DOM using defined DOM processors


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
    }

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 ) ; } }

Add a child component
@param {Component} child


function(child) {
        var index = this._children.indexOf(child);
        if (index !== -1) {
            this._children.splice(index, 1);
            child.root.parentNode.removeChild(child.root);
            child.destroy();
        }
    }

function ( child ) { var index = this . _children . indexOf ( child ) ; if ( index !== - 1 ) { this . _children . splice ( index , 1 ) ; child . root . parentNode . removeChild ( child . root ) ; child . destroy ( ) ; } }

Remove child component
@param {Component} child


function(child, element, root) {
        this._children.push(child);
        (root || this.root).insertBefore(child.root, element);
        (root || this.root).removeChild(element);
    }

function ( child , element , root ) { this . _children . push ( child ) ; ( root || this . root ) . insertBefore ( child . root , element ) ; ( root || this . root ) . removeChild ( element ) ; }

Attaches a component by replacing the provided element. Element must be an element inside the parent component.
@param {Component} child
@param {Element} element
@param {HTMLElement} root if different than child.root

Attaches a component by replacing the provided element . Element must be an element inside the parent component .


function(repoPath, doc, done) {
    generify(path.join(__dirname, 'template'), repoPath, {
      name: doc.name,
      namespace: doc.namespace,
      id: doc.id
    }, done);
  }

function ( repoPath , doc , done ) { generify ( path . join ( __dirname , 'template' ) , repoPath , { name : doc . name , namespace : doc . namespace , id : doc . id } , done ) ; }

ensures that system has all required files


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');
    }
  }

checks if a directory is a system (has all the required files and correct
system.json and system.js

checks if a directory is a system ( has all the required files and correct system . json and system . js


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});
    }
  }

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
(
)
{
cb
(
err
,
{
id
:
doc
.
id
,
err
:
err
}
)
;
}
)
;
}
)
;
}
)
;
}
)
;
}
else
{
cb
(
,
{
id
:
_meta
.
repoId
(
repoName
)
,
err
:
}
)
;
}
}


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});
      });
    });
  }

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
}
)
;
}
)
;
}
)
;
}

create a new system by linking from local file system


function(user, systemId, cb) {
    writeTimeline(user, systemId, 'system unlinked', function() {
      // swallow any errors here
      _meta.unregister(user, systemId, function(err) {
        cb(err);
      });
    });
  }

function
(
user
,
systemId
,
cb
)
{
writeTimeline
(
user
,
systemId
,
'system unlinked'
,
function
(
)
{
_meta
.
unregister
(
user
,
systemId
,
function
(
err
)
{
cb
(
err
)
;
}
)
;
}
)
;
}


function(systemId, fileName, contents, cb) {
    var repoPath = _meta.repoPath(systemId);
    fse.writeFile(path.join(repoPath, fileName), contents, 'utf8', cb);
  }

function ( systemId , fileName , contents , cb ) { var repoPath = _meta . repoPath ( systemId ) ; fse . writeFile ( path . join ( repoPath , fileName ) , contents , 'utf8' , cb ) ; }

commit a new version of the system, the head of the commit log
may be ahead of the actual deployed version of the system

commit a new version of the system the head of the commit log may be ahead of the actual deployed version of the system


function(systemId, target, cb) {
    listRevisions(systemId, function(err, revs) {
      if (err) { return cb(err); }
      getRevision(systemId, revs[0].id, target, cb);
    });
  }

function ( systemId , target , cb ) { listRevisions ( systemId , function ( err , revs ) { if ( err ) { return cb ( err ) ; } getRevision ( systemId , revs [ 0 ] . id , target , cb ) ; } ) ; }


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);
    });
  }

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
)
,
)
;
}
cb
(
err
,
s
)
;
}
)
;
}

get a revision from the history, with a specific version number

get a revision from the history with a specific version number


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);
        }
      });
    }
  }

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 ) ; } } ) ; } }

get a revision from the history, with abbreviation support

get a revision from the history with abbreviation support


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);
          });
        }
      });
    });
  }

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
(
,
head
.
toString
(
)
)
;
}
else
{
ngit
.
Reference
.
nameToId
(
repo
,
editsTagName
,
function
(
err
)
{
if
(
err
)
{
return
cb
(
err
)
;
}
cb
(
,
EDITS
)
;
}
)
;
}
}
)
;
}
)
;
}


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);
      });
    });
  }

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 ) ; } ) ; } ) ; }

list all of the available revisions in the system


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);
    }
  }

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
)
;
}
}

find revision id by parital or full identifier


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
    };
  }

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
}
;
}

Allows custom configuration from `environment`

Allows custom configuration from environment


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;
  }

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 ; }

Determine the target containers - machine containers that have a proxy on them.

Determine the target containers - machine containers that have a proxy on them .


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 );
			}
		}

Create a new `Relation`.
@param {Backbone.RelationalModel} [model]
@param {Object} relation
@param {Object} [options]


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 );
		}

function ( modelType ) { _ . find ( this . _subModels , function ( subModelDef ) { return _ . find ( subModelDef . subModels || [ ] , function ( subModelTypeName , typeValue ) { var subModelType = this . getObjectByName ( subModelTypeName ) ; if ( modelType === subModelType ) { subModelDef . superModelType . _subModels [ typeValue ] = modelType ; modelType . _superModel = subModelDef . superModelType ; modelType . _subModelTypeValue = typeValue ; modelType . _subModelTypeAttribute = subModelDef . superModelType . prototype . subModelTypeAttribute ; return true ; } } , this ) ; } , this ) ; }

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'.

@param {Backbone.RelationalModel} modelType

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 .


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 );
			}
		}

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 ) ; } }

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.
@param {Object} relation
@param {Backbone.RelationalModel} relation.model
@param {String} relation.type
@param {String} relation.key
@param {String|Object} relation.relatedModel

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 .


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 );
			}
		}

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 ) ; } }

Deposit a `relation` for which the `relatedModel` can't be resolved at the moment.

@param {Object} relation

Deposit a relation for which the relatedModel can t be resolved at the moment .


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 );
		}

function ( ) { _ . 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 ) ; }

Try to initialize any `_orphanRelation`s


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 );
		}

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 ) ; }

Add a 'relation' to all existing instances of 'relation.model' in the store
@param {Object} relation

Add a relation to all existing instances of relation . model in the store


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;
		}

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 ; }

Find the Store's collection for a certain type of model.
@param {Backbone.RelationalModel} type
@param {Boolean} [create=true] Should a collection be created if none is found?
@return {Backbone.Collection} A collection if found (or applicable for 'model'), or null

Find the Store s collection for a certain type of model .


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;
		}

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 ; }

Find a model type on one of the modelScopes by name. Names are split on dots.
@param {String} name
@return {Object}

Find a model type on one of the modelScopes by name . Names are split on dots .


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;
		}

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 ] ; } } if ( ! id && id !== 0 ) { id = null ; } return id ; }

Find the attribute that is to be used as the `id` on a given object
@param type
@param {String|Number|Object|Backbone.RelationalModel} item
@return {String|Number}

Find the attribute that is to be used as the id on a given object


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;
		}

function ( type , item ) { var id = this . resolveIdForItem ( type , item ) ; var coll = this . getCollection ( type ) ; if ( coll ) { var obj = coll . get ( id ) ; if ( obj instanceof type ) { return obj ; } } return null ; }

Find a specific model of a certain `type` in the store
@param type
@param {String|Number|Object|Backbone.RelationalModel} item

Find a specific model of a certain type in the store


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;
			}
		}

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 ; } }

Add a 'model' to its appropriate collection. Retain the original contents of 'model.collection'.
@param {Backbone.RelationalModel} model

Add a model to its appropriate collection . Retain the original contents of model . collection .


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!" );
			}
		}

Check if the given model may use the given `id`
@param model
@param [id]

Check if the given model may use the given id


function( model, collection, options ) {
			this.stopListening( model );
			var coll = this.getCollection( model );
			coll && coll.remove( model, options );
		}

function ( model , collection , options ) { this . stopListening ( model ) ; var coll = this . getCollection ( model ) ; coll && coll . remove ( model , options ) ; }

Remove a 'model' from the store.
@param {Backbone.RelationalModel} model


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;
		}

Check several pre-conditions.
@return {Boolean} True if pre-conditions are satisfied, false if they're not.


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 );
		}

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 ) ; }

When `this.instance` is destroyed, cleanup our relations.
Get reverse relation, call removeRelated on each.

When this . instance is destroyed cleanup our relations . Get reverse relation call removeRelated on each .


function( keyContents ) {
			this.keyContents = keyContents;
			this.keyId = Backbone.Relational.store.resolveIdForItem( this.relatedModel, this.keyContents );
		}

function ( keyContents ) { this . keyContents = keyContents ; this . keyId = Backbone . Relational . store . resolveIdForItem ( this . relatedModel , this . keyContents ) ; }

Normalize and reduce `keyContents` to an `id`, for easier comparison
@param {String|Number|Backbone.Model} keyContents

Normalize and reduce keyContents to an id for easier comparison


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;
			}
		}

function ( model , coll , options ) { if ( ( this . keyId || this . keyId === 0 ) && model . id === this . keyId ) { this . addRelated ( model , options ) ; this . keyId = null ; } }

If a new 'this.relatedModel' appears in the 'store', try to match it to the last set 'keyContents'

If a new this . relatedModel appears in the store try to match it to the last set keyContents


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;
		}

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.
@param {Backbone.Collection} [collection]
@return {Backbone.Collection}

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 .


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 );
			}
		}

function ( keyContents ) { this . keyContents = keyContents instanceof Backbone . Collection ? keyContents : null ; this . keyIds = [ ] ; if ( ! this . keyContents && ( keyContents || keyContents === 0 ) ) { 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 ) ; } }

Normalize and reduce `keyContents` to a list of `ids`, for easier comparison
@param {String|Number|String[]|Number[]|Backbone.Collection} keyContents

Normalize and reduce keyContents to a list of ids for easier comparison


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;
		}

function ( key , options , refresh ) { 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 ] : [ ] ) ) ; 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 ) { 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 ) ; if ( rel . related instanceof Backbone . Collection && _ . isFunction ( rel . related . url ) ) { setUrl = rel . related . url ( models ) ; } 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 ; }

Retrieve related objects.
@param key {string} The relation key to fetch models for.
@param [options] {Object} Options for 'Backbone.Model.fetch' and 'Backbone.sync'.
@param [refresh=false] {boolean} Fetch existing models from the server as well (in order to update them).
@return {jQuery.when[]} An array of request objects


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;
		}

function ( options ) { 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 ) ; } 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 ; }

Convert relations to JSON, omits them when required

Convert relations to JSON omits them when required


function( attributes, options ) {
			options || ( options = {} );
			options.create = false;
			return this.findOrCreate( attributes, options );
		}

function ( attributes , options ) { options || ( options = { } ) ; options . create = false ; return this . findOrCreate ( attributes , options ) ; }

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`.
@param {Object|String|Number} attributes Either a model's id, or the attributes used to create or update a model.
@param {Object} [options]
@param {Boolean} [options.merge=true]
@param {Boolean} [options.parse=false]
@return {Backbone.RelationalModel}

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 .


function XtallatX(superClass) {
    return class extends superClass {
        constructor() {
            super(...arguments);
            this._evCount = {};
        }
        static get observedAttributes() {
            return [disabled];
        }
        /**
         * Any component that emits events should not do so if it is disabled.
         * Note that this is not enforced, but the disabled property is made available.
         * Users of this mix-in should ensure not to call "de" if this property is set to true.
         */
        get disabled() {
            return this._disabled;
        }
        set disabled(val) {
            this.attr(disabled, val, '');
        }
        /**
         * Set attribute value.
         * @param name
         * @param val
         * @param trueVal String to set attribute if true.
         */
        attr(name, val, trueVal) {
            const v = val ? 'set' : 'remove'; //verb
            this[v + 'Attribute'](name, trueVal || val);
        }
        /**
         * Turn number into string with even and odd values easy to query via css.
         * @param n
         */
        to$(n) {
            const mod = n % 2;
            return (n - mod) / 2 + '-' + mod;
        }
        /**
         * Increment event count
         * @param name
         */
        incAttr(name) {
            const ec = this._evCount;
            if (name in ec) {
                ec[name]++;
            }
            else {
                ec[name] = 0;
            }
            this.attr('data-' + name, this.to$(ec[name]));
        }
        attributeChangedCallback(name, oldVal, newVal) {
            switch (name) {
                case disabled:
                    this._disabled = newVal !== null;
                    break;
            }
        }
        /**
         * Dispatch Custom Event
         * @param name Name of event to dispatch ("-changed" will be appended if asIs is false)
         * @param detail Information to be passed with the event
         * @param asIs If true, don't append event name with '-changed'
         */
        de(name, detail, asIs = false) {
            const eventName = name + (asIs ? '' : '-changed');
            const newEvent = new CustomEvent(eventName, {
                detail: detail,
                bubbles: true,
                composed: false,
            });
            this.dispatchEvent(newEvent);
            this.incAttr(eventName);
            return newEvent;
        }
        /**
         * Needed for asynchronous loading
         * @param props Array of property names to "upgrade", without losing value set while element was Unknown
         */
        _upgradeProperties(props) {
            props.forEach(prop => {
                if (this.hasOwnProperty(prop)) {
                    let value = this[prop];
                    delete this[prop];
                    this[prop] = value;
                }
            });
        }
    };
}

function XtallatX ( superClass ) { return class extends superClass { constructor ( ) { super ( ... arguments ) ; this . _evCount = { } ; } static get observedAttributes ( ) { return [ disabled ] ; } get disabled ( ) { return this . _disabled ; } set disabled ( val ) { this . attr ( disabled , val , '' ) ; } attr ( name , val , trueVal ) { const v = val ? 'set' : 'remove' ; this [ v + 'Attribute' ] ( name , trueVal || val ) ; } to$ ( n ) { const mod = n % 2 ; return ( n - mod ) / 2 + '-' + mod ; } incAttr ( name ) { const ec = this . _evCount ; if ( name in ec ) { ec [ name ] ++ ; } else { ec [ name ] = 0 ; } this . attr ( 'data-' + name , this . to$ ( ec [ name ] ) ) ; } attributeChangedCallback ( name , oldVal , newVal ) { switch ( name ) { case disabled : this . _disabled = newVal !== null ; break ; } } de ( name , detail , asIs = false ) { const eventName = name + ( asIs ? '' : '-changed' ) ; const newEvent = new CustomEvent ( eventName , { detail : detail , bubbles : true , composed : false , } ) ; this . dispatchEvent ( newEvent ) ; this . incAttr ( eventName ) ; return newEvent ; } _upgradeProperties ( props ) { props . forEach ( prop => { if ( this . hasOwnProperty ( prop ) ) { let value = this [ prop ] ; delete this [ prop ] ; this [ prop ] = value ; } } ) ; } } ; }

Base class for many xtal- components
@param superClass


function Bitmap(imageOrUri) {
		this.DisplayObject_constructor();

	// public properties:
		/**
		 * The source image to display. This can be a CanvasImageSource
		 * (image, video, canvas), an object with a `getImage` method that returns a CanvasImageSource, or a string URL to an image.
		 * If the latter, a new Image instance with the URL as its src will be used.
		 * @property image
		 * @type CanvasImageSource | Object
		 **/
		if (typeof imageOrUri == "string") {
			this.image = document.createElement("img");
			this.image.src = imageOrUri;
		} else {
			this.image = imageOrUri;
		}

		/**
		 * Specifies an area of the source image to draw. If omitted, the whole image will be drawn.
		 * Note that video sources must have a width / height set to work correctly with `sourceRect`.
		 * @property sourceRect
		 * @type Rectangle
		 * @default null
		 */
		this.sourceRect = null;

	// private properties:
		/**
		 * Docced in superclass.
		 */
		this._webGLRenderStyle = createjs.DisplayObject._StageGL_BITMAP;
	}

function Bitmap ( imageOrUri ) { this . DisplayObject_constructor ( ) ; if ( typeof imageOrUri == "string" ) { this . image = document . createElement ( "img" ) ; this . image . src = imageOrUri ; } else { this . image = imageOrUri ; } this . sourceRect = null ; this . _webGLRenderStyle = createjs . DisplayObject . _StageGL_BITMAP ; }

A Bitmap represents an Image, Canvas, or Video in the display list. A Bitmap can be instantiated using an existing
HTML element, or a string.

Example

var bitmap = new createjs.Bitmap("imagePath.jpg");

Notes:

When using a video source that may loop or seek, use a {{#crossLink "VideoBuffer"}}{{/crossLink}} object to
prevent blinking / flashing.

When a string path or image tag that is not yet loaded is used, the stage may need to be redrawn before it
will be displayed.

Bitmaps with an SVG source currently will not respect an alpha value other than 0 or 1. To get around this,
the Bitmap can be cached.

Bitmaps with an SVG source will taint the canvas with cross-origin data, which prevents interactivity. This
happens in all browsers except recent Firefox builds.

Images loaded cross-origin will throw cross-origin security errors when interacted with using a mouse, using
methods such as `getObjectUnderPoint`, or using filters, or caching. You can get around this by setting
`crossOrigin` flags on your images before passing them to EaselJS, eg: `img.crossOrigin="Anonymous";`

@class Bitmap
@extends DisplayObject
@constructor
@param {CanvasImageSource | String | Object} imageOrUri The source image to display. This can be a CanvasImageSource
(image, video, canvas), an object with a `getImage` method that returns a CanvasImageSource, or a string URL to an image.
If the latter, a new Image instance with the URL as its src will be used.

A Bitmap represents an Image Canvas or Video in the display list . A Bitmap can be instantiated using an existing HTML element or a string .


function canonicalize(value, stack) {
  var canonicalizedObj;
  /* eslint-disable no-unused-vars */
  var prop;
  /* eslint-enable no-unused-vars */
  var type = getType(value);
  function withStack(value, fn) {
    stack.push(value);
    fn();
    stack.pop();
  }

  stack = stack || [];

  if (stack.indexOf(value) !== -1) {
    return '[Circular]';
  }

  switch (type) {
    case 'undefined':
    case 'buffer':
    case 'null':
      canonicalizedObj = value;
      break;
    case 'array':
      withStack(value, function() {
        canonicalizedObj = value.map(function(item) {
          return canonicalize(item, stack);
        });
      });
      break;
    case 'function':
      /* eslint-disable guard-for-in */
      for (prop in value) {
        canonicalizedObj = {};
        break;
      }
      /* eslint-enable guard-for-in */
      if (!canonicalizedObj) {
        canonicalizedObj = emptyRepresentation(value, type);
        break;
      }
    /* falls through */
    case 'object':
      canonicalizedObj = canonicalizedObj || {};
      withStack(value, function() {
        Object.keys(value).sort().forEach(function(key) {
          canonicalizedObj[key] = canonicalize(value[key], stack);
        });
      });
      break;
    case 'date':
    case 'number':
    case 'regexp':
    case 'boolean':
      canonicalizedObj = value;
      break;
    default:
      canonicalizedObj = value.toString();
  }

  return canonicalizedObj;
}

function canonicalize ( value , stack ) { var canonicalizedObj ; var prop ; var type = getType ( value ) ; function withStack ( value , fn ) { stack . push ( value ) ; fn ( ) ; stack . pop ( ) ; } stack = stack || [ ] ; if ( stack . indexOf ( value ) !== - 1 ) { return '[Circular]' ; } switch ( type ) { case 'undefined' : case 'buffer' : case 'null' : canonicalizedObj = value ; break ; case 'array' : withStack ( value , function ( ) { canonicalizedObj = value . map ( function ( item ) { return canonicalize ( item , stack ) ; } ) ; } ) ; break ; case 'function' : for ( prop in value ) { canonicalizedObj = { } ; break ; } if ( ! canonicalizedObj ) { canonicalizedObj = emptyRepresentation ( value , type ) ; break ; } case 'object' : canonicalizedObj = canonicalizedObj || { } ; withStack ( value , function ( ) { Object . keys ( value ) . sort ( ) . forEach ( function ( key ) { canonicalizedObj [ key ] = canonicalize ( value [ key ] , stack ) ; } ) ; } ) ; break ; case 'date' : case 'number' : case 'regexp' : case 'boolean' : canonicalizedObj = value ; break ; default : canonicalizedObj = value . toString ( ) ; } return canonicalizedObj ; }

Return a new Thing that has the keys in sorted order. Recursive.

If the Thing...
- has already been seen, return string `'[Circular]'`
- is `undefined`, return string `'[undefined]'`
- is `null`, return value `null`
- is some other primitive, return the value
- is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
- is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
- is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`

Return a new Thing that has the keys in sorted order . Recursive .


function emptyRepresentation(value, type) {
  type = type || getType(value);

  switch (type) {
    case 'function':
      return '[Function]';
    case 'object':
      return '{}';
    case 'array':
      return '[]';
    default:
      return value.toString();
  }
}

function emptyRepresentation ( value , type ) { type = type || getType ( value ) ; switch ( type ) { case 'function' : return '[Function]' ; case 'object' : return '{}' ; case 'array' : return '[]' ; default : return value . toString ( ) ; } }

If a value could have properties, and has none, this function is called,
which returns a string representation of the empty value.

Functions w/ no properties return `'[Function]'`
Arrays w/ length === 0 return `'[]'`
Objects w/ no properties return `'{}'`
All else: return result of `value.toString()`

If a value could have properties and has none this function is called which returns a string representation of the empty value .


function(doc, first, last) {
							var f = doc.WordPos[first];
							var l;
							if (last==doc.WordPos.length-1) //
								l = doc.DocLength;
							else
								l = doc.WordPos[last+1];
							return l-f;
						}

function ( doc , first , last ) { var f = doc . WordPos [ first ] ; var l ; if ( last == doc . WordPos . length - 1 ) l = doc . DocLength ; else l = doc . WordPos [ last + 1 ] ; return l - f ; }


function compile() {
  var buf = '';
  buf += '(function() {\n';
  buf += '\n// CommonJS require()\n\n';
  buf += browser.require + '\n\n';
  buf += 'require.modules = {};\n\n';
  buf += 'require.resolve = ' + browser.resolve + ';\n\n';
  buf += 'require.register = ' + browser.register + ';\n\n';
  buf += 'require.relative = ' + browser.relative + ';\n\n';
  args.forEach(function(file){
    var js = files[file];
    file = file.replace('lib/', '');
    buf += '\nrequire.register("' + file + '", function(module, exports, require){\n';
    buf += js;
    buf += '\n}); // module: ' + file + '\n';
  });
  buf += '\nwindow.kiwi = require("kiwi");\n';
  buf += '})();\n';
  fs.writeFile('kiwi.js', buf, function(err){
    if (err) throw err;
    console.log('  \033[90m create : \033[0m\033[36m%s\033[0m', 'kiwi.js');
    console.log();
  });
}

function
compile
(
)
{
var
buf
=
''
;
buf
+=
'(function() {\n'
;
\n
buf
+=
'\n// CommonJS require()\n\n'
;
\n
\n
\n
buf
+=
browser
.
require
+
'\n\n'
;
\n
\n
buf
+=
'require.modules = {};\n\n'
;
\n
}


function fp() {
      var args = Array.prototype.slice.call(arguments, 0);
      if (args.length) {
        if (!args.every(isStringOrFunction)) {
          var signature = args.map(humanizeArgument).join('\n\t');
          throw new Error('Invalid arguments to functional pipeline - not a string or function\n\t' +
            signature);
        }

        var fns = splitDots(args);
        return function (d) {
          var originalObject = d;
          fns.forEach(function (fn) {
            if (typeof fn === 'string') {
              if (typeof d[fn] === 'function') {
                d = d[fn].call(d, d);
              } else if (typeof d[fn] !== 'undefined') {
                d = d[fn];
              } else {
                var signature = args.map(humanizeArgument).join('\n\t');
                throw new Error('Cannot use property ' + fn + ' from object ' +
                  JSON.stringify(d, null, 2) + '\npipeline\n\t' + signature +
                  '\noriginal object\n' + JSON.stringify(originalObject, null, 2));
              }
            } else if (typeof fn === 'function') {
              d = fn(d);
            } else {
              throw new Error('Cannot apply ' + JSON.stringify(fn, null, 2) +
                ' to value ' + d + ' not a property name or a function');
            }
          });
          return d;
        };
      }
    }

Creates an optimistic chain, no checks before calling a function or accessing a property, or calling a method

Creates an optimistic chain no checks before calling a function or accessing a property or calling a method


function(tickRate){
    events.EventEmitter.call(this);

    // Initialize private properties
    this._milliseconds = 0;
    this._setState('stopped');
    this._timer = new NanoTimer();

    tickRate = tickRate || 100;
    Object.defineProperty(this, 'tickRate', {
        enumerable: true,
        configurable: false,
        writable: false,
        value: tickRate
    });
}

function ( tickRate ) { events . EventEmitter . call ( this ) ; this . _milliseconds = 0 ; this . _setState ( 'stopped' ) ; this . _timer = new NanoTimer ( ) ; tickRate = tickRate || 100 ; Object . defineProperty ( this , 'tickRate' , { enumerable : true , configurable : false , writable : false , value : tickRate } ) ; }

Construct a new Rieussec stopwatch

@class Rieussec
@classdesc A rieussec stopwatch object.

@param {Number} [tickRate=100] - How often (in milliseconds) to emit "tick" events


function onProcessed(err, processed) {
    if(err) return callback(err);
    _this._tokenize(processed, onTokenized);
  }

function onProcessed ( err , processed ) { if ( err ) return callback ( err ) ; _this . _tokenize ( processed , onTokenized ) ; }


function Template(str, options) {

  // Handle the case where the only argument passed is the `options` object
  if(_.isObject(str) && !options){
    options = str;
    str = null;
  }

  // Create options if not provided
  options = options ? _.clone(options) : {};

  // Set default cache behavior
  // if node
  if(!_.isBoolean(options.cache)) {
    options.cache = process.env.NODE_ENV === 'production';
  }
  // end

  // Merges given `options` with `DEFAULTS`
  options = _.defaults(options, DEFAULTS);
  options.cacheContext = options.cacheContext || Template;

  // Sets instance variables
  this.template = str;
  this.options = options;
  this._compiled = null;

  // Creates the cache if not already done
  if(options.cache && !(this._getCache() instanceof options.cacheHandler)) {
    var cacheOptions = [options.cacheHandler].concat(options.cacheOptions);
    options.cacheContext[options._cacheProp] = typeof window !== 'undefined' ?
                                                 new options.cacheHandler() :
                                                 construct.apply(this,
                                                                 cacheOptions);
  }
}

function Template ( str , options ) { if ( _ . isObject ( str ) && ! options ) { options = str ; str = null ; } options = options ? _ . clone ( options ) : { } ; if ( ! _ . isBoolean ( options . cache ) ) { options . cache = process . env . NODE_ENV === 'production' ; } options = _ . defaults ( options , DEFAULTS ) ; options . cacheContext = options . cacheContext || Template ; this . template = str ; this . options = options ; this . _compiled = null ; if ( options . cache && ! ( this . _getCache ( ) instanceof options . cacheHandler ) ) { var cacheOptions = [ options . cacheHandler ] . concat ( options . cacheOptions ) ; options . cacheContext [ options . _cacheProp ] = typeof window !== 'undefined' ? new options . cacheHandler ( ) : construct . apply ( this , cacheOptions ) ; } }

Initializes `Template` with optionnally the given `str` and
`options`.

@param {String} [str]
@param {Object} [options]
@api public

Initializes Template with optionnally the given str and options .


function (fn, rate) {
  var allowed = true;
  return function () {
    if (allowed) {
      allowed = false;
      fn.apply(null, [].slice.call(arguments, 0));
      setTimeout(function () {
        allowed = true;
      }, rate);
    }
  }
}

function ( fn , rate ) { var allowed = true ; return function ( ) { if ( allowed ) { allowed = false ; fn . apply ( null , [ ] . slice . call ( arguments , 0 ) ) ; setTimeout ( function ( ) { allowed = true ; } , rate ) ; } } }

used to fix fs.watch on windows triggering cascading events the function fn can only be called once per rate

used to fix fs . watch on windows triggering cascading events the function fn can only be called once per rate


function get_data (callback) {
  var data;
  try {
    data = program.data ? JSON.parse(program.data) : {};
    callback(data);
  } catch (err) {
    fs.readFile(program.data, function (err, str) {
      str = '' + str;
      if (!err) {
        try {
          data = JSON.parse(str);
          callback(data);
        } catch (err) {
          data = eval(str);
          callback(data);
        }
      }
    });
  }
  return data;
}

function get_data ( callback ) { var data ; try { data = program . data ? JSON . parse ( program . data ) : { } ; callback ( data ) ; } catch ( err ) { fs . readFile ( program . data , function ( err , str ) { str = '' + str ; if ( ! err ) { try { data = JSON . parse ( str ) ; callback ( data ) ; } catch ( err ) { data = eval ( str ) ; callback ( data ) ; } } } ) ; } return data ; }

get optional data from command line as json or file containing json or javascript


function secureWebhookEndpoints() {
    var authenticationMiddleware = require(__dirname + '/middleware/slack_authentication.js');
    // convert a variable argument list to an array, drop the webserver argument
    var tokens = Array.prototype.slice.call(arguments);
    var webserver = tokens.shift();

    slack_botkit.logger.info(
      '** Requiring token authentication for webhook endpoints for Slash commands ' +
      'and outgoing webhooks; configured ' + tokens.length + ' token(s)'
    );

    webserver.use(authenticationMiddleware(tokens));
  }

adds the webhook authentication middleware module to the webserver


function postForm(url, formData, cb, multipart) {
        cb = cb || noop;

        bot.logger.info('** API CALL: ' + url);
        var params = {
            url: url,
            headers: {
                'User-Agent': bot.userAgent(),
            }
        };

        if (multipart === true) {
            params.formData = formData;
        } else {
            params.form = formData;
        }

        request.post(params, function(error, response, body) {
            bot.logger.debug('Got response', error, body);

            if (error) {
                return cb(error);
            }

            if (response.statusCode == 200) {
                var json;
                try {
                    json = JSON.parse(body);
                } catch (parseError) {
                    return cb(parseError);
                }

                return cb((json.ok ? null : json.error), json);
            } else if (response.statusCode == 429) {
                return cb(new Error('Rate limit exceeded'));
            } else {
                return cb(new Error('Invalid response'));
            }
        });
    }

function
postForm
(
url
,
formData
,
cb
,
multipart
)
{
cb
=
cb
||
noop
;
bot
.
logger
.
info
(
'** API CALL: '
+
url
)
;
var
params
=
{
url
:
url
,
headers
:
{
'User-Agent'
:
bot
.
userAgent
(
)
,
}
}
;
if
(
multipart
===
true
)
{
params
.
formData
=
formData
;
}
else
{
params
.
form
=
formData
;
}
request
.
post
(
params
,
function
(
error
,
response
,
body
)
{
bot
.
logger
.
debug
(
'Got response'
,
error
,
body
)
;
if
(
error
)
{
return
cb
(
error
)
;
}
if
(
response
.
statusCode
==
200
)
{
var
json
;
try
{
json
=
JSON
.
parse
(
body
)
;
}
catch
(
parseError
)
{
return
cb
(
parseError
)
;
}
return
cb
(
(
json
.
ok
:
json
.
error
)
,
json
)
;
}
else
if
(
response
.
statusCode
==
429
)
{
return
cb
(
new
Error
(
'Rate limit exceeded'
)
)
;
}
else
{
return
cb
(
new
Error
(
'Invalid response'
)
)
;
}
}
)
;
}

Makes a POST request as a form to the given url with the options as data

@param {string} url The URL to POST to
@param {Object} formData The data to POST as a form
@param {function=} cb An optional NodeJS style callback when the POST completes or errors out.


function verifyRequest(req, res, buf, encoding) {
    var expected = req.headers['x-hub-signature'];
    var calculated = getSignature(buf);
    if (expected !== calculated) {
      throw new Error('Invalid signature on incoming request');
    } else {
      // facebook_botkit.logger.debug('** X-Hub Verification successful!')
    }
  }

function
verifyRequest
(
req
,
res
,
buf
,
encoding
)
{
var
expected
=
req
.
headers
[
'x-hub-signature'
]
;
var
calculated
=
getSignature
(
buf
)
;
if
(
expected
!==
calculated
)
{
throw
new
Error
(
'Invalid signature on incoming request'
)
;
}
else
{
}
}

Verifies the SHA1 signature of the raw request payload before bodyParser parses it Will abort parsing if signature is invalid, and pass a generic error to response

Verifies the SHA1 signature of the raw request payload before bodyParser parses it Will abort parsing if signature is invalid and pass a generic error to response


function() {
				if ( !this.selfUpdating ) {
					this.deferred = true;
				}
				var i = this.refs.length;
				while ( i-- ) {
					this.refs[ i ].update();
				}
				if ( this.deferred ) {
					this.update();
					this.deferred = false;
				}
			}

function ( ) { if ( ! this . selfUpdating ) { this . deferred = true ; } var i = this . refs . length ; while ( i -- ) { this . refs [ i ] . update ( ) ; } if ( this . deferred ) { this . update ( ) ; this . deferred = false ; } }

This method forces the evaluator to sync with the current model in the case of a smart update


function DockerCmdManager(dockerdescPath) {
    dockerdescPath = dockerdescPath || './dockerdesc.json';

    if (!fs.existsSync(dockerdescPath)) {
        throw new Error(util.format('The path "%s" does not exists.', dockerdescPath));
    }
    /** @type {string} */
    this.dockerdescDir = path.dirname(dockerdescPath);

    var dockerdescPathStat = fs.statSync(dockerdescPath);
    if (dockerdescPathStat.isDirectory()) {
        this.dockerdescDir = dockerdescPath;
        dockerdescPath = path.join(dockerdescPath, 'dockerdesc.json');
    }
    /** @type {Dockerdesc} */
    var dockerdescContent = fs.readFileSync(dockerdescPath);
    try {
        this.dockerdesc = JSON.parse(dockerdescContent);
    } catch (err) {
        throw new Error('Problem in the dockerdesc.json file format.\n' + err.stack);
    }
}

This class manages the DockerCmd and handles dockerdesc.json
@constructor
@param {string} [dockerdescPath='./dockerdesc.json'] - Path to `dockerdesc.json` file or parent dir

This class manages the DockerCmd and handles dockerdesc . json


function dd(object, _context, _key, _root, _rootPath) {
    _root = _root || object;
    _rootPath = _rootPath || [];
    var drill = function(key) {
        var nextObject = (
            object &&
            object.hasOwnProperty(key) &&
            object[key] ||
            undefined
        );
        return dd(nextObject, object, key, _root, _rootPath.concat(key));
    };
    drill.val = object;
    drill.exists = object !== undefined;
    drill.set = function(value) {
        if (_rootPath.length === 0) {
            return;
        }
        var contextIterator = _root;
        for (var depth = 0; depth < _rootPath.length; depth++) {
            var key = _rootPath[depth];
            var isFinalDepth = (depth === _rootPath.length - 1);
            if (!isFinalDepth) {
                contextIterator[key] = (
                    contextIterator.hasOwnProperty(key) &&
                    typeof contextIterator[key] === 'object' ?
                        contextIterator[key] : {}
                );
                contextIterator = contextIterator[key];
            } else {
                _context = contextIterator;
                _key = key;
            }
        }
        _context[_key] = value;
        drill.val = value;
        drill.exists = value !== undefined;
        return value;
    };
    drill.update = function(value) {
        if (drill.exists) {
            _context[_key] = value;
            drill.val = value;
            return value;
        }
    };
    drill.invoke = isFunction(object) ? Function.prototype.bind.call(object, _context) : function () {
    };

    return drill;
}

function dd ( object , _context , _key , _root , _rootPath ) { _root = _root || object ; _rootPath = _rootPath || [ ] ; var drill = function ( key ) { var nextObject = ( object && object . hasOwnProperty ( key ) && object [ key ] || undefined ) ; return dd ( nextObject , object , key , _root , _rootPath . concat ( key ) ) ; } ; drill . val = object ; drill . exists = object !== undefined ; drill . set = function ( value ) { if ( _rootPath . length === 0 ) { return ; } var contextIterator = _root ; for ( var depth = 0 ; depth < _rootPath . length ; depth ++ ) { var key = _rootPath [ depth ] ; var isFinalDepth = ( depth === _rootPath . length - 1 ) ; if ( ! isFinalDepth ) { contextIterator [ key ] = ( contextIterator . hasOwnProperty ( key ) && typeof contextIterator [ key ] === 'object' ? contextIterator [ key ] : { } ) ; contextIterator = contextIterator [ key ] ; } else { _context = contextIterator ; _key = key ; } } _context [ _key ] = value ; drill . val = value ; drill . exists = value !== undefined ; return value ; } ; drill . update = function ( value ) { if ( drill . exists ) { _context [ _key ] = value ; drill . val = value ; return value ; } } ; drill . invoke = isFunction ( object ) ? Function . prototype . bind . call ( object , _context ) : function ( ) { } ; return drill ; }

drilldown
Safely accesses deep properties of objects.

var foo;
foo.bar;
// TypeError: Cannot read property 'bar' of undefined

var foo = {abc: {def: {ghi: 'jkl'}}};
dd(foo)('abc')('def')('ghi').val is 'jkl'
dd(foo)('abc')('zzz')('yyy').val is undefined

Check if a deep property exists:
dd(foo)('abc').exists

Works with arrays too:
var foo = {abc: [ {bar: 'def'},{bar: 'ghi'} ]};
dd(foo)('abc')(0)('bar') is 'def'

Safely call functions:
var foo = {abc: {addOne: function(x) { return x + 1; }}};
dd(foo)('abc')('addOne').invoke(5); returns 6
dd(foo)('zzz')('aaa').invoke(5); returns undefined

Update values if the original value exists:
var foo = {abc: {def: {ghi: 'jkl'}}};
var newValue = {ping: 'pong'};
dd(foo)('abc')('def').update(newValue);
- foo is now {abc: {def: {ping: 'pong'}}}
- {ping: 'pong'} is returned
dd(foo)('abc')('zzz').update(5);
- foo is unchanged
- undefined is returned

Set values even if the path drilled to does not exist:
var foo = {abc: {}};
dd(foo)('abc')('def')('ghi').set('jkl');
- foo is now {abc: {def: {ghi: 'jkl}}}

To prevent confusion, only own properties are drilled into.

Available properties:
- val - the value
- exists - true if val is defined
- update function(value) - sets the value if the value exists
- set function(value) - sets the value at any path
- invoke - the value if the value is a function, or else a dummy function

@param {object} object
@param _context
@param _key
@param _root
@param _rootPath
@returns {Function}

drilldown Safely accesses deep properties of objects .


function printTasks(tasks, verbose) {
  tasks = tasks
    .filterHidden(verbose)
    .sort();

  var results = [
    'Usage: gulp [task] [task2] ...',
    '',
    'Tasks: '
  ];

  var fieldTaskLen = tasks.getLongestNameLength();

  tasks.forEach(function(task) {
    var comment = task.comment || {};
    var lines = comment.lines || [];
    results.push(formatColumn(task.name, fieldTaskLen) + (lines[0] || ''));
    for (var i = 1; i < lines.length; i++) {
      results.push(formatColumn('', fieldTaskLen) + '  ' + lines[i]);
    }
  });

  return results.join('\n');
}

function
printTasks
(
tasks
,
verbose
)
{
tasks
=
tasks
.
filterHidden
(
verbose
)
.
sort
(
)
;
var
results
=
[
'Usage: gulp [task] [task2] ...'
,
''
,
'Tasks: '
]
;
var
fieldTaskLen
=
tasks
.
getLongestNameLength
(
)
;
tasks
.
forEach
(
function
(
task
)
{
var
comment
=
task
.
comment
||
{
}
;
var
lines
=
comment
.
lines
||
[
]
;
results
.
push
(
formatColumn
(
task
.
name
,
fieldTaskLen
)
+
(
lines
[
0
]
||
''
)
)
;
for
(
var
i
=
1
;
i
<
lines
.
length
;
i
++
)
{
results
.
push
(
formatColumn
(
''
,
fieldTaskLen
)
+
'  '
+
lines
[
i
]
)
;
}
}
)
;
return
results
.
join
(
'\n'
)
;
}

Render output from tasks
@param {TaskList} tasks
@param {boolean}  [verbose=false]
@returns {string}


function formatColumn(text, width, offsetLeft, offsetRight) {
  offsetLeft  = undefined !== offsetLeft  ? offsetLeft  : 3;
  offsetRight = undefined !== offsetRight ? offsetRight : 3;

  return new Array(offsetLeft + 1).join(' ') +
    text +
    new Array(Math.max(width - text.length, 0) + 1).join(' ') +
    new Array(offsetRight + 1).join(' ');
}

function
formatColumn
(
text
,
width
,
offsetLeft
,
offsetRight
)
{
offsetLeft
=
undefined
!==
offsetLeft
offsetLeft
:
3
;
offsetRight
=
undefined
!==
offsetRight
offsetRight
:
3
;
return
new
Array
(
offsetLeft
+
1
)
.
join
(
' '
)
+
text
+
new
Array
(
Math
.
max
(
width
text
.
length
,
0
)
+
1
)
.
join
(
' '
)
+
new
Array
(
offsetRight
+
1
)
.
join
(
' '
)
;
}

Return a text surrounded by space
@param {string} text
@param {number} width Column width without offsets
@param {number} [offsetLeft=3]  space count before text
@param {number} [offsetRight=3] space count after text
@returns {string}


function inheritGulp() {
  function TaskDoc() {
    this.taskList = new TaskList();
    gulp.Gulp.call(this);
  }
  TaskDoc.prototype = gulp;
  return new TaskDoc();
}

function inheritGulp ( ) { function TaskDoc ( ) { this . taskList = new TaskList ( ) ; gulp . Gulp . call ( this ) ; } TaskDoc . prototype = gulp ; return new TaskDoc ( ) ; }

Return a new instance that is inherited from Gulp
@returns {TaskDoc}