/*
Makes functions asynchronous, following a specific pattern

@private
@param {string} data
@param {object} vars
@param {string} relPath
return {function}
541929
function _makePartialAsync(func, asyncFn, syncFn) {
  
  // Return from cache
  var out,cached = this.cache[func.id];
  if (cached instanceof Function) return cached;

  if (func.async) {
    // Async function
    out = this.cache[func.relPath] = asyncFn;
  } else {
    // Sync function
    out = this.cache[func.relPath] = syncFn;
  }
  
  return out;

}
683165
function seekArray(data, pathArr, result, key) {
    var subpath = pathArr[1];
    var path = pathArr[0];
    var seek = jsonPath.eval(data, path) || [];

    if (seek.length && subpath) {
      result = result[key] = [];

      seek[0].forEach(function(item, index) {
        walk(item, subpath, result, index);
      });
    } else {
      result[key] = seek;
    }
  }
752667
function asyncRender(view, data, raw) {
  
  var request = this.request;
  
  // Get raw option, or set default
  raw = (raw || app.config.rawViews);
  
  // Get controller, or set default
  var controller = (this.__controller || app.controller);

  // Get engine
  var viewPath = this.getViewPath(view);
  var engine = app.defaultEngine.getEngineByExtension(viewPath);
  
  if (!engine) {
    // Using this.end to prevent infinite loops
    this.statusCode = 500;
    this.end('500 Internal Server Error');
    if (viewPath) {
      app.log(new Error("View not found or no engine detected for route: " + request.url));
    } else {
      app.log("View not found: %s/%s", controller.getAlias(), view);
    }
    return;
  } else if (engine.multiPart === false) {
    // Force raw on non-multiPart engines
    raw = true;
  }
  
  // Attach engine to response
  this.engine = engine;

  // Detect args
  if (typeof data == 'boolean') { raw = data; data = null; }
  
  // Create new object with partials as prototype
  var proto = Object.create(engine.returnPartials());
  
  // Make app.locals available as view locals
  _.extend(proto, app.locals);
  
  if (data == null) {
    // If no data available, use proto as data
    data = proto;
  } else {
    // Set proto as data`s prototype
    data.__proto__ = proto;
  }
  
  // View Locals
  data = _.extend(data, {
    protos: protos,
    app: app,
    res: this,
    req: request,
    params: request.params,
    session: request.session || {},
    cookies: request.cookies || {},
  });
  
  // Extend data with request metadata
  _.extend(data, request.__metadata);
  
  // Add `locals` variable redundancy
  data.locals = this.viewLocals = data;
  
  // Add view data filter. Useful if you want to add locals
  app.emit('view_locals', data);
  
  // Render full layout or response
  // TODO: Ability to pass an array with the desired layout to res.render (awesome!)
  // TODO: If view is an array, ignore the `raw` option
  var views = (raw) ? [view] : ['@header', view, '@footer'];
    
  // TODO: Assign status code based on template name (validated with regex)
  if (view == '#404') this.statusCode = 404;
  else if (view == '#500') this.statusCode = 500;

  this.__runtimeData = {
    buffer: '',
    data: data,
    views: views,
    currentView: null,
    controller: controller,
    mainView: view,
  };
  
  renderViewBuffer.call(this);
}
1202873
async function (rid, varName, query, val) {
      const ops = await putPVar(ldb, ['appvars', rid, varName], query, val)
      await ldb.batch(ops)
    }
871356
function createPersistentPath(client, path, data, callback) {
  debug('createPersistentPath: "%s" "%s"', path, data);

  data = ensureBuffer(data);

  client.create(path, data, function(err) {
    if (err) {
      if (err.code !== NO_NODE)
        return callback(err);

      createParentPath(client, path, function(err) {
        if (err) return callback(err);

        client.create(path, data, callback);
      });
    } else
      callback(null, path);
  })
}
673015
function Watch(paths,      // @arg PathArray
               options,    // @arg Object   - { delay, action, verbose, ... }
               callback) { // @arg Function - callback(err:Error):void
//{@dev
    _if(!Array.isArray(paths),  "invalid Watch(paths)");
    _if(!_isObject(options),    "invalid Watch(,options)");
    _if(!_isFunction(callback), "invalid Watch(,,callback)");
//}@dev

    var that = this;

    this._options = options || {};

    if (this._options.verbose) {
        console.log("  --- watch ---");
    }
    paths.forEach(function(path) {
        if (_isFile(path)) {
            Watch_file(that, path, function(diff) { // { path: { dir, size, mtime }, ... }
                callback(null, diff);
            });
        } else if (_isDir(path)) {
            Watch_dir(that, path, function(diff) { // { path: { dir, size, mtime }, ... }
                callback(null, diff);
            }, options);
        }
    });
}
1268018
function(data) {
            var deferreds = [];

            // pull out deferreds
            if (can.isDeferred(data)) {
                return [data];
            } else {
                for (var prop in data) {
                    if (can.isDeferred(data[prop])) {
                        deferreds.push(data[prop]);
                    }
                }
            }
            return deferreds;
        }
781443
function( patterns, options ){

        options = options || {};

        var deferred = Q.defer(),
            updateHTMLFile = this.updateHTMLFile,
            results = {
                success: [],
                error: []
            };

        globby( patterns, options, function( err, files ){
            if( err ){
                deferred.reject( err );
                return;
            }

            files.reduce( function( previousUpdating, currentTargetFilePath ){
                return previousUpdating.then(
                    function( previousPath ){
                        if( previousPath ){
                            results.success.push( previousPath );
                        }
                        return updateHTMLFile( currentTargetFilePath );
                    }
                );
            }, Q() )
                .then(
                    function( lastPath ){
                        results.success.push( lastPath );
                        deferred.resolve( results );
                    },
                    function( e ){
                        deferred.reject( e );
                    }
                );
        } );

        return deferred.promise;
    }
784338
function replaceVariables(localPath, variables) {
    return new Promise(function(resolve, reject) {
        // Read the file
        let body = fs.readFileSync(localPath, 'utf8');

        // Do the replacement for all of the variables
        const keys = Object.keys(variables);
        keys.forEach(function(key) {
            const value = variables[key];
            const re = new RegExp(`"\\$${key}"`, 'g');

            // Parse the value (to see if it is falsey)
            try {
                const parsed = JSON.parse(value);
                body = body.replace(re, parsed ? `"${parsed}"` : `null`);
            } catch (err) {
                // Not valid JSON, treat it as a string
                body = body.replace(re, `"${value}"`);
            }
        });

        console.log('Variables replaced', body);
        fs.writeFile(localPath, body, function(err) {
            if (err) return reject(err);
            resolve(localPath);
        });
    });
}
582769
function analyseExprDataHotspot(expr, accessorMeanDynamic) {
    var refs = [];
    var isDynamic;

    function analyseExprs(exprs, accessorMeanDynamic) {
        for (var i = 0, l = exprs.length; i < l; i++) {
            refs = refs.concat(analyseExprDataHotspot(exprs[i], accessorMeanDynamic));
            isDynamic = isDynamic || exprs[i].dynamic;
        }
    }

    switch (expr.type) {
        case ExprType.ACCESSOR:
            isDynamic = accessorMeanDynamic;

            var paths = expr.paths;
            refs.push(paths[0].value);

            if (paths.length > 1) {
                refs.push(paths[0].value + '.' + (paths[1].value || '*'));
            }

            analyseExprs(paths.slice(1), 1);
            break;

        case ExprType.UNARY:
            refs = analyseExprDataHotspot(expr.expr, accessorMeanDynamic);
            isDynamic = expr.expr.dynamic;
            break;

        case ExprType.TEXT:
        case ExprType.BINARY:
        case ExprType.TERTIARY:
            analyseExprs(expr.segs, accessorMeanDynamic);
            break;

        case ExprType.INTERP:
            refs = analyseExprDataHotspot(expr.expr);
            isDynamic = expr.expr.dynamic;

            each(expr.filters, function (filter) {
                analyseExprs(filter.name.paths);
                analyseExprs(filter.args);
            });

            break;

        case ExprType.ARRAY:
        case ExprType.OBJECT:
            for (var i = 0; i < expr.items.length; i++) {
                refs = refs.concat(analyseExprDataHotspot(expr.items[i].expr));
                isDynamic = isDynamic || expr.items[i].expr.dynamic;
            }
            break;
    }

    isDynamic && (expr.dynamic = true);
    return refs;
}
367101
function seekSingle(data, pathStr, result, key) {
    if(pathStr.indexOf('$') < 0){
      result[key] = pathStr;
    }else{
      var seek = jsonPath.eval(data, pathStr) || [];

      result[key] = seek.length ? seek[0] : undefined;
    }
  }
323789
function(data, callback) {
    var json
    try {
        json = JSON.parse(data)
    } catch (exc) {
        return callback(exc)
    }
    callback(null, json)
}
1347286
function (stream, destPath) {
    let data = '';
    return new Promise(function (resolve, reject) {
        stream.on('error', reject);
        stream.on('data', function (d) {
            data += d.toString();
        });
        stream.on('end', function () {
            fs.outputFile(destPath, data, function (err) {
                if (!err) {
                    resolve();
                } else {
                    reject(err);
                }
            });
        });
    });
}
610709
function (path, data) {
        var i = 0,
            len = path.length;
        for (;i<len;i++) {
            if (isObject(data) && (path[i] in data)) {
                data = data[path[i]];
            } else {
                data = undefined;
                break;
            }
        }
        return data;
    }
1122032
function onData(data) {

		data = data.toString("ascii");
		bufferedData += data;

		if (debug) console.log("Server: " + util.inspect(data));

		if (checkResp === true) {

			if (bufferedData.substr(0, 3) === "+OK") {

				checkResp = false;
				response = true;

			} else if (bufferedData.substr(0, 4) === "-ERR") {

				checkResp = false;
				response = false;

			// The following is only used for SASL
			} else if (multiline === false) {

				checkResp = false;
				response = true;

			}
		}

		if (checkResp === false) {

			if (multiline === true && (response === false || bufferedData.substr(bufferedData.length-5) === "\r\n.\r\n")) {

				// Make a copy to avoid race conditions
				var responseCopy = response;
				var bufferedDataCopy = bufferedData;

				response = null;
				checkResp = true;
				multiline = false;
				bufferedData = "";

				callback(responseCopy, bufferedDataCopy);

			} else if (multiline === false) {

				// Make a copy to avoid race conditions
				var responseCopy = response;
				var bufferedDataCopy = bufferedData;

				response = null;
				checkResp = true;
				multiline = false;
				bufferedData = "";

				callback(responseCopy, bufferedDataCopy);

			}
		} 
	}
192852
function resolvePaths(globals, data, value) {
    var regex = /\{\{(.*?)\}\}/g;

    value = value.replace(regex, function (match, path) {
        var result;

        // Handle aliases
        path = pathAliases[path] ? pathAliases[path] : path;
        // Handle Handlebars .[] style arrays
        path = path.replace(/\.\[/g, '[');

        if (path.charAt(0) === '@') {
            result = jsonpath.query(globals, path.substr(1));
        } else {
            // Do the query, which always returns an array of matches
            result = jsonpath.query(data, path);
        }

        // Handle the case where the single data property we return is a Date
        // Data.toString() is not DB compatible, so use `toISOString()` instead
        if (_.isDate(result[0])) {
            result[0] = result[0].toISOString();
        }

        // Concatenate the results with a comma, handles common case of multiple tag slugs
        return result.join(',');
    });

    return value;
}
312332
function rimrafWithRetries(...args) {
    let retries = 0;
    return new Promise((resolve, reject) => {
        function rm(...rmArgs) {
            try {
                rimraf.sync(...rmArgs);
                resolve();
            } catch (e) {
                retries += 1;
                if (retries < 5) {
                    setTimeout(() => {
                        rm(...rmArgs);
                    }, 100);
                } else {
                    reject(e);
                }
            }
        }
        rm(...args);
    });
}