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

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

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}


function _log(level) {

  return function() {
    var meta = null;
    var args = arguments;
    if (arguments.length === 0) {
      // we only check here current level, but we also should more but restify uses it only for trace checks
      return this._winston.level === level;
    } else if (arguments[0] instanceof Error) {
      // winston supports Error in meta, so pass it as last
      meta = arguments[0].toString();
      args = Array.prototype.slice.call(arguments, 1);
      args.push(meta);
    } else if (typeof (args[0]) === 'string') {
      // just arrayize for level
      args = Array.prototype.slice.call(arguments);
    } else {
      // push provided object as meta
      meta = arguments[0];
      args = Array.prototype.slice.call(arguments, 1);
      args.push(meta);
    }
    args.unshift(level);
    this._winston.log.apply(this._winston, args);
  }
}

We are creating one generic version of logger.

We are creating one generic version of logger .


function isPromise(item) {
	if (!item) return false;
	return (
		(util.types && util.types.isPromise && util.types.isPromise(item))
		|| (item.constructor && item.constructor.name == 'Promise')
		|| (!item instanceof objectInstance && item.then && typeof item.then == 'function')
	);
}

function isPromise ( item ) { if ( ! item ) return false ; return ( ( util . types && util . types . isPromise && util . types . isPromise ( item ) ) || ( item . constructor && item . constructor . name == 'Promise' ) || ( ! item instanceof objectInstance && item . then && typeof item . then == 'function' ) ) ; }

Try and idenfity if the given item is a promise or is promise like
@param {*} item The item to examine
@returns {boolean} Whether the item looks like a promise


function hasCallback(fn) {
	var fnString = fn.toString();
	// console.log('---');
	// console.log('GIVEN', '>>> ' + fnString + ' <<<');

	var bits, fnArgs;
	if (/^async /.test(fnString)) {
		// console.log('IS ASYNC');
		return false; // Its an async function and should only ever return a promise
	} else if (bits = /^function\s*(?:.*?)\s*\((.*?)\)/.exec(fnString)) {
		// console.log('> FUNC', bits[1]);
		fnArgs = bits[1];
	} else if (/^\(\s*\)\s*=>/.test(fnString)) {
		// console.log('ARROW (no args)');
		return false;
	} else if (bits = /^\s\((.*?)\)\s*?=>/.exec(fnString)) {
		// console.log('> ARROW (braces)', bits[1]);
		fnArgs = bits[1];
	} else if (bits = /^(.*?)\s*=>/.exec(fnString)) {
		// console.log('> ARROW (no braces)', bits[1]);
		fnArgs = bits[1];
	} else {
		// console.log('> EMPTY');
		return false;
	}

	fnArgs = fnArgs.replace(/^\s+/, '').replace(/\s+$/, ''); // Clean up args by trimming whitespace
	// console.log('ARGS:', fnArgs);

	return !! fnArgs;

}

Figure out if a function declaration looks like it takes a callback
Really this just checks the setup of a function for an argument - it cannot check if that argument is a function
@param {function} fn The function to examine
@returns {boolean} Whether the function LOOKS like it takes a callback


function race() {
	var self = this;

	argy(arguments)
		.ifForm('', function() {})
		.ifForm('array', function(tasks) {
			self._struct.push({ type: 'race', payload: tasks });
		})
		.ifForm('string array', function(id, tasks) {
			self._struct.push({ type: 'race', id: arguments[0], payload: arguments[1] });
		})
		.ifFormElse(function(form) {
			throw new Error('Unknown call style for .parallel(): ' + form);
		})

	return self;
}

function
race
(
)
{
var
self
=
this
;
argy
(
arguments
)
.
ifForm
(
''
,
function
(
)
{
}
)
.
ifForm
(
'array'
,
function
(
tasks
)
{
self
.
_struct
.
push
(
{
type
:
'race'
,
payload
:
tasks
}
)
;
}
)
.
ifForm
(
'string array'
,
function
(
id
,
tasks
)
{
self
.
_struct
.
push
(
{
type
:
'race'
,
id
:
arguments
[
0
]
,
payload
:
arguments
[
1
]
}
)
;
}
)
.
ifFormElse
(
function
(
form
)
{
throw
new
Error
(
'Unknown call style for .parallel(): '
+
form
)
;
}
)
return
self
;
}

Like parallel but only return the first, non-undefined, non-null result
@param {string} The ID to set when the first function returns a non-undefined, non-null result
@param {array} The functions to execute
@return {Object} This chainable object

Like parallel but only return the first non - undefined non - null result


function deferAdd(id, task, parentChain) {
	var self = this;
	parentChain.waitingOn = (parentChain.waitingOn || 0) + 1;

	if (! parentChain.waitingOnIds)
		parentChain.waitingOnIds = [];
	parentChain.waitingOnIds.push(id);

	self._deferred.push({
		id: id || null,
		prereq: parentChain.prereq || [],
		payload: function(next) {
			self._context._id = id;

			run(self._options.context, task, function(err, value) { // Glue callback function to first arg
				if (id) self._context[id] = value;

				self._deferredRunning--;

				if (--parentChain.waitingOn == 0) {
					parentChain.completed = true;

					if (self._struct.length && self._struct[self._structPointer].type == 'await') self._execute(err);
				}

				self._execute(err);
			}, (parentChain.prereq || []).map(function(pre) {
				return self._context[pre];
			}));
		}
	});
}

function
deferAdd
(
id
,
task
,
parentChain
)
{
var
self
=
this
;
parentChain
.
waitingOn
=
(
parentChain
.
waitingOn
||
0
)
+
1
;
if
(
!
parentChain
.
waitingOnIds
)
parentChain
.
waitingOnIds
=
[
]
;
parentChain
.
waitingOnIds
.
push
(
id
)
;
self
.
_deferred
.
push
(
{
id
:
id
||
,
prereq
:
parentChain
.
prereq
||
[
]
,
payload
:
function
(
next
)
{
self
.
_context
.
_id
=
id
;
run
(
self
.
_options
.
context
,
task
,
function
(
err
,
value
)
{
// Glue callback function to first arg
if
(
id
)
self
.
_context
[
id
]
=
value
;
self
.
_deferredRunning
;
if
(
parentChain
.
waitingOn
==
0
)
{
parentChain
.
completed
=
true
;
if
(
self
.
_struct
.
length
&&
self
.
_struct
[
self
.
_structPointer
]
.
type
==
'await'
)
self
.
_execute
(
err
)
;
}
self
.
_execute
(
err
)
;
}
,
(
parentChain
.
prereq
||
[
]
)
.
map
(
function
(
pre
)
{
return
self
.
_context
[
pre
]
;
}
)
)
;
}
}
)
;
}

Collection of items that have been deferred
@type {array} {payload: function, id: null|String, prereq: [dep1, dep2...]}
@access private


function await() {
	var payload = [];

	// Slurp all args into payload
	argy(arguments)
		.getForm()
		.split(',')
		.forEach(function(type, offset) {
			switch (type) {
				case '': // Blank arguments - do nothing
					// Pass
					break;
				case 'string':
					payload.push(args[offset]);
					break;
				case 'array':
					payload.concat(args[offset]);
					break;
				default:
					throw new Error('Unknown argument type passed to .await(): ' + type);
			}
		});

	this._struct.push({ type: 'await', payload: payload });

	return this;
}

Queue up an await point
This stops the execution queue until its satisfied that dependencies have been resolved
@param {array,...} The dependencies to check resolution of. If omitted all are checked
@return {Object} This chainable object


function timeout(newTimeout) {
	var self = this;
	argy(arguments)
		.ifForm('', function() {
			self._struct.push({ type: 'timeout', delay: false });
		})
		.ifForm('boolean', function(setTimeout) {
			if (setTimeout) throw new Error('When calling .timeout(Boolean) only False is accepted to disable the timeout');
			self._struct.push({ type: 'timeout', delay: false });
		})
		.ifForm('number', function(delay) {
			self._struct.push({ type: 'timeout', delay: delay });
		})
		.ifForm('function', function(callback) {
			self._struct.push({ type: 'timeout', callback: callback });
		})
		.ifForm('number function', function(delay, callback) {
			self._struct.push({ type: 'timeout', delay: delay, callback: callback });
		})
		.ifForm('function number', function(delay, callback) {
			self._struct.push({ type: 'timeout', delay: delay, callback: callback });
		})
		.ifFormElse(function(form) {
			throw new Error('Unknown call style for .timeout():' + form);
		});

	return self;
}

Queue up a timeout setter
@param {number|function|false} Either a number (time in ms) of the timeout, a function to set the timeout handler to or falsy to disable
@return {Object} This chainable object


function _timeoutHandler() {
	var currentTaskIndex = this._struct.findIndex(function(task) { return ! task.completed });

	if (!currentTaskIndex < 0) {
		console.log('Async-Chainable timeout on unknown task');
		console.log('Full structure:', this._struct);
	} else {
		console.log('Async-Chainable timeout: Task #', currentTaskIndex + 1, '(' + this._struct[currentTaskIndex].type + ')', 'elapsed timeout of', this._options.timeout + 'ms');
	}

	this.fire('timeout');
}

The default timeout handler
This function displays a simple error message and also fires the 'timeout' hook

The default timeout handler This function displays a simple error message and also fires the timeout hook


function run(context, fn, finish, args) {
	// Argument mangling {{{
	if (typeof context == 'function') { // called as run(fn, finish, args);
		args = finish;
		finish = fn;
		fn = context;
		context = this;
	}
	// }}}

	if (isPromise(fn)) { // Given a promise that has already resolved?
		fn
			.then(function(value) {
				finish.apply(context, [null, value]);
			})
			.catch(function(err) {
				finish.call(context, err || 'An error occured');
			});
	} else if (hasCallback(fn)) { // Callback w/ (err, result) pattern
		var result = fn.apply(context, args ? [finish].concat(args) : [finish]);
		if (isPromise(result)) {
			result
				.then(function(value) { // Remap result from (val) => (err, val)
					finish.apply(context, [null, value]);
				})
				.catch(function(err) {
					finish.call(context, err || 'An error occured');
				});
		}
	} else { // Maybe either a promise or sync function?
		var result;
		try {
			result = fn.apply(context, args || []); // Run the function and see what it gives us
		} catch (e) {
			finish.call(context, e);
		}
		if (isPromise(result)) { // Got back a promise - attach to the .then() function
			result
				.then(function(value) { // Remap result from (val) => (err, val)
					finish.apply(context, [null, value]);
				})
				.catch(function(err) {
					finish.call(context, err || 'An error occured');
				});
		} else { // Didn't provide back a promise - assume it was a sync function
			finish.apply(context, [null, result]);
		}
	}
}

Run a single function, promise return, promise factory or any other combination - then a callback when finished
Take a function reference and treat it as a callback style function
If the function returns a promise this behaviour is transformed into a callback style function

This function accepts all types of input functions:
- callback functions (e.g. `next => ...`)
- async functions (e.g. `async ()=> ...`)
- promise functions (e.g. `new Promise(resolve => ...)`)
- promise factories (e.g. `()=> new Promise(resolve => ...)`)

@param {Object} context The context object to pass to the function
@param {function|Promise} fn The function to run or the promise to resolve
@param {function} finish The function to call when finished
@param {array} [args] Additional arguments to pass when calling the function

@example Run a regular callback function - if func is callback its just passed through, if its a promise its mapped normally
run(func, thenFunc)

Run a single function promise return promise factory or any other combination - then a callback when finished Take a function reference and treat it as a callback style function If the function returns a promise this behaviour is transformed into a callback style function


function runWhile(iter, limit, callback) {
	var index = 0;
	var hasExited = false;
	var err;
	var running = 0;
	if (!Number.isFinite(limit)) limit = 10;

	var invoke = function() {
		iter.call(this._context, function(taskErr, taskResult) {
			if (taskErr) err = taskErr;
			if (taskErr || !taskResult) hasExited = true;
			--running;
			if (err && !running) {
				callback(err, res);
			} else if (running <= 0 && hasExited) {
				callback(err);
			} else if (!hasExited) {
				setTimeout(invoke);
			}
		}, index++);
	};

	for (var i = 0; i < limit; i++) {
		running++;

		setTimeout(invoke);
	}

	return this;
}

function runWhile ( iter , limit , callback ) { var index = 0 ; var hasExited = false ; var err ; var running = 0 ; if ( ! Number . isFinite ( limit ) ) limit = 10 ; var invoke = function ( ) { iter . call ( this . _context , function ( taskErr , taskResult ) { if ( taskErr ) err = taskErr ; if ( taskErr || ! taskResult ) hasExited = true ; -- running ; if ( err && ! running ) { callback ( err , res ) ; } else if ( running <= 0 && hasExited ) { callback ( err ) ; } else if ( ! hasExited ) { setTimeout ( invoke ) ; } } , index ++ ) ; } ; for ( var i = 0 ; i < limit ; i ++ ) { running ++ ; setTimeout ( invoke ) ; } return this ; }

Internal function to run a callback until it returns a falsy value
@param {function} iter The function to invoke on each call with the arguments (next, index)
@param {number} limit The number of parallel threads to execute. This must be a finite number (defaults to 10 if not)
@param {function} callback The function to invoke when iter finally returns a falsy value
@return {Object} This chainable object


function reset() {
	this._struct = [];
	this._structPointer = 0;

	var reAttachContext = (this._options.context == this._context); // Reattach the context pointer after reset?
	this._context = {
		_struct: this._struct,
		_structPointer: this._structPointer,
		_options: this._options,
		_deferredRunning: this._deferredRunning,
		hook: this.hook.bind(this),
		fire: this.fire.bind(this),
	};

	if (reAttachContext) this._options.context = this._context;
}

}}}
Reset all state variables and return the object into a pristine condition
@return {Object} This chainable object


function hook() {
	var self = this;
	argy(arguments)
		.ifForm('', function() {})
		.ifForm('string function', function(hook, callback) { // Attach to one hook
			if (!self._hooks[hook]) self._hooks[hook] = [];
			self._hooks[hook].push({cb: callback});
		})
		.ifForm('string string function', function(hook, id, callback) { // Attach a named hook
			if (!self._hooks[hook]) self._hooks[hook] = [];
			self._hooks[hook].push({id: id, cb: callback});
		})
		.ifForm('string array function', function(hook, prereqs, callback) { // Attach to a hook with prerequisites
			if (!self._hooks[hook]) self._hooks[hook] = [];
			self._hooks[hook].push({prereqs: prereqs, cb: callback});
		})
		.ifForm('string string array function', function(hook, id, prereqs, callback) { // Attach a named hook with prerequisites
			if (!self._hooks[hook]) self._hooks[hook] = [];
			self._hooks[hook].push({id: id, prereqs: prereqs, cb: callback});
		})
		.ifForm('array function', function(hooks, callback) { // Attach to many hooks
			hooks.forEach(function(hook) {
				if (!self._hooks[hook]) self._hooks[hook] = [];
				self._hooks[hook].push({cb: callback});
			});
		})
		.ifFormElse(function(form) {
			throw new Error('Unknown call style for .on(): ' + form);
		});

	return self;
}

Hooks {{{
Set up a hook
@param {string} hook The hook name
@param {string} [name] The function ID
@param {array} [prereqs] Optional prerequisites to fired
@param {function} callback Callback to run when hook fires (each callback takes a next paramter which must be called)
@return {Object} This chainable object


function tag(name) {
    if (!this.comment || !this.comment.tags) {
      return null;
    }

    for (var i = 0; i < this.comment.tags.length; i++) {
      var tagObj = this.comment.tags[i];
      if (tagObj.name === name) {
        return tagObj.value;
      }
    }
    return null;
  }

function tag ( name ) { if ( ! this . comment || ! this . comment . tags ) { return null ; } for ( var i = 0 ; i < this . comment . tags . length ; i ++ ) { var tagObj = this . comment . tags [ i ] ; if ( tagObj . name === name ) { return tagObj . value ; } } return null ; }

Return the first tag with a name=name
@param {string} name
@returns {*}


function checkPattern(file, blackList, whiteList){

  if (util.isRegExp(blackList) && blackList.test(file)) {
    return false;
  }

  if (util.isRegExp(whiteList)) {
    if (whiteList.test(file)) {
      return true;
    }
    return false;
  }

  return true;
}

function checkPattern ( file , blackList , whiteList ) { if ( util . isRegExp ( blackList ) && blackList . test ( file ) ) { return false ; } if ( util . isRegExp ( whiteList ) ) { if ( whiteList . test ( file ) ) { return true ; } return false ; } return true ; }

Helper functions

Checks blackList- and whitList-regex against
the given file name and returns if this file can
be deleted.

@param string file - the gile name
@param regex|undefined blackList
@param regex|undefined - whiteList
@returns {boolean}

Helper functions Checks blackList - and whitList - regex against the given file name and returns if this file can be deleted .


function Seven(_a) {
                    var _b = _a === void 0 ? {} : _a, height = _b.height, width = _b.width, _c = _b.angle, angle = _c === void 0 ? 10 : _c, _d = _b.ratioLtoW, ratioLtoW = _d === void 0 ? 4 : _d, _e = _b.ratioLtoS, ratioLtoS = _e === void 0 ? 32 : _e, _f = _b.digit, digit = _f === void 0 ? Digit.BLANK : _f;
                    /** The cononical points for a horizontal segment for the given configuration. */
                    this._horizontalSegmentGeometry = [
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 }
                    ];
                    /** The cononical points for a vertical segment for the given configuration. */
                    this._verticalSegmentGeometry = [
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 },
                        { x: 0, y: 0 }
                    ];
                    /** The x and y shifts that must be applied to each segment. */
                    this._translations = [
                        { x: 0, y: 0, a: this._horizontalSegmentGeometry },
                        { x: 0, y: 0, a: this._verticalSegmentGeometry },
                        { x: 0, y: 0, a: this._verticalSegmentGeometry },
                        { x: 0, y: 0, a: this._horizontalSegmentGeometry },
                        { x: 0, y: 0, a: this._verticalSegmentGeometry },
                        { x: 0, y: 0, a: this._verticalSegmentGeometry },
                        { x: 0, y: 0, a: this._horizontalSegmentGeometry }
                    ];
                    /** The segments, A-G of the digit. */
                    this.segments = [new Segment(), new Segment(), new Segment(), new Segment(), new Segment(), new Segment(), new Segment()];
                    this._angleDegree = angle;
                    this.digit = digit;
                    this._ratioLtoW = ratioLtoW;
                    this._ratioLtoS = ratioLtoS;
                    this._height = this._width = 100; //initialize so checkConfig passes, and for default case
                    this._isHeightFixed = true;
                    if (height !== undefined) {
                        this._height = height;
                    }
                    else if (width !== undefined) {
                        this._width = width;
                        this._isHeightFixed = false;
                    } //else - neither specified, default to height=100
                    this._positionSegments();
                }

Construct a new Seven object.
Optionally pass a SevenConfig object to set properties.
Each property of the SevenConfig object is optional.
If the passed in config contains bad values an exception will be thrown.

Construct a new Seven object . Optionally pass a SevenConfig object to set properties . Each property of the SevenConfig object is optional . If the passed in config contains bad values an exception will be thrown .


function onChange(event) { try {
		if (remove()) { return; }
		resolve(Array.from(input.files)); // actually got file(s)
	} catch (error) { reject(error); } }

function
onChange
(
event
)
{
try
{
if
(
remove
(
)
)
{
return
;
}
resolve
(
Array
.
from
(
input
.
files
)
)
;
// actually got file(s)
}
catch
(
error
)
{
reject
(
error
)
;
}
}


function RemoveObserver_init(ref, node) {
	let self = Self.get(node);
	if (!self) {
		self = new RemoveObserverPrivate(node);
		Self.set(node, self);
	}
	Self.set(ref, self);
}

function RemoveObserver_init ( ref , node ) { let self = Self . get ( node ) ; if ( ! self ) { self = new RemoveObserverPrivate ( node ) ; Self . set ( node , self ) ; } Self . set ( ref , self ) ; }

there are no properties on a `RemoveObserver`, every object that went as ref through this function can be used as `this` in any of the RemoveObserver methods

there are no properties on a RemoveObserver every object that went as ref through this function can be used as this in any of the RemoveObserver methods


function parsePropertyChains(expr) {
  var parsedExpr = '', chain;

  // allow recursion (e.g. into function args) by resetting propertyRegex
  // This is more efficient than creating a new regex for each chain, I assume
  var prevCurrentIndex = currentIndex;
  var prevLastIndex = propertyRegex.lastIndex;

  currentIndex = 0;
  propertyRegex.lastIndex = 0;
  while ((chain = nextChain(expr)) !== false) {
    parsedExpr += chain;
  }

  // Reset indexes
  currentIndex = prevCurrentIndex;
  propertyRegex.lastIndex = prevLastIndex;
  return parsedExpr;
}

Finds and parses the property chains in an expression.

Finds and parses the property chains in an expression .


function parseFunction(link, index, expr) {
  var call = getFunctionCall(expr);

  // Always call functions in the scope of the object they're a member of
  if (index === 0) {
    link = addThisOrGlobal(link);
  } else {
    link = '_ref' + currentReference + link;
  }

  var calledLink = link + '(~~insideParens~~)';

  link = 'typeof ' + link + ' !== \'function\' ? void 0 : ' + calledLink;
  var insideParens = call.slice(1, -1);

  if (expr.charAt(propertyRegex.lastIndex) === '.') {
    currentReference = ++referenceCount;
    var ref = '_ref' + currentReference;
    link = '(' + ref + ' = (' + link + ')) == null ? void 0 : ';
  }

  var ref = currentReference;
  link = link.replace('~~insideParens~~', parsePropertyChains(insideParens));
  currentReference = ref;
  return link;
}

Handles a function to be called in its correct scope Finds the end of the function and processes the arguments


function parseBrackets(link, index, expr) {
  var call = getFunctionCall(expr);
  var insideBrackets = call.slice(1, -1);
  var evaledLink = parsePart(link, index);
  index += 1;
  link = '[~~insideBrackets~~]';

  if (expr.charAt(propertyRegex.lastIndex) === '.') {
    link = parsePart(link, index);
  } else {
    link = '_ref' + currentReference + link;
  }

  link = evaledLink + link;

  var ref = currentReference;
  link = link.replace('~~insideBrackets~~', parsePropertyChains(insideBrackets));
  currentReference = ref;
  return link;
}

function parseBrackets ( link , index , expr ) { var call = getFunctionCall ( expr ) ; var insideBrackets = call . slice ( 1 , - 1 ) ; var evaledLink = parsePart ( link , index ) ; index += 1 ; link = '[~~insideBrackets~~]' ; if ( expr . charAt ( propertyRegex . lastIndex ) === '.' ) { link = parsePart ( link , index ) ; } else { link = '_ref' + currentReference + link ; } link = evaledLink + link ; var ref = currentReference ; link = link . replace ( '~~insideBrackets~~' , parsePropertyChains ( insideBrackets ) ) ; currentReference = ref ; return link ; }

Handles a bracketed expression to be parsed


function addReferences(expr) {
  if (referenceCount) {
    var refs = [];
    for (var i = 1; i <= referenceCount; i++) {
      refs.push('_ref' + i);
    }
    expr = 'var ' + refs.join(', ') + ';\n' + expr;
  }
  return expr;
}

function
addReferences
(
expr
)
{
if
(
referenceCount
)
{
var
refs
=
[
]
;
for
(
var
i
=
1
;
i
<=
referenceCount
;
i
++
)
{
refs
.
push
(
'_ref'
+
i
)
;
}
expr
=
'var '
+
refs
.
join
(
', '
)
+
';\n'
+
expr
;
}
return
expr
;
}


function(fn) {
    var pending
    var hasNext

    function next() {
      setTimeout(function() {
        if (pending === false) return
        pending = false

        if (hasNext) {
          hasNext = false
          fn(next)
        }
      }, 50) // call after gulp ending handler done
    }
    return function() {
      if (pending) return (hasNext = true)

      pending = true
      fn(next)
    }
  }

function
(
fn
)
{
var
pending
var
hasNext
function
next
(
)
{
setTimeout
(
function
(
)
{
if
(
pending
===
false
)
return
pending
=
false
if
(
hasNext
)
{
hasNext
=
false
fn
(
next
)
}
}
,
50
)
// call after gulp ending handler done
}
return
function
(
)
{
if
(
pending
)
return
(
hasNext
=
true
)
pending
=
true
fn
(
next
)
}
}


function assert (t, m) {
  if (!t) {
    var err = new AssertionError(m)
    if (Error.captureStackTrace) Error.captureStackTrace(err, assert)
    throw err
  }
}

function assert ( t , m ) { if ( ! t ) { var err = new AssertionError ( m ) if ( Error . captureStackTrace ) Error . captureStackTrace ( err , assert ) throw err } }

Minimal assert function
@param  {any} t Value to check if falsy
@param  {string=} m Optional assertion error message
@throws {AssertionError}


function bindArguments(func) {
  function binder() {
    return func.apply(this, args.concat(slice.call(arguments)));
  }

  var args = slice.call(arguments, 1);
  return binder;
}

function bindArguments ( func ) { function binder ( ) { return func . apply ( this , args . concat ( slice . call ( arguments ) ) ) ; } var args = slice . call ( arguments , 1 ) ; return binder ; }

a custom "bind" function to bind arguments to a function without binding the context

a custom bind function to bind arguments to a function without binding the context


function getExceptions() {
      const openers = [];
      const closers = [];

      if ( options.braceException ) {
        openers.push('{');
        closers.push('}');
      }

      if ( options.bracketException ) {
        openers.push('[');
        closers.push(']');
      }

      if ( options.parenException ) {
        openers.push('(');
        closers.push(')');
      }

      if ( options.empty ) {
        openers.push(')');
        closers.push('(');
      }

      return {
        openers,
        closers
      };
    }

function getExceptions ( ) { const openers = [ ] ; const closers = [ ] ; if ( options . braceException ) { openers . push ( '{' ) ; closers . push ( '}' ) ; } if ( options . bracketException ) { openers . push ( '[' ) ; closers . push ( ']' ) ; } if ( options . parenException ) { openers . push ( '(' ) ; closers . push ( ')' ) ; } if ( options . empty ) { openers . push ( ')' ) ; closers . push ( '(' ) ; } return { openers , closers } ; }

Produces an object with the opener and closer exception values
@param {Object} opts The exception options
@returns {Object} `openers` and `closers` exception values
@private


function shouldOpenerHaveSpace( left, right ) {
      if ( sourceCode.isSpaceBetweenTokens( left, right ) ) {
        return false;
      }

      if ( ALWAYS ) {
        if ( astUtils.isClosingParenToken( right ) ) {
          return false;
        }
        return !isOpenerException( right );
      }
      return isOpenerException( right );
    }

function shouldOpenerHaveSpace ( left , right ) { if ( sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { if ( astUtils . isClosingParenToken ( right ) ) { return false ; } return ! isOpenerException ( right ) ; } return isOpenerException ( right ) ; }

Determines if an opener paren should have a missing space after it
@param {Object} left The paren token
@param {Object} right The token after it
@returns {boolean} True if the paren should have a space


function shouldCloserHaveSpace( left, right ) {
      if ( astUtils.isOpeningParenToken( left ) ) {
        return false;
      }

      if ( sourceCode.isSpaceBetweenTokens( left, right ) ) {
        return false;
      }

      if ( ALWAYS ) {
        return !isCloserException( left );
      }
      return isCloserException( left );
    }

function shouldCloserHaveSpace ( left , right ) { if ( astUtils . isOpeningParenToken ( left ) ) { return false ; } if ( sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return ! isCloserException ( left ) ; } return isCloserException ( left ) ; }

Determines if an closer paren should have a missing space after it
@param {Object} left The token before the paren
@param {Object} right The paren token
@returns {boolean} True if the paren should have a space


function shouldOpenerRejectSpace( left, right ) {
      if ( right.type === 'Line' ) {
        return false;
      }

      if ( !astUtils.isTokenOnSameLine( left, right ) ) {
        return false;
      }

      if ( !sourceCode.isSpaceBetweenTokens( left, right ) ) {
        return false;
      }

      if ( ALWAYS ) {
        return isOpenerException( right );
      }
      return !isOpenerException( right );
    }

function shouldOpenerRejectSpace ( left , right ) { if ( right . type === 'Line' ) { return false ; } if ( ! astUtils . isTokenOnSameLine ( left , right ) ) { return false ; } if ( ! sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return isOpenerException ( right ) ; } return ! isOpenerException ( right ) ; }

Determines if an opener paren should not have an existing space after it
@param {Object} left The paren token
@param {Object} right The token after it
@returns {boolean} True if the paren should reject the space


function shouldCloserRejectSpace( left, right ) {
      if ( astUtils.isOpeningParenToken( left ) ) {
        return false;
      }

      if ( !astUtils.isTokenOnSameLine( left, right ) ) {
        return false;
      }

      if ( !sourceCode.isSpaceBetweenTokens( left, right ) ) {
        return false;
      }

      if ( ALWAYS ) {
        return isCloserException( left );
      }
      return !isCloserException( left );
    }

function shouldCloserRejectSpace ( left , right ) { if ( astUtils . isOpeningParenToken ( left ) ) { return false ; } if ( ! astUtils . isTokenOnSameLine ( left , right ) ) { return false ; } if ( ! sourceCode . isSpaceBetweenTokens ( left , right ) ) { return false ; } if ( ALWAYS ) { return isCloserException ( left ) ; } return ! isCloserException ( left ) ; }

Determines if an closer paren should not have an existing space after it
@param {Object} left The token before the paren
@param {Object} right The paren token
@returns {boolean} True if the paren should reject the space


function defineConfigurable ( obj, key, val ) {
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: false,
      writable: true,
      value: val
    });
  }

function defineConfigurable ( obj , key , val ) { Object . defineProperty ( obj , key , { configurable : true , enumerable : false , writable : true , value : val } ) ; }

set a value as configurable and non-enumerable

set a value as configurable and non - enumerable


function ToInteger ( argument ) {
    var number = +argument;
    if ( number !== number ) {
      return 0;
    }
    if ( number === 0 || number === Infinity || number === -Infinity ) {
      return number;
    }
    return ( number >= 0 ? 1 : -1 ) * Math.floor(Math.abs(number));
  }

function ToInteger ( argument ) { var number = + argument ; if ( number !== number ) { return 0 ; } if ( number === 0 || number === Infinity || number === - Infinity ) { return number ; } return ( number >= 0 ? 1 : - 1 ) * Math . floor ( Math . abs ( number ) ) ; }


function ToLength ( argument ) {
    var len = ToInteger(argument);
    return len <= 0 ? 0 : Math.min(len, Math.pow(2, 53) - 1);
  }

function ToLength ( argument ) { var len = ToInteger ( argument ) ; return len <= 0 ? 0 : Math . min ( len , Math . pow ( 2 , 53 ) - 1 ) ; }


function CreateArrayIterator ( array, kind ) {
    var O = ToObject(array),
      iterator = Object.create(ArrayIteratorPrototype);
    defineInternal(iterator, '[[IteratedObject]]', O);
    defineInternal(iterator, '[[ArrayIteratorNextIndex]]', 0);
    defineInternal(iterator, '[[ArrayIteratorKind]]', kind);
    return iterator;
  }

function CreateArrayIterator ( array , kind ) { var O = ToObject ( array ) , iterator = Object . create ( ArrayIteratorPrototype ) ; defineInternal ( iterator , '[[IteratedObject]]' , O ) ; defineInternal ( iterator , '[[ArrayIteratorNextIndex]]' , 0 ) ; defineInternal ( iterator , '[[ArrayIteratorKind]]' , kind ) ; return iterator ; }

22.1.5.1 CreateArrayIterator Abstract Operation


function PromiseResolve () {
    return function F ( resolution ) {
      var promise = F['[[Promise]]'], reactions;
      if ( Type(promise) !== 'object' ) {
        throw TypeError();
      }
      if ( promise['[[PromiseStatus]]'] !== 'unresolved' ) {
        return undefined;
      }
      reactions = promise['[[PromiseResolveReactions]]'];
      defineInternal(promise, '[[PromiseResult]]', resolution);
      defineInternal(promise, '[[PromiseResolveReactions]]', undefined);
      defineInternal(promise, '[[PromiseRejectReactions]]', undefined);
      defineInternal(promise, '[[PromiseStatus]]', 'has-resolution');
      return TriggerPromiseReactions(reactions, resolution);
    };
  }

function PromiseResolve ( ) { return function F ( resolution ) { var promise = F [ '[[Promise]]' ] , reactions ; if ( Type ( promise ) !== 'object' ) { throw TypeError ( ) ; } if ( promise [ '[[PromiseStatus]]' ] !== 'unresolved' ) { return undefined ; } reactions = promise [ '[[PromiseResolveReactions]]' ] ; defineInternal ( promise , '[[PromiseResult]]' , resolution ) ; defineInternal ( promise , '[[PromiseResolveReactions]]' , undefined ) ; defineInternal ( promise , '[[PromiseRejectReactions]]' , undefined ) ; defineInternal ( promise , '[[PromiseStatus]]' , 'has-resolution' ) ; return TriggerPromiseReactions ( reactions , resolution ) ; } ; }


function GetCapabilitiesExecutor () {
    return function F ( resolve, reject ) {
      var promiseCapability = F['[[Capability]]'];
      if ( Type(promiseCapability['[[Resolve]]']) !== 'undefined' ) {
        throw TypeError();
      }
      if ( Type(promiseCapability['[[Reject]]']) !== 'undefined' ) {
        throw TypeError();
      }
      defineInternal(promiseCapability, '[[Resolve]]', resolve);
      defineInternal(promiseCapability, '[[Reject]]', reject);
    };
  }

function GetCapabilitiesExecutor ( ) { return function F ( resolve , reject ) { var promiseCapability = F [ '[[Capability]]' ] ; if ( Type ( promiseCapability [ '[[Resolve]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } if ( Type ( promiseCapability [ '[[Reject]]' ] ) !== 'undefined' ) { throw TypeError ( ) ; } defineInternal ( promiseCapability , '[[Resolve]]' , resolve ) ; defineInternal ( promiseCapability , '[[Reject]]' , reject ) ; } ; }


function PromiseResolutionHandlerFunction () {
    return function F ( x ) {
      var promise = F['[[Promise]]'],
        fulfillmentHandler = F['[[FulfillmentHandler]]'],
        rejectionHandler = F['[[RejectionHandler]]'],
        selfResolutionError, C, promiseCapability, updateResult;
      if ( SameValue(x, promise) ) {
        selfResolutionError = TypeError();
        return rejectionHandler.call(undefined, selfResolutionError);
      }
      C = promise['[[PromiseConstructor]]'];
      try {
        promiseCapability = NewPromiseCapability(C);
      } catch ( e ) {
        return e;
      }
      try {
        updateResult = UpdatePromiseFromPotentialThenable(x,
          promiseCapability
        );
      } catch ( e ) {
        return e;
      }
      if ( updateResult !== 'not a thenable') {
        return promiseCapability['[[Promise]]'].then(fulfillmentHandler,
          rejectionHandler
        );
      }
      return fulfillmentHandler.call(undefined, x);
    };
  }

function
PromiseResolutionHandlerFunction
(
)
{
return
function
F
(
x
)
{
var
promise
=
F
[
'[[Promise]]'
]
,
fulfillmentHandler
=
F
[
'[[FulfillmentHandler]]'
]
,
rejectionHandler
=
F
[
'[[RejectionHandler]]'
]
,
selfResolutionError
,
C
,
promiseCapability
,
updateResult
;
if
(
SameValue
(
x
,
promise
)
)
{
selfResolutionError
=
TypeError
(
)
;
return
rejectionHandler
.
call
(
undefined
,
selfResolutionError
)
;
}
C
=
promise
[
'[[PromiseConstructor]]'
]
;
try
{
promiseCapability
=
NewPromiseCapability
(
C
)
;
}
catch
(
e
)
{
return
e
;
}
try
{
updateResult
=
UpdatePromiseFromPotentialThenable
(
x
,
promiseCapability
)
;
}
catch
(
e
)
{
return
e
;
}
if
(
updateResult
!==
'not a thenable'
)
{
return
promiseCapability
[
'[[Promise]]'
]
.
then
(
fulfillmentHandler
,
rejectionHandler
)
;
}
return
fulfillmentHandler
.
call
(
undefined
,
x
)
;
}
;
}


function(target, sequence, t) {//t==trigger (usually a 'click'ish event)
            sequence = sequence.split(_.splitRE);
            for (var i=0, e, props; i<sequence.length && (!e||!e.isSequenceStopped()); i++) {
                props = _.parse(sequence[i]);
                if (props) {
                    props.sequence = sequence;
                    if (e){ props.previousEvent = e; }
                    if (t){ props.trigger = t; }
                    _.controls(props, target, sequence, i);
                    e = _.event(target, props);
                }
            }
            return e;
        }


function(e) {
            var el = e.target, attr,
                type = e.type,
                key = type.indexOf('key') === 0 ? e.which || e.keyCode || '' : '',
                special = _.special[type+key];
            if (el && special) {
                type = special(e, el, el.nodeName.toLowerCase());
                if (!type){ return; }// special said to ignore it!
            }
            el = _.find(el, type),
            attr = _.attr(el, type);
            if (attr) {
                _.all(el, attr, e);
                if (type === 'click' && !_.boxRE.test(el.type)) {
                    e.preventDefault();
                }
            }
        }

function
(
e
)
{
var
el
=
e
.
target
,
attr
,
type
=
e
.
type
,
key
=
type
.
indexOf
(
'key'
)
===
0
e
.
which
||
e
.
keyCode
||
''
:
''
,
special
=
_
.
special
[
type
+
key
]
;
if
(
el
&&
special
)
{
type
=
special
(
e
,
el
,
el
.
nodeName
.
toLowerCase
(
)
)
;
if
(
!
type
)
{
return
;
}
// special said to ignore it!
}
el
=
_
.
find
(
el
,
type
)
,
attr
=
_
.
attr
(
el
,
type
)
;
if
(
attr
)
{
_
.
all
(
el
,
attr
,
e
)
;
if
(
type
===
'click'
&&
!
_
.
boxRE
.
test
(
el
.
type
)
)
{
e
.
preventDefault
(
)
;
}
}
}


function reportNoEndingSpace( node, token, tokenBefore ) {
    context.report({
      node: node,
      loc: token.loc.start,
      message: 'There should be no space before \'' + token.value + '\'',
      fix: function( fixer ) {
        return fixer.removeRange([ tokenBefore.range[ 1 ], token.range[ 0 ] ]);
      }
    });
  }

function
reportNoEndingSpace
(
node
,
token
,
tokenBefore
)
{
context
.
report
(
{
node
:
node
,
loc
:
token
.
loc
.
start
,
message
:
'There should be no space before \''
+
token
.
value
+
'\''
,
fix
:
function
(
fixer
)
{
return
fixer
.
removeRange
(
[
tokenBefore
.
range
[
1
]
,
token
.
range
[
0
]
]
)
;
}
}
)
;
}

Reports that there shouldn't be a space before the last token
@param {ASTNode} node - The node to report in the event of an error.
@param {Token} token - The token to use for the report.
@param {Token} tokenBefore - The token before `token`.
@returns {void}

Reports that there shouldn t be a space before the last token


function reportRequiredBeginningSpace( node, token ) {
    context.report({
      node: node,
      loc: token.loc.start,
      message: 'A space is required after \'' + token.value + '\'',
      fix: function( fixer ) {
        return fixer.insertTextAfter( token, ' ' );
      }
    });
  }

function
reportRequiredBeginningSpace
(
node
,
token
)
{
context
.
report
(
{
node
:
node
,
loc
:
token
.
loc
.
start
,
message
:
'A space is required after \''
+
token
.
value
+
'\''
,
fix
:
function
(
fixer
)
{
return
fixer
.
insertTextAfter
(
token
,
' '
)
;
}
}
)
;
}

Reports that there should be a space after the first token
@param {ASTNode} node - The node to report in the event of an error.
@param {Token} token - The token to use for the report.
@returns {void}


function reportRequiredEndingSpace( node, token ) {
    context.report({
      node: node,
      loc: token.loc.start,
      message: 'A space is required before \'' + token.value + '\'',
      fix: function( fixer ) {
        return fixer.insertTextBefore( token, ' ' );
      }
    });
  }

function
reportRequiredEndingSpace
(
node
,
token
)
{
context
.
report
(
{
node
:
node
,
loc
:
token
.
loc
.
start
,
message
:
'A space is required before \''
+
token
.
value
+
'\''
,
fix
:
function
(
fixer
)
{
return
fixer
.
insertTextBefore
(
token
,
' '
)
;
}
}
)
;
}

Reports that there should be a space before the last token
@param {ASTNode} node - The node to report in the event of an error.
@param {Token} token - The token to use for the report.
@returns {void}


function generateDestinationLonLat ({
  lat,
  lon
}) {
  const latOffset = (getDistance() / LAT_DEGREE) * getSign()
  const lonOffset = (getDistance() / (LAT_DEGREE * Math.cos(lat))) * getSign()
  return {
    lat: lat + latOffset,
    lon: lon + lonOffset
  }
}

function generateDestinationLonLat ( { lat , lon } ) { const latOffset = ( getDistance ( ) / LAT_DEGREE ) * getSign ( ) const lonOffset = ( getDistance ( ) / ( LAT_DEGREE * Math . cos ( lat ) ) ) * getSign ( ) return { lat : lat + latOffset , lon : lon + lonOffset } }

Get a random point offset from the origin


function (keyParts, hash) {

		for (var i = 0; i < keyParts.length-1; ++i) {
			hash = getValue(keyParts[i], hash);
			if (typeof(hash) === 'undefined') {
				return undefined;
			}
		}

		var lastKeyPartIndex = keyParts.length-1;
		return getValue(keyParts[lastKeyPartIndex], hash)
	}

function ( keyParts , hash ) { for ( var i = 0 ; i < keyParts . length - 1 ; ++ i ) { hash = getValue ( keyParts [ i ] , hash ) ; if ( typeof ( hash ) === 'undefined' ) { return undefined ; } } var lastKeyPartIndex = keyParts . length - 1 ; return getValue ( keyParts [ lastKeyPartIndex ] , hash ) }

Get a nested value from the specified object. Returns undefined if not found.

Get a nested value from the specified object . Returns undefined if not found .


function gitAuthors (cb) {
  return exec('git log --pretty="%an <%ae>"', function (er, stdout, stderr) {
    if (er || stderr) throw new Error(er || stderr)
    return cb(null, stdout.split('\n').reverse())
  })
}

function
gitAuthors
(
cb
)
{
return
exec
(
'git log --pretty="%an <%ae>"'
,
function
(
er
,
stdout
,
stderr
)
{
if
(
er
||
stderr
)
throw
new
Error
(
er
||
stderr
)
return
cb
(
,
stdout
.
split
(
'\n'
)
.
reverse
(
)
)
}
)
}

returns array of strings like "firstname lastname <email@host.com>" - first contributions are first in the list - contains duplicates - might not have a real email - might not have real name

returns array of strings like firstname lastname <email


function lookupGithubLogin (p, print, callback) {
  var apiURI = 'https://api.github.com/search/users?q='
  var options = { json: true, headers: { 'user-agent': pkg.name + '/' + pkg.version } }
  if (process.env.OAUTH_TOKEN) {
    options.headers['Authorization'] = 'token ' + process.env.OAUTH_TOKEN.trim()
  }
  function cb (err, p) {
    callback(err, p)
  }
  if (print) process.stdout.write('.')

  request(apiURI + encodeURIComponent(p.email + ' in:email type:user'), options, onEmail)
  function onEmail (err, data) {
    rateLimitExceeded = rateLimitExceeded || data.body.message
    if (!err && data.body.items && data.body.items[0]) {
      p.login = data.body.items[0].login
      return cb(err, p)
    }
    request(apiURI + encodeURIComponent(p.name + ' in:fullname type:user'), options, onName)
  }
  function onName (err, data) {
    rateLimitExceeded = rateLimitExceeded || data.body.message
    if (!err && data.body.items && data.body.items[0]) {
      p.login = data.body.items[0].login
      return cb(err, p)
    }
    cb(err, p)
  }
}

look for the email first. if no results, look for the name.

look for the email first . if no results look for the name .


function _unpackOutput(message) {
    if (message.charAt(0) != keyczar_util.VERSION_BYTE) {
        throw new Error('Unsupported version byte: ' + message.charCodeAt(0));
    }

    var keyhash = message.substr(1, keyczar_util.KEYHASH_LENGTH);
    message = message.substr(1 + keyczar_util.KEYHASH_LENGTH);
    return {keyhash: keyhash, message: message};
}

function
_unpackOutput
(
message
)
{
if
(
message
.
charAt
(
0
)
!=
keyczar_util
.
VERSION_BYTE
)
{
throw
new
Error
(
'Unsupported version byte: '
+
message
.
charCodeAt
(
0
)
)
;
}
var
keyhash
=
message
.
substr
(
1
,
keyczar_util
.
KEYHASH_LENGTH
)
;
message
=
message
.
substr
(
1
+
keyczar_util
.
KEYHASH_LENGTH
)
;
return
{
keyhash
:
keyhash
,
message
:
message
}
;
}


function _rsaHash(publicKey) {
    var md = forge.md.sha1.create();

    // hash:
    // 4-byte big endian length
    // "magnitude" of the public modulus (trim all leading zero bytes)
    // same for the exponent
    _hashBigNumber(md, publicKey.n);
    _hashBigNumber(md, publicKey.e);
    var digest = md.digest();
    return digest.getBytes(keyczar_util.KEYHASH_LENGTH);
}

Returns the keyhash for an RSA public key.

Returns the keyhash for an RSA public key .


function _makeRsaKey(rsaKey) {
    var key = {
        keyhash: _rsaHash(rsaKey),
        size: rsaKey.n.bitLength()
    };

    key.encrypt = function(plaintext) {
        // needed to make this work with private keys
        var tempKey = forge.pki.setRsaPublicKey(rsaKey.n, rsaKey.e);
        var ciphertext = tempKey.encrypt(plaintext, 'RSA-OAEP');
        return _packOutput(key.keyhash, ciphertext);
    };

    key.verify = function(message, signature) {
        signature = _unpackOutput(signature);
        _checkKeyHash(key.keyhash, signature);

        var digest = _mdForSignature(message).digest().getBytes();

        // needed to make this work with private keys
        var tempKey = forge.pki.setRsaPublicKey(rsaKey.n, rsaKey.e);
        return tempKey.verify(digest, signature.message);
    };

    return key;
}


function() {
      if (!result) {
        var exec = grunt.config.get('exec');

        for (var key in exec) {
          exec[key].cmd = nvmUse + ' && ' + exec[key].cmd;
        }

        grunt.config.set('exec', exec);
      }
    }

function
(
)
{
if
(
!
result
)
{
var
exec
=
grunt
.
config
.
get
(
'exec'
)
;
for
(
var
key
in
exec
)
{
exec
[
key
]
.
cmd
=
nvmUse
+
' && '
+
exec
[
key
]
.
cmd
;
}
grunt
.
config
.
set
(
'exec'
,
exec
)
;
}
}


function(callback) {
      var command = '. ' + nvmPath;

      childProcess.exec(command, cmdOpts, function(err, stdout, stderr) {
        if (stderr.indexOf('No such file or directory') !== -1) {
          if (nvmPath === home + '/.nvm/nvm.sh') {
            nvmPath = home + '/nvm/nvm.sh';
            nvmInit = '. ' + nvmPath + ' && ';
            checkNVM(callback);
          } else {
            grunt[options.errorLevel]('Expected node ' + expected + ', but found v' + actual + '\nNVM does not appear to be installed.\nPlease install (https://github.com/creationix/nvm#installation), or update the NVM path.');
          }
        } else {
          callback();
        }
      });
    }


function(thisPackage, callback) {
      var command = nvmUse + ' && npm install -g ' + thisPackage;

      childProcess.exec(command, cmdOpts,function(err, stdout, stderr) {
        if (err) { throw err ;}
        grunt.verbose.writeln(stdout);
        grunt.log.oklns('Installed ' + thisPackage);
        callback();
      });
    }

function
(
thisPackage
,
callback
)
{
var
command
=
nvmUse
+
' && npm install -g '
+
thisPackage
;
childProcess
.
exec
(
command
,
cmdOpts
,
function
(
err
,
stdout
,
stderr
)
{
if
(
err
)
{
throw
err
;
}
grunt
.
verbose
.
writeln
(
stdout
)
;
grunt
.
log
.
oklns
(
'Installed '
+
thisPackage
)
;
callback
(
)
;
}
)
;
}


function() {
      prompt.start();

      var prop = {
        name: 'yesno',
        message: 'You do not have any node versions installed that satisfy this project\'s requirements ('.white + expected.yellow + '). Would you like to install the latest compatible version? (y/n)'.white,
        validator: /y[es]*|n[o]?/,
        required: true,
        warning: 'Must respond yes or no'
      };

      prompt.get(prop, function (err, result) {
        result = result.yesno.toLowerCase();
        if (result === 'yes' ||
            result === 'y') {
          nvmInstall();
        } else {
          grunt[options.errorLevel]('Expected node v' + expected + ', but found ' + actual);
        }
      });

    }


function() {
      nvmLs('remote', function() {

        bestMatch = semver.maxSatisfying(remotes, expected);
        nvmUse = nvmInit + 'nvm use ' + bestMatch;

        var command = nvmInit + 'nvm install ' + bestMatch;

        childProcess.exec(command, cmdOpts,function(err, stdout, stderr) {
          if (err) { throw err ;}
          var nodeVersion = stdout.split(' ')[3];
          grunt.log.ok('Installed node v' + bestMatch);
          printVersion(nodeVersion);
          extendExec();
          checkPackages(options.globals);
        });
      });
    }

function
(
)
{
nvmLs
(
'remote'
,
function
(
)
{
bestMatch
=
semver
.
maxSatisfying
(
remotes
,
expected
)
;
nvmUse
=
nvmInit
+
'nvm use '
+
bestMatch
;
var
command
=
nvmInit
+
'nvm install '
+
bestMatch
;
childProcess
.
exec
(
command
,
cmdOpts
,
function
(
err
,
stdout
,
stderr
)
{
if
(
err
)
{
throw
err
;
}
var
nodeVersion
=
stdout
.
split
(
' '
)
[
3
]
;
grunt
.
log
.
ok
(
'Installed node v'
+
bestMatch
)
;
printVersion
(
nodeVersion
)
;
extendExec
(
)
;
checkPackages
(
options
.
globals
)
;
}
)
;
}
)
;
}


function(loc, callback) {
      var command = nvmInit + 'nvm ls';

      if (loc === 'remote') {
        command += '-remote';
      }

      childProcess.exec(command, cmdOpts, function(err, stdout, stderr) {
        var data = stripColorCodes(stdout.toString()).replace(/\s+/g, '|'),
            available = data.split('|');

        for (var i = 0; i < available.length; i++) {
          // Trim whitespace
          available[i] = available[i].replace(/\s/g, '');
          // Validate
          var ver = semver.valid(available[i]);
          if (ver) {
            if (loc === 'remote') {
              remotes.push(ver);
            } else if (loc === 'local') {
              locals.push(ver);
            }
          }
        }

        callback();
      });
    }

function
(
loc
,
callback
)
{
var
command
=
nvmInit
+
'nvm ls'
;
if
(
loc
===
'remote'
)
{
command
+=
'-remote'
;
}
childProcess
.
exec
(
command
,
cmdOpts
,
function
(
err
,
stdout
,
stderr
)
{
var
data
=
stripColorCodes
(
stdout
.
toString
(
)
)
.
replace
(
/
\s+
/
g
,
'|'
)
,
available
=
data
.
split
(
'|'
)
;
for
(
var
i
=
0
;
i
<
available
.
length
;
i
++
)
{
// Trim whitespace
available
[
i
]
=
available
[
i
]
.
replace
(
/
\s
/
g
,
''
)
;
// Validate
var
ver
=
semver
.
valid
(
available
[
i
]
)
;
if
(
ver
)
{
if
(
loc
===
'remote'
)
{
remotes
.
push
(
ver
)
;
}
else
if
(
loc
===
'local'
)
{
locals
.
push
(
ver
)
;
}
}
}
callback
(
)
;
}
)
;
}


function() {
      // Make sure a node version is intalled that satisfies
      // the projects required engine. If not, prompt to install.
      nvmLs('local', function() {
        var matches = semver.maxSatisfying(locals, expected);

        if (matches) {
          bestMatch = matches;
          nvmUse = nvmInit + 'nvm use ' + bestMatch;

          childProcess.exec(nvmUse, cmdOpts,function(err, stdout, stderr) {
            printVersion(stdout.split(' ')[3]);
            extendExec();
            checkPackages(options.globals);
          });
        } else {
          if (options.alwaysInstall) {
            nvmInstall();
          } else {
            askInstall();
          }
        }
      });
    }


function EachSubject(subject, elements, elementName, opt_noIndex) {
  ProxyBase.call(this);
  this.elementSubjects = [];
  for (var i = 0; i < elements.length; ++i) {
    var es = subjectFactory.newSubject(subject.failureStrategy, elements[i]);
    es.named(elementName + (opt_noIndex ? '' : (' ' + i)) + ' of ' + subject.describe());
    es.failureMessage = subject.failureMessage;
    this.elementSubjects.push(es);
  }
}

function
EachSubject
(
subject
,
elements
,
elementName
,
opt_noIndex
)
{
ProxyBase
.
call
(
this
)
;
this
.
elementSubjects
=
[
]
;
for
(
var
i
=
0
;
i
<
elements
.
length
;
++
i
)
{
var
es
=
subjectFactory
.
newSubject
(
subject
.
failureStrategy
,
elements
[
i
]
)
;
es
.
named
(
elementName
+
(
opt_noIndex
''
:
(
' '
+
i
)
)
+
' of '
+
subject
.
describe
(
)
)
;
es
.
failureMessage
=
subject
.
failureMessage
;
this
.
elementSubjects
.
push
(
es
)
;
}
}

A subject which executes its assertions on each element of an iterable.
@param {Subject} The subject responsible for creating this.
@param {Array} elements List of elements to test.
@param {string} elementName What noun to use when referring to elements ('item', 'child', etc.)
@param {bool} opt_noIndex If true, don't include the element index in the failure message.
@constructor
@extends ProxyBase

A subject which executes its assertions on each element of an iterable .


function EventualSubject(subject, promise) {
  DeferredSubject.call(this);
  this.subject = subject;
  var self = this;
  this.promise = promise.then(
    function(value) {
      // Play back the recorded calls on a new subject which is created based on the resolved
      // value of the promise.
      var valueSubject = subjectFactory.newSubject(subject.failureStrategy, value);
      valueSubject.failureMessage = subject.failureMessage;
      self.run(valueSubject);
      return value;
    },
    function(reason) {
      subject.fail('Expected promise ' + subject.describe() +
        ' to succeed, but failed with ' + this.format(reason) + '.');
      return reason;
    }
  );
  // Make this object a thenable
  this.then = this.promise.then.bind(this.promise);
  this.catch = this.promise.catch.bind(this.promise);
}

A class which functions as a subject, but doesn't actually execute any assertions until
the promise has resolved. Once the promise succeeds, any method calls will be played back
on the result value of the promise.
@param {PromiseSubject} subject The subject wrapping the promise.
@param {Promise} promise The promise being tested.
@constructor
@extends DeferredSubject

A class which functions as a subject but doesn t actually execute any assertions until the promise has resolved . Once the promise succeeds any method calls will be played back on the result value of the promise .


function PromiseSubject(failureStrategy, value) {
  Subject.call(this, failureStrategy, value);
  // Make this object a thenable
  this.then = this.value.then.bind(this.value);
  this.catch = this.value.catch.bind(this.value);
}

function
PromiseSubject
(
failureStrategy
,
value
)
{
Subject
.
call
(
this
,
failureStrategy
,
value
)
;
// Make this object a thenable
this
.
then
=
this
.
value
.
then
.
bind
(
this
.
value
)
;
this
.
catch
=
this
.
value
.
catch
.
bind
(
this
.
value
)
;
}

Subject subclass which provides assertion methods for promise types.
@param {FailureStrategy} failureStrategy The failure strategy to use when an assertion fails.
@param {*} value The value being checked.
@constructor
@extends Subject

Subject subclass which provides assertion methods for promise types .


function doGet(store, key, options = {}) {
  // Resolve back to original key if referenced
  key = store._resolveRefKey(key);

  const { referenceDepth = 1 } = options;
  const cacheKey = `${key}:${referenceDepth}`;
  const shouldCache = !store._isWritable;

  if (shouldCache) {
    if (store._getCache[cacheKey]) {
      return store._getCache[cacheKey];
    }
  }

  let value = property.get(store._data, key);

  if (referenceDepth > 0) {
    value = resolveReferences(store, value, referenceDepth);
  }

  if (shouldCache) {
    store._getCache[cacheKey] = value;
  }

  return value;
}

Retrieve value stored at 'key'
@param {DataStore} store
@param {String} key
@param {Object} [options]
- {Number} referenceDepth
@returns {*}


function resolveReferences(store, value, depth) {
  if (--depth < 0) {
    return value;
  }

  if (Array.isArray(value)) {
    const n = value.length;
    const v = new Array(n);
    let item;

    for (let i = n - 1; i >= 0; i--) {
      item = value[i];
      v[i] = resolveReferences(
        store,
        store._isRefValue(item) ? property.get(store._data, store._parseRefKey(item)) : item,
        depth
      );
    }

    value = v;
  } else if (isPlainObject(value)) {
    const v = {};
    let item;

    for (const prop in value) {
      item = value[prop];
      v[prop] = resolveReferences(
        store,
        store._isRefValue(item) ? property.get(store._data, store._parseRefKey(item)) : item,
        depth
      );
    }

    value = v;
  }

  return value;
}

function resolveReferences ( store , value , depth ) { if ( -- depth < 0 ) { return value ; } if ( Array . isArray ( value ) ) { const n = value . length ; const v = new Array ( n ) ; let item ; for ( let i = n - 1 ; i >= 0 ; i -- ) { item = value [ i ] ; v [ i ] = resolveReferences ( store , store . _isRefValue ( item ) ? property . get ( store . _data , store . _parseRefKey ( item ) ) : item , depth ) ; } value = v ; } else if ( isPlainObject ( value ) ) { const v = { } ; let item ; for ( const prop in value ) { item = value [ prop ] ; v [ prop ] = resolveReferences ( store , store . _isRefValue ( item ) ? property . get ( store . _data , store . _parseRefKey ( item ) ) : item , depth ) ; } value = v ; } return value ; }

Resolve all references in 'value' up to max 'depth'
@param {DataStore} store
@param {Object} value
@param {Number} depth
@returns {Object}

Resolve all references in value up to max depth


function formatString(value, options) {
  var opts = options || {};
  var result = value.replace(/[\0-\37]/g, function (ch) {
    switch (ch) {
      case '\n': return '\\n';
      case '\r': return '\\r';
      case '\t': return '\\t';
      case '\b': return '\\b';
      case '\v': return '\\v';
      case '\f': return '\\f';
      default: return '\\' + ch.charCodeAt(0).toString(8);
    }
  });
  if (opts.clip && result.length > opts.clip) {
    result = result.slice(0, Math.max(0, opts.clip - 3)) + '...';
  }
  return '"' + result + '"';
}

function formatString ( value , options ) { var opts = options || { } ; var result = value . replace ( / [\0-\37] / g , function ( ch ) { switch ( ch ) { case '\n' : return '\\n' ; case '\r' : return '\\r' ; case '\t' : return '\\t' ; case '\b' : return '\\b' ; case '\v' : return '\\v' ; case '\f' : return '\\f' ; default : return '\\' + ch . charCodeAt ( 0 ) . toString ( 8 ) ; } } ) ; if ( opts . clip && result . length > opts . clip ) { result = result . slice ( 0 , Math . max ( 0 , opts . clip - 3 ) ) + '...' ; } return '"' + result + '"' ; }

Convert a string value to a printable string representation.
@param {String} value The value to format.
@param {Object} options Formatting options.
@protected

Convert a string value to a printable string representation .


function formatObject(value, options) {
  if (value === undefined) {
    return 'undefined';
  }
  if (value === null) {
    return 'null';
  }

  if (typeof(value) == 'object') {
    if (value instanceof RegExp || value instanceof Date) {
      return value + '';
    }

    var opts = options || {};
    var innerOpts = Object.assign({}, opts, { clip: false });
    // If it's a plain object
    var proto = Object.getPrototypeOf(value);
    if (proto === Object.prototype || proto === null) {
      var keys = [];
      for (var k in value) {
        keys.push(k);
      }
      keys.sort();
      var parts = ['{'];
      var length = 4; // Include both open and close brace.
      for (var i = 0; i < keys.length; ++i) {
        var key = keys[i];
        var sep = i > 0 ? ', ' : ' ';
        var s = registry.format(value[key], innerOpts);
        length += sep.length + key.length + 2 + s.length;
        if (opts.clip && opts.clip < length) {
          parts.push(', ...');
          break;
        }
        parts.push(sep);
        parts.push(key);
        parts.push(': ');
        parts.push(s);
      }
      if (keys.length > 0) {
        parts.push(' ');
      }
      parts.push('}');
      return parts.join('');
    }
    if (typeof value.toString == 'function') {
      return value.toString();
    }
    return String(value);
  }
  throw new Error('Implement');
}

function
formatObject
(
value
,
options
)
{
if
(
value
===
undefined
)
{
return
'undefined'
;
}
if
(
value
===
)
{
return
'null'
;
}
if
(
typeof
(
value
)
==
'object'
)
{
if
(
value
instanceof
RegExp
||
value
instanceof
Date
)
{
return
value
+
''
;
}
var
opts
=
options
||
{
}
;
var
innerOpts
=
Object
.
assign
(
{
}
,
opts
,
{
clip
:
false
}
)
;
// If it's a plain object
var
proto
=
Object
.
getPrototypeOf
(
value
)
;
if
(
proto
===
Object
.
prototype
||
proto
===
)
{
var
keys
=
[
]
;
for
(
var
k
in
value
)
{
keys
.
push
(
k
)
;
}
keys
.
sort
(
)
;
var
parts
=
[
'{'
]
;
var
length
=
4
;
// Include both open and close brace.
for
(
var
i
=
0
;
i
<
keys
.
length
;
++
i
)
{
var
key
=
keys
[
i
]
;
var
sep
=
i
>
0
', '
:
' '
;
var
s
=
registry
.
format
(
value
[
key
]
,
innerOpts
)
;
length
+=
sep
.
length
+
key
.
length
+
2
+
s
.
length
;
if
(
opts
.
clip
&&
opts
.
clip
<
length
)
{
parts
.
push
(
', ...'
)
;
break
;
}
parts
.
push
(
sep
)
;
parts
.
push
(
key
)
;
parts
.
push
(
': '
)
;
parts
.
push
(
s
)
;
}
if
(
keys
.
length
>
0
)
{
parts
.
push
(
' '
)
;
}
parts
.
push
(
'}'
)
;
return
parts
.
join
(
''
)
;
}
if
(
typeof
value
.
toString
==
'function'
)
{
return
value
.
toString
(
)
;
}
return
String
(
value
)
;
}
throw
new
Error
(
'Implement'
)
;
}

Convert an object value to a printable string representation.
@param {Object} value The value to format.
@param {Object} options Formatting options.
@protected

Convert an object value to a printable string representation .


function _exportPublicKey(key) {
    var t = key.metadata.type;
    var p = key.metadata.purpose;
    if (!(t == keyczar.TYPE_RSA_PRIVATE && (p == keyczar.PURPOSE_DECRYPT_ENCRYPT || p == keyczar.PURPOSE_SIGN_VERIFY))) {
        throw new Error('Unsupported key type/purpose:' + t + '/' + p);
    }

    var publicPurpose = keyczar.PURPOSE_ENCRYPT;
    if (p == keyczar.PURPOSE_SIGN_VERIFY) {
        publicPurpose = keyczar.PURPOSE_VERIFY;
    }

    var metadata = {
        name: key.metadata.name,
        purpose: publicPurpose,
        type: keyczar.TYPE_RSA_PUBLIC,
        encrypted: false,
        // TODO: Probably should do a deep copy
        versions: key.metadata.versions
    };

    if (key.metadata.versions.length != 1) {
        throw new Error('TODO: Support key sets with multiple keys');
    }

    var primaryVersion = _getPrimaryVersion(key.metadata);

    var data = {
        meta: JSON.stringify(metadata)
    };
    data[String(primaryVersion)] = key.primary.exportPublicKeyJson();
    return _makeKeyczar(data);
}

Return a new keyczar containing the public part of key, which must be an asymmetric key.

Return a new keyczar containing the public part of key which must be an asymmetric key .


function _getPrimaryVersion(metadata) {
    var primaryVersion = null;
    for (var i = 0; i < metadata.versions.length; i++) {
        if (metadata.versions[i].status == STATUS_PRIMARY) {
            if (primaryVersion !== null) {
                throw new Error('Invalid key: multiple primary keys');
            }
            primaryVersion = metadata.versions[i].versionNumber;
        }
    }

    if (primaryVersion === null) {
        throw new Error('No primary key');
    }

    return primaryVersion;
}

function
_getPrimaryVersion
(
metadata
)
{
var
primaryVersion
=
;
for
(
var
i
=
0
;
i
<
metadata
.
versions
.
length
;
i
++
)
{
if
(
metadata
.
versions
[
i
]
.
status
==
STATUS_PRIMARY
)
{
if
(
primaryVersion
!==
)
{
throw
new
Error
(
'Invalid key: multiple primary keys'
)
;
}
primaryVersion
=
metadata
.
versions
[
i
]
.
versionNumber
;
}
}
if
(
primaryVersion
===
)
{
throw
new
Error
(
'No primary key'
)
;
}
return
primaryVersion
;
}

find the primary version; ensure we don't have more than one

find the primary version ; ensure we don t have more than one


function formatMap(value, options) {
  return 'Map(' + registry.format(Array.from(value.entries()), options) + ')';
}

function formatMap ( value , options ) { return 'Map(' + registry . format ( Array . from ( value . entries ( ) ) , options ) + ')' ; }

Convert a map value to a printable string representation.
@param {Map} value The value to format.
@param {Object} options Formatting options.
@protected

Convert a map value to a printable string representation .


function load(store, key, url, options) {
  const { cacheControl, rejectOnError, retry, timeout } = options;

  options.id = key;

  store.debug('load %s from %s', key, url);

  return agent
    .get(url, options)
    .timeout(timeout)
    .retry(retry)
    .then(res => {
      // Abort if already destroyed
      if (store.destroyed) {
        throw Error('store destroyed');
      }

      store.debug('loaded "%s" in %dms', key, res.duration);

      // Guard against empty data
      if (res.body) {
        // Parse cache-control headers
        if (res.headers && 'expires' in res.headers) {
          res.body[store.EXPIRY_KEY] = generateExpiry(res.headers, cacheControl);
        }

        // Enable handling by not calling inner set()
        store.set(key, res.body, options);
      }

      return res;
    })
    .catch(err => {
      // Abort if already destroyed
      if (store.destroyed) {
        throw err;
      }

      store.debug('unable to load "%s" from %s', key, url);

      if (rejectOnError) {
        store.set(key, undefined, options);
      }

      throw err;
    });
}

Load data from 'url' and store at 'key'
@param {DataStore} store
@param {String} key
@param {String} url
@param {Object} options
- {Boolean} abort
- {Boolean} ignoreQuery
- {Number} minExpiry
- {Number} retry
- {Boolean} staleIfError
- {Number} timeout
@returns {Promise}


function mergeCacheControl(cacheControl, defaultCacheControl) {
  if (cacheControl == null) {
    return Object.assign({}, defaultCacheControl);
  }

  return {
    maxAge: 'maxAge' in cacheControl ? cacheControl.maxAge : defaultCacheControl.maxAge,
    staleIfError: 'staleIfError' in cacheControl ? cacheControl.staleIfError : defaultCacheControl.staleIfError
  };
}

function mergeCacheControl ( cacheControl , defaultCacheControl ) { if ( cacheControl == null ) { return Object . assign ( { } , defaultCacheControl ) ; } return { maxAge : 'maxAge' in cacheControl ? cacheControl . maxAge : defaultCacheControl . maxAge , staleIfError : 'staleIfError' in cacheControl ? cacheControl . staleIfError : defaultCacheControl . staleIfError } ; }

Merge 'cacheControl' with defaults
@param {Object} cacheControl
@param {Object} defaultCacheControl
@returns {Object}


function generateExpiry(headers = {}, defaultCacheControl) {
  const cacheControl = mergeCacheControl(parseCacheControl(headers['cache-control']), defaultCacheControl);

  const now = Date.now();
  let expires = now;

  if (headers.expires) {
    expires = typeof headers.expires === 'string' ? Number(new Date(headers.expires)) : headers.expires;
  }
  if (now >= expires) {
    expires = now + cacheControl.maxAge;
  }

  return {
    expires,
    expiresIfError: expires + cacheControl.staleIfError
  };
}

function generateExpiry ( headers = { } , defaultCacheControl ) { const cacheControl = mergeCacheControl ( parseCacheControl ( headers [ 'cache-control' ] ) , defaultCacheControl ) ; const now = Date . now ( ) ; let expires = now ; if ( headers . expires ) { expires = typeof headers . expires === 'string' ? Number ( new Date ( headers . expires ) ) : headers . expires ; } if ( now >= expires ) { expires = now + cacheControl . maxAge ; } return { expires , expiresIfError : expires + cacheControl . staleIfError } ; }

Generate expiry object from 'headers'
@param {Object} [headers]
@param {Object} defaultCacheControl
@returns {Number}


function generateResponseHeaders(expiry = {}, defaultCacheControl, isError) {
  const now = Date.now();
  let maxAge;

  if (isError) {
    maxAge =
      expiry && expiry.expiresIfError > now && expiry.expiresIfError - now < defaultCacheControl.maxAge
        ? Math.ceil((expiry.expiresIfError - now) / 1000)
        : defaultCacheControl.maxAge / 1000;
  } else {
    // Round up to nearest second
    maxAge =
      expiry && expiry.expires > now ? Math.ceil((expiry.expires - now) / 1000) : defaultCacheControl.maxAge / 1000;
  }

  return {
    // TODO: add stale-if-error
    'cache-control': `public, max-age=${maxAge}`,
    expires: new Date(now + maxAge * 1000).toUTCString()
  };
}

function
generateResponseHeaders
(
expiry
=
{
}
,
defaultCacheControl
,
isError
)
{
const
now
=
Date
.
now
(
)
;
let
maxAge
;
if
(
isError
)
{
maxAge
=
expiry
&&
expiry
.
expiresIfError
>
now
&&
expiry
.
expiresIfError
now
<
defaultCacheControl
.
maxAge
Math
.
ceil
(
(
expiry
.
expiresIfError
now
)
/
1000
)
:
defaultCacheControl
.
maxAge
/
1000
;
}
else
{
// Round up to nearest second
maxAge
=
expiry
&&
expiry
.
expires
>
now
Math
.
ceil
(
(
expiry
.
expires
now
)
/
1000
)
:
defaultCacheControl
.
maxAge
/
1000
;
}
return
{
// TODO: add stale-if-error
'cache-control'
:
`
${
maxAge
}
`
,
expires
:
new
Date
(
now
+
maxAge
*
1000
)
.
toUTCString
(
)
}
;
}

Generate serialized headers object for response
@param {Object} [expiry]
@param {Object} defaultCacheControl
@param {Boolean} isError
@returns {Object}


function hasExpired(expiry, isError) {
  if (!expiry) {
    return true;
  }

  // Round up to nearest second
  return Math.ceil(Date.now() / 1000) * 1000 > (isError ? expiry.expiresIfError : expiry.expires);
}

function
hasExpired
(
expiry
,
isError
)
{
if
(
!
expiry
)
{
return
true
;
}
// Round up to nearest second
return
Math
.
ceil
(
Date
.
now
(
)
/
1000
)
*
1000
>
(
isError
expiry
.
expiresIfError
:
expiry
.
expires
)
;
}

Check if expired
@param {Object} expiry
@param {Boolean} isError
@returns {Boolean}


function formatSet(value, options) {
  return 'Set(' + registry.format(Array.from(value.values()), options) + ')';
}

function formatSet ( value , options ) { return 'Set(' + registry . format ( Array . from ( value . values ( ) ) , options ) + ')' ; }

Convert a set value to a printable string representation.
@param {Set} value The value to format.
@param {Object} options Formatting options.
@protected

Convert a set value to a printable string representation .


function formatArray(value, options) {
  var opts = options || {};
  var innerOpts = Object.assign({}, opts, { clip: false });
  var parts = ['['];
  var length = 2; // Include both open and close bracket.
  for (var i = 0; i < value.length; ++i) {
    var sep = i > 0 ? ', ' : '';
    var s = registry.format(value[i], innerOpts);
    length += sep.length + s.length;
    if (opts.clip && opts.clip < length) {
      parts.push(', ...');
      break;
    }
    parts.push(sep);
    parts.push(s);
  }
  parts.push(']');
  return parts.join('');
}

function
formatArray
(
value
,
options
)
{
var
opts
=
options
||
{
}
;
var
innerOpts
=
Object
.
assign
(
{
}
,
opts
,
{
clip
:
false
}
)
;
var
parts
=
[
'['
]
;
var
length
=
2
;
// Include both open and close bracket.
for
(
var
i
=
0
;
i
<
value
.
length
;
++
i
)
{
var
sep
=
i
>
0
', '
:
''
;
var
s
=
registry
.
format
(
value
[
i
]
,
innerOpts
)
;
length
+=
sep
.
length
+
s
.
length
;
if
(
opts
.
clip
&&
opts
.
clip
<
length
)
{
parts
.
push
(
', ...'
)
;
break
;
}
parts
.
push
(
sep
)
;
parts
.
push
(
s
)
;
}
parts
.
push
(
']'
)
;
return
parts
.
join
(
''
)
;
}

Convert an array value to a printable string representation.
@param {Array} value The value to format.
@param {Object} options Formatting options.
@protected

Convert an array value to a printable string representation .


function reset(store, data) {
  store.debug('reset');
  store._data = data;
  store.changed = true;
}

function reset ( store , data ) { store . debug ( 'reset' ) ; store . _data = data ; store . changed = true ; }

Reset underlying 'data'
@param {DataStore} store
@param {Object} data


function serialise(key, data, config) {
  if (isPlainObject(data)) {
    const obj = {};

    for (const prop in data) {
      const keyChain = key ? `${key}/${prop}` : prop;
      const value = data[prop];

      if (config[keyChain] !== false) {
        if (isPlainObject(value)) {
          obj[prop] = serialise(keyChain, value, config);
        } else if (value != null && typeof value === 'object' && 'toJSON' in value) {
          obj[prop] = value.toJSON();
        } else {
          obj[prop] = value;
        }
      }
    }

    return obj;
  }

  return config[key] !== false ? data : null;
}

function serialise ( key , data , config ) { if ( isPlainObject ( data ) ) { const obj = { } ; for ( const prop in data ) { const keyChain = key ? ` ${ key } ${ prop } ` : prop ; const value = data [ prop ] ; if ( config [ keyChain ] !== false ) { if ( isPlainObject ( value ) ) { obj [ prop ] = serialise ( keyChain , value , config ) ; } else if ( value != null && typeof value === 'object' && 'toJSON' in value ) { obj [ prop ] = value . toJSON ( ) ; } else { obj [ prop ] = value ; } } } return obj ; } return config [ key ] !== false ? data : null ; }

Retrieve serialisable 'data'
@param {String} key
@param {Object} data
@param {Object} config
@returns {Object}


function explode(store, data) {
  if (isPlainObject(data)) {
    const obj = {};

    for (const prop in data) {
      obj[prop] = explode(store, data[prop]);
    }
    return obj;
  } else if (Array.isArray(data)) {
    return data.map(value => explode(store, value));
  } else if (store._isRefValue(data)) {
    return explode(store, store.get(store._parseRefKey(data)));
  }

  return data;
}

function explode ( store , data ) { if ( isPlainObject ( data ) ) { const obj = { } ; for ( const prop in data ) { obj [ prop ] = explode ( store , data [ prop ] ) ; } return obj ; } else if ( Array . isArray ( data ) ) { return data . map ( value => explode ( store , value ) ) ; } else if ( store . _isRefValue ( data ) ) { return explode ( store , store . get ( store . _parseRefKey ( data ) ) ) ; } return data ; }

Resolve all nested references for 'data'
@param {DataStore} store
@param {Object} data
@returns {Object}


function Subject(failureStrategy, value) {
  this.failureStrategy = failureStrategy;
  this.value = value;
  this.name = null;
  this.format = format;
  this.failureMessage = null;
}

function Subject ( failureStrategy , value ) { this . failureStrategy = failureStrategy ; this . value = value ; this . name = null ; this . format = format ; this . failureMessage = null ; }

Represents the value being checked, and provides assertion methods. Can be subclassed to
provide assertion methods that are type-specific.
@param {FailureStrategy} failureStrategy The failure strategy to use when an assertion fails.
@param {*} value The value being checked.
@constructor

Represents the value being checked and provides assertion methods . Can be subclassed to provide assertion methods that are type - specific .


function(json){

    // Protect against forgetting the new keyword when calling the constructor
    if(!(this instanceof User)){
      return new User(json);
    }

    // If the given object is already an instance then just return it. DON'T copy it.
    if(User.isInstance(json)){
      return json;
    }

    this.init(json);
  }

FamilySearch user.

@class User
@extends ExtensibleData
@param {Object} [json]


function () {
        for (var fls in configs) {
            dirName = utils.folderName(configs[fls]['input'], configs[fls]['folderName']);
            dirType = configs[fls]['type'];
            destFolderDir = path.join(configs[fls]['destinationSourcePath'], dirName);
            destDir = configs[fls]['destinationSourcePath'];
            tmpDir = configs[fls]['tempFolderPath'];
            tempFolderName = utils.getBaseFolderName(tmpDir);
            refSrcDir = configs[fls]['refrenceSourcePath'];
            ignoreExtentions = configs[fls]['ignoreExts'] || [];
            ignoreFolders = configs[fls]['ignoreFolders'] || [];
            contentReplaceRegx = new RegExp(utils.regxContent(configs[fls]['replaceContent']), 'g');
            if (configs[fls]['replaceContent']) {
                replaceContentLength = Object.keys(configs[fls]['replaceContent']).length;
            }
            console.log(':::~~' + fls + ':::~~');
            folderSync(configs[fls]);
        }
    }

function ( ) { for ( var fls in configs ) { dirName = utils . folderName ( configs [ fls ] [ 'input' ] , configs [ fls ] [ 'folderName' ] ) ; dirType = configs [ fls ] [ 'type' ] ; destFolderDir = path . join ( configs [ fls ] [ 'destinationSourcePath' ] , dirName ) ; destDir = configs [ fls ] [ 'destinationSourcePath' ] ; tmpDir = configs [ fls ] [ 'tempFolderPath' ] ; tempFolderName = utils . getBaseFolderName ( tmpDir ) ; refSrcDir = configs [ fls ] [ 'refrenceSourcePath' ] ; ignoreExtentions = configs [ fls ] [ 'ignoreExts' ] || [ ] ; ignoreFolders = configs [ fls ] [ 'ignoreFolders' ] || [ ] ; contentReplaceRegx = new RegExp ( utils . regxContent ( configs [ fls ] [ 'replaceContent' ] ) , 'g' ) ; if ( configs [ fls ] [ 'replaceContent' ] ) { replaceContentLength = Object . keys ( configs [ fls ] [ 'replaceContent' ] ) . length ; } console . log ( ':::~~' + fls + ':::~~' ) ; folderSync ( configs [ fls ] ) ; } }


function (fls) {
        if (fs.existsSync(destFolderDir)) {
            console.log(':::~~' + dirName + ' exists, please pick another name or delete previous to create new~~:::')
            deferred.reject(fls.type + ' exists, please pick another name.');
        } else {
            console.log(':::~~' + dirName + ' does not exists, creating new~~:::');
            if (!fs.existsSync(destFolderDir)) {
                fse.ensureDirSync(destFolderDir);
                console.log(':::~~Created new directory:' + fls.type + "/" + dirName + '~~:::');
            }
            //copy refrence directroy data in temporry directory folder
            copyRefToTemp();
            //update folder names, file names and file content in temp folder
            updateTempSubDirNames(fls);
            //copy temporary directroy data in destination directory folder
            copyTempToDest();
            // add tasks to create folder
            // addWebpackTasks();
            deferred.resolve('successfuly created directory');
        }
        return deferred.promise;
    }

sync folder to create new directories with provided Configurations
@param {*} fls


function () {
        fse.emptyDirSync(tmpDir);
        fse.copySync(refSrcDir, tmpDir, { overwrite: true }, err => {
            if (err) {
                console.log(':::~~error in copying to temp directory:' + err + '~~:::');
                fse.removeSync(destFolderDir);
                fse.emptyDirSync(tmpDir);
                deferred.reject('Error in copying to temp directory');
            }
            console.log(':::~~ temp directory created~~:::');
        });
    }

Copy refrence directory in temporary directory


function (oldPath, fls) {
        console.log(":::~~processing your temp folder and file~~:::"+oldPath);
        var parsedPath = updateFileNamePath(path.parse(oldPath), fls);
        var newPath = path.format(parsedPath);
        var firstFolderName = utils.getFirstFolderName(oldPath, tempFolderName);
        fs.renameSync(oldPath, newPath);
        if (replaceContentLength > 0 && ignoreExtentions.indexOf(parsedPath.ext) < 0 && ignoreFolders.indexOf(firstFolderName) < 0) {
            console.log(":::~~writing your temp file~~:::"+newPath);
            var oldContent = fs.readFileSync(newPath, 'utf8');
            var newContent = updateFileContent(oldContent, fls.replaceContent, fls);
            fs.writeFileSync(newPath, newContent);
        }else{
            console.log(":::~~skipping writing of your temp file~~:::"+newPath);
        }
    }

Process files that were recently copied in temp directory
@param {*} oldPath
@param {*} fls


function (parsedPath, fls) {
        // parsedPath.dir, parsedPath.base, parsedPath.ext, parsedPath.name
        var newName = "";
        var fileConfigs = "";
        var folderDirArray = getNestedFolderName(parsedPath);
        parsedPath['folderName'] = utils.getBaseFolderName(parsedPath.dir) != tempFolderName ? utils.getBaseFolderName(parsedPath.dir) : "";
        //fileConfigs = parsedPath.folderName ? fls.replaceFileName[parsedPath.folderName][parsedPath.base] : fls.replaceFileName[parsedPath.base];
        if (folderDirArray == "base" && fls.replaceFileName[parsedPath.base]) {
            fileConfigs = fls.replaceFileName[parsedPath.base];
        } else if (Array.isArray(folderDirArray)) {
            var replaceFileNameArray = fls.replaceFileName;
            for (var i in folderDirArray) {
                if (replaceFileNameArray[folderDirArray[i]] && Object.keys(replaceFileNameArray[folderDirArray[i]]).length > 0) {
                    replaceFileNameArray = replaceFileNameArray[folderDirArray[i]];
                } else {
                    replaceFileNameArray = [];
                    break;
                }
            }
            if (replaceFileNameArray && replaceFileNameArray[parsedPath.base]) {
                fileConfigs = replaceFileNameArray[parsedPath.base];
            } else {
                fileConfigs = [];
            }
        } else {
            fileConfigs = []
        }
        console.log(":::~~Configurations from replaceFileName~~:::" +fileConfigs);
        newName = utils.getupdatedFileName(parsedPath.name, fileConfigs, fls.input);
        parsedPath.base = newName + parsedPath.ext;
        parsedPath.name = newName;
        return parsedPath;
    }

update refrence directory files names as per config provided by replaceFileName key
@param {*} parsedPath
@param {*} fls


function (parsedPath) {
        var tempPathArray = tmpDir.split("\\");
        var parsedPathArray = parsedPath.dir.split("\\");
        if (parseInt(tempPathArray.length) === parseInt(parsedPathArray.length)) {
            return "base";
        } else if (parseInt(tempPathArray.length) < parseInt(parsedPathArray.length)) {
            var folderNameArray = [];
            for (var i in parsedPathArray) {
                if (i > parseInt(tempPathArray.length) - 1) {
                    folderNameArray.push(parsedPathArray[i]);
                }
            }
            return folderNameArray;
        }
    }

function ( parsedPath ) { var tempPathArray = tmpDir . split ( "\\" ) ; var parsedPathArray = parsedPath . dir . split ( "\\" ) ; if ( parseInt ( tempPathArray . length ) === parseInt ( parsedPathArray . length ) ) { return "base" ; } else if ( parseInt ( tempPathArray . length ) < parseInt ( parsedPathArray . length ) ) { var folderNameArray = [ ] ; for ( var i in parsedPathArray ) { if ( i > parseInt ( tempPathArray . length ) - 1 ) { folderNameArray . push ( parsedPathArray [ i ] ) ; } } return folderNameArray ; } }

get array of folders from base temp path
@param {*} parsedPath