<commit_before>//TODO: simple -r provider to get nice test bundles via require global.

//TODO Standalone compilation with no module checking: window.Name = module (use case - weakset);
//TODO Concat stdin
//TODO wrap final result into simple closure to provide closurecompiler scope

//TODO tests
//TODO pass module prefix
//TODO debug mode
//TODO cut comments
//TODO exclude files
//TODO externs - list of global reserved words
//TODO humanized output
//TODO same options as browserify, especially -r

//FIXME provide require function at the top for runtime calculations

var util = require('util');
var map = require('map-stream');
var fs = require('fs');
var slug = require('slug');
var path = require('path');
var concat = require('concat-stream');
var esprima = require('esprima');
var escodegen = require('escodegen');
var escope = require('escope');
var resolve = require('resolve');
var browserify = require('browserify');

/** processing options */
var options = {
	/** Prefix for module global vars */
	prefix: '_m_'
};

/**
 * @module uncommonjs
 *
 * @param {Array|Stream} arg Whether list of files or stdin stream
 *
 * @return {[type]} [description]
 */
module.exports = function(arg, opts, cb){
	//TODO: extend self options with external opts passed

	var b = browserify(arg, opts);

	var bundle, result;

	b.on('error', function(a,b,c){
		throw Error(a,b,c);
	});

	//start pipeline
	b.pipeline.get('dedupe')

	//prepare each module
	.pipe(
		map(
			function(dep, done){
				processModule(dep);
				done(null, dep);
			})
		)

	//form result
	.pipe(
		concat(
			function(list){
				result = processResult(list);

				if (opts.wrap) {
					result = opts.wrap.replace('%output%', result);
				}

				bundle.emit('success', result);
			}
		)
	);

	//Start browserify (bundle)
	bundle = b.bundle();

	return bundle;
};

/** global variables aliases dict: 'var1: var1, var2: var2alias' */
var globalVariables = {};

/** module variable names and aliases keyed by module ids */
var moduleVariableName = {};

/** cache of module paths keyed by ids */
var modulePath = {};

/**
 * catch `require` in code (too bad, I know, but the fastest relative to esprima)
 * Note that require accepts simple numbers also
 */
var requireRe = /require\(\s*['"]([^'")]*)['"]\s*\)/g;

/**
 * Process resulted module dep list once it’s formed
 *
 * @param {array} list A list of module deps
 *
 * @return {[type]} [description]
 */
function processResult(list){
	//sort deps to include innermost first

	//dupes aliases
	var dupes={};

	//filter list of deps
	list = list

	//remove duplicates
	.filter(function(item){
		//dedupe found by browserify
		if (item.dedupe) {
			dupes[item.id] = item.dedupeIndex;
			return false;
		}
		//search dupes manually in list
		// for (var i = list.length; i--;){
		// 	if (list[i] !== item && list[i].name === item.name) {
		// 		console.log('dedupe', list[i], item)
				// return false;
		// 	}
		// }
		return true;
	})

	//sort deps to declare in proper order
	.sort(function(a,b){
		//if includes one as an other’s dep - declare independent first
		if (hasDep(a, b)) return 1;
		if (hasDep(b, a)) return -1;

		//calc number of deps, return smaller
		//suppose that less-dependent module is better to be declared first
		if (depNumber(a) > depNumber(b)) return 1;
		else return -1;
	});

	//whether a-dep depends on b
	function hasDep(a, b){
		for (var name in a.deps){
			if (a.deps[name] === b.id || dupes[a.deps[name]] === b.id) return true;
		}
		return false;
	}

	function depNumber(a){
		return Object.keys(a.deps).length;
	}

	// list.forEach(function(item){
	// 	item.source = item.source.slice(0,30) + '... ' + item.source.length;
	// });
	// console.log(list)
	// console.log('concat:\n',util.inspect(list, {colors:true}));

	//declare all var module names beforehead
	//in order to not get accessed undeclared
	var declStr = '/**\n * Modules declarations\n */\n';
	declStr += 'var ';
	list.forEach(function(item){
		declStr += item.name + ', ';
	});
	declStr = declStr.slice(0, -2) + ';\n';

	//concat sources in the proper order of declaration
	var result = declStr;
	list.forEach(function(dep){
		result += '\n\n\n/**\n * @module ' + moduleVariableName[dep.id] + '\n * @file ' + modulePath[dep.id] + ' \n */\n\n';
		result += dep.source + '\n';
	});

	//replace require calls
	result = result.replace(requireRe, function(requireStr, modPath, idx, fullSrc){
		var modName;

		//get module name from cached paths
		if (modulePath[modPath]) modName = modulePath[modPath];

		//resolve unresolved module
		else modName = resolve.sync(modPath);

		//replace require with var name
		if (moduleVariableName[modName]) {
			return moduleVariableName[modName];
		}

		throw Error('Module to require isn’t found: `' + modName + '`');
	});

	//if there are runtime requires left
	//append `require` function returning found modules' if any
	//TODO
	// if (/\brequire\b/.test(result)) {
	// 	result =
	// 	(function require(name){
	// 		return m[name];
	// 	}).toSource() + '\n'
	// 	+ result;
	// }

	//for each standalone passed, create global unadvancedoptimizable var

	//for each require passed, create an entry in require set

	return result;
}

/**
 * Process a separate module
 *
 * @param {object} dep A dependency object (module info)
 *
 * @return {object} The dep with rebuilt `source` property
 */
function processModule(dep){
	// console.log('---------dep:\n',util.inspect(dep, {colors:true}));
	var dir = path.dirname(dep.file);
	var src = dep.source;

	//get module var name
	var moduleVarName = getModuleVarName(dep);

	//save module name to declare it beforehead as a first-class var
	dep.name = moduleVarName;
	moduleVariableName[dep.id] = moduleVarName;
	moduleVariableName[dep.file] = moduleVarName;
	modulePath[dep.id] = dep.file;
	// console.log('\n> Module', dep.id, ':', moduleVarName);

	//replace `exports` & `module.exports` in code with `newName`
	//stupid regex replacers are the way faster and simpler than esprima for that goal
	src = src.replace(/\bmodule\.exports/g, moduleVarName);
	src = src.replace(/\bmodule\b\[\s*['"]exports['"]\s*\]/g, moduleVarName);
	src = src.replace(/\bexports\b/g, moduleVarName);

	//replace all `module` calls with an empty object
	//FIXME: ensure this is right
	src = src.replace(/\bmodule\b/g, '{}');

	//resolve require calls (insert module paths instead of module names)
	//FIXME: what about runtime/calculated require calls?
	src = src.replace(requireRe, function(requireStr, moduleName, idx, fullSrc){
		try {
			moduleName = resolve.sync(moduleName, {
				basedir: dir
			});
		} catch (e) {

		}

		return 'require(\'' + moduleName.replace(/\\/g, '/') + '\')';
	});
	// console.log(src)

	//Resolve global modules variables conflict - analyze scopes
	var ast = esprima.parse(src);

	//optimistic flag causes getting references for variables (places where they’re met)
	var moduleVars = escope.analyze(ast, {optimistic: true}).scopes[0].variables;

	//rename conflicting first-level vars
	//its first-level vars declared within a module, not the global-scope vars
	moduleVars.forEach(function(item){

		if (globalVariables[item.name]) {
			//rename variable
			var newName = moduleVarName + '_' + item.name;

			//replace each occurence
			item.references.forEach(function(ref){
				ref.identifier.name = newName;
			});

			//as well as a definition
			item.identifiers.forEach(function(ident){
				ident.name = newName;
			});
		} else {
			//reserve var name
			globalVariables[item.name] = item.name;
		}
	});

	//rebuild source
	//FIXME: include comments
	//FIXME: include source map optionally
	dep.source = escodegen.generate(ast);

	return dep;
}

//extend slugifier charmap (replace . and - in paths with $ and _ in code)
slug.charmap['.'] = '$';
slug.charmap['-'] = '_';

/**
 * Name variable based on module id
 */
//TODO: fuck all this stuff. Get rid of fucking name resolving via path. Use natural module names which should be available in deps resolver.
function getModuleVarName(dep){
	var name;

	//path to module
	var modulePath;

	var idx = dep.file.lastIndexOf('node_modules');

	//catch path to dep after the last node_modules dirname, if any
	if (idx >= 0){
		var path = dep.file.slice(idx);
		var matchResult = /node_modules[\/\\](.+)/.exec(path);
		modulePath = matchResult[1];
	}

	//if no node_modules in path and dep is entry - get last dir as module path
	else if (dep.entry) {
		var matchResult = /([^\/\\]+)[\/\\][^\/\\]+$/.exec(dep.file);
		modulePath = matchResult[1];
	}

	//try to take dirname before index.js, if dep is an entry
	if (modulePath)	{
		//shorten index.js
		if (/[\\\/]index.js$/.test(modulePath)) name = modulePath.slice(0, -9);
		else name = modulePath;
	}

	//else take id as a name
	if (!name) name = dep.id;

	name = slug(name).toLowerCase();

	//get rid of .js postfix
	if (name.slice(-3) === '.js') name = name.slice(0,-3);

	return options.prefix + name;
}<commit_msg>Detect inner deps<commit_after>//TODO: simple -r provider to get nice test bundles via require global.

//TODO Standalone compilation with no module checking: window.Name = module (use case - weakset);
//TODO Concat stdin
//TODO wrap final result into simple closure to provide closurecompiler scope

//TODO tests
//TODO pass module prefix
//TODO debug mode
//TODO cut comments
//TODO exclude files
//TODO externs - list of global reserved words
//TODO humanized output
//TODO same options as browserify, especially -r

//FIXME provide require function at the top for runtime calculations

var util = require('util');
var map = require('map-stream');
var fs = require('fs');
var slug = require('slug');
var path = require('path');
var concat = require('concat-stream');
var esprima = require('esprima');
var escodegen = require('escodegen');
var escope = require('escope');
var resolve = require('resolve');
var browserify = require('browserify');

/** processing options */
var options = {
	/** Prefix for module global vars */
	prefix: '_m_'
};

/**
 * @module uncommonjs
 *
 * @param {Array|Stream} arg Whether list of files or stdin stream
 *
 * @return {[type]} [description]
 */
module.exports = function(arg, opts, cb){
	//TODO: extend self options with external opts passed

	var b = browserify(arg, opts);

	var bundle, result;

	b.on('error', function(a,b,c){
		throw Error(a,b,c);
	});

	//start pipeline
	b.pipeline.get('dedupe')

	//prepare each module
	.pipe(
		map(
			function(dep, done){
				processModule(dep);
				done(null, dep);
			})
		)

	//form result
	.pipe(
		concat(
			function(list){
				result = processResult(list);

				if (opts.wrap) {
					result = opts.wrap.replace('%output%', result);
				}

				bundle.emit('success', result);
			}
		)
	);

	//Start browserify (bundle)
	bundle = b.bundle();

	return bundle;
};

/** global variables aliases dict: 'var1: var1, var2: var2alias' */
var globalVariables = {};

/** module variable names and aliases keyed by module ids */
var moduleVariableName = {};

/** cache of module paths keyed by ids */
var modulePath = {};

/**
 * catch `require` in code (too bad, I know, but the fastest relative to esprima)
 * Note that require accepts simple numbers also
 */
var requireRe = /require\(\s*['"]([^'")]*)['"]\s*\)/g;

/**
 * Process resulted module dep list once it’s formed
 *
 * @param {array} list A list of module deps
 *
 * @return {[type]} [description]
 */
function processResult(list){
	//sort deps to include innermost first

	//dupes aliases
	var dupes={},

	//dict of items by ids
		items={};

	//filter list of deps
	list = list

	//remove duplicates
	.filter(function(item){
		//create dict of modules by ids
		items[item.id] = item;

		//dedupe found by browserify
		if (item.dedupe) {
			dupes[item.id] = item.dedupeIndex;
			return false;
		}
		//search dupes manually in list
		// for (var i = list.length; i--;){
		// 	if (list[i] !== item && list[i].name === item.name) {
		// 		console.log('dedupe', list[i], item)
				// return false;
		// 	}
		// }
		return true;
	})

	//sort deps to declare in proper order
	.sort(function(a,b){
		//if includes one as an other’s dep - declare independent first
		if (hasDep(a, b)) return 1;
		if (hasDep(b, a)) return -1;

		//calc number of deps, return smaller
		//suppose that less-dependent module is better to be declared first
		if (depNumber(a) > depNumber(b)) return 1;
		else return -1;
	});

	//whether a-dep depends on b
	function hasDep(a, b){
		for (var name in a.deps){
			if (a.deps[name] === b.id || dupes[a.deps[name]] === b.id) return true;

			//find inner dep
			if ( hasDep(items[a.deps[name]], b)) return true;
		}
		return false;
	}

	function depNumber(a){
		return Object.keys(a.deps).length;
	}

	// list.forEach(function(item){
	// 	item.source = item.source.slice(0,30) + '... ' + item.source.length;
	// });
	// console.log(list)
	// console.log('concat:\n',util.inspect(list, {colors:true}));

	//declare all var module names beforehead
	//in order to not get accessed undeclared
	var declStr = '/**\n * Modules declarations\n */\n';
	declStr += 'var ';
	list.forEach(function(item){
		declStr += item.name + ', ';
	});
	declStr = declStr.slice(0, -2) + ';\n';

	//concat sources in the proper order of declaration
	var result = declStr;
	list.forEach(function(dep){
		result += '\n\n\n/**\n * @module ' + moduleVariableName[dep.id] + '\n * @file ' + modulePath[dep.id] + ' \n */\n\n';
		result += dep.source + '\n';
	});

	//replace require calls
	result = result.replace(requireRe, function(requireStr, modPath, idx, fullSrc){
		var modName;

		//get module name from cached paths
		if (modulePath[modPath]) modName = modulePath[modPath];

		//resolve unresolved module
		else modName = resolve.sync(modPath);

		//replace require with var name
		if (moduleVariableName[modName]) {
			return moduleVariableName[modName];
		}

		throw Error('Module to require isn’t found: `' + modName + '`');
	});

	//if there are runtime requires left
	//append `require` function returning found modules' if any
	//TODO
	// if (/\brequire\b/.test(result)) {
	// 	result =
	// 	(function require(name){
	// 		return m[name];
	// 	}).toSource() + '\n'
	// 	+ result;
	// }

	//for each standalone passed, create global unadvancedoptimizable var

	//for each require passed, create an entry in require set

	return result;
}

/**
 * Process a separate module
 *
 * @param {object} dep A dependency object (module info)
 *
 * @return {object} The dep with rebuilt `source` property
 */
function processModule(dep){
	// console.log('---------dep:\n',util.inspect(dep, {colors:true}));
	var dir = path.dirname(dep.file);
	var src = dep.source;

	//get module var name
	var moduleVarName = getModuleVarName(dep);

	//save module name to declare it beforehead as a first-class var
	dep.name = moduleVarName;
	moduleVariableName[dep.id] = moduleVarName;
	moduleVariableName[dep.file] = moduleVarName;
	modulePath[dep.id] = dep.file;
	// console.log('\n> Module', dep.id, ':', moduleVarName);

	//replace `exports` & `module.exports` in code with `newName`
	//stupid regex replacers are the way faster and simpler than esprima for that goal
	src = src.replace(/\bmodule\.exports/g, moduleVarName);
	src = src.replace(/\bmodule\b\[\s*['"]exports['"]\s*\]/g, moduleVarName);
	src = src.replace(/\bexports\b/g, moduleVarName);

	//replace all `module` calls with an empty object
	//FIXME: ensure this is right
	src = src.replace(/\bmodule\b/g, '{}');

	//resolve require calls (insert module paths instead of module names)
	//FIXME: what about runtime/calculated require calls?
	src = src.replace(requireRe, function(requireStr, moduleName, idx, fullSrc){
		try {
			moduleName = resolve.sync(moduleName, {
				basedir: dir
			});
		} catch (e) {

		}

		return 'require(\'' + moduleName.replace(/\\/g, '/') + '\')';
	});
	// console.log(src)

	//Resolve global modules variables conflict - analyze scopes
	var ast = esprima.parse(src);

	//optimistic flag causes getting references for variables (places where they’re met)
	var moduleVars = escope.analyze(ast, {optimistic: true}).scopes[0].variables;

	//rename conflicting first-level vars
	//its first-level vars declared within a module, not the global-scope vars
	moduleVars.forEach(function(item){

		if (globalVariables[item.name]) {
			//rename variable
			var newName = moduleVarName + '_' + item.name;

			//replace each occurence
			item.references.forEach(function(ref){
				ref.identifier.name = newName;
			});

			//as well as a definition
			item.identifiers.forEach(function(ident){
				ident.name = newName;
			});
		} else {
			//reserve var name
			globalVariables[item.name] = item.name;
		}
	});

	//rebuild source
	//FIXME: include comments
	//FIXME: include source map optionally
	dep.source = escodegen.generate(ast);

	return dep;
}

//extend slugifier charmap (replace . and - in paths with $ and _ in code)
slug.charmap['.'] = '$';
slug.charmap['-'] = '_';

/**
 * Name variable based on module id
 */
//TODO: fuck all this stuff. Get rid of fucking name resolving via path. Use natural module names which should be available in deps resolver.
function getModuleVarName(dep){
	var name;

	//path to module
	var modulePath;

	var idx = dep.file.lastIndexOf('node_modules');

	//catch path to dep after the last node_modules dirname, if any
	if (idx >= 0){
		var path = dep.file.slice(idx);
		var matchResult = /node_modules[\/\\](.+)/.exec(path);
		modulePath = matchResult[1];
	}

	//if no node_modules in path and dep is entry - get last dir as module path
	else if (dep.entry) {
		var matchResult = /([^\/\\]+)[\/\\][^\/\\]+$/.exec(dep.file);
		modulePath = matchResult[1];
	}

	//try to take dirname before index.js, if dep is an entry
	if (modulePath)	{
		//shorten index.js
		if (/[\\\/]index.js$/.test(modulePath)) name = modulePath.slice(0, -9);
		else name = modulePath;
	}

	//else take id as a name
	if (!name) name = dep.id;

	name = slug(name).toLowerCase();

	//get rid of .js postfix
	if (name.slice(-3) === '.js') name = name.slice(0,-3);

	return options.prefix + name;
}<|endoftext|>


<commit_before>// By Curran Kelleher
// Last updated May 2016

// See https://github.com/datavis-tech/reactive-function
var ReactiveFunction = require("reactive-function");

// See https://github.com/datavis-tech/reactive-property
var ReactiveProperty = require("reactive-property");

// Functional utility for invoking methods on collections.
function invoke(method){
  return function(d){
    return d[method]();
  };
}

// The constructor for reactive models.
// This function is exported as the public API of this module.
function ReactiveModel(){

  // An array of property names for exposed properties.
  var exposedProperties;

  // This is a string, the name of the last property added.
  // This is used in `expose()`;
  var lastPropertyAdded;

  // The configuration of the model is represented as an object and stored
  // in this reactive property. Note that only values for exposed properties
  // whose values differ from their defaults are included in the configuration object.
  // The purpose of the configuration accessor API is serialization and deserialization,
  // so default values are left out for a concise serialized form.
  var configurationProperty = ReactiveProperty();
  configurationProperty.propertyName = "configuration";

  // This is a reactive function set up to listen for changes in all
  // exposed properties and set the configurationProperty value.
  var configurationReactiveFunction;

  // An array of reactive functions that have been set up on this model.
  // These are tracked only so they can be destroyed in model.destroy().
  var reactiveFunctions = [];

  // The model instance object.
  // This is the value returned from the constructor.
  var model = function (){
    var outputPropertyName, callback, inputPropertyNames

    if(arguments.length === 0){
      return configurationProperty();
    } else if(arguments.length === 1){
      if(typeof arguments[0] === "object"){

        // The invocation is of the form model(configuration)
        return setConfiguration(arguments[0]);
      } else {

        // The invocation is of the form model(propertyName)
        return addProperty(arguments[0]);
      }
    } else if(arguments.length === 2){
      if(typeof arguments[0] === "function"){

        // The invocation is of the form model(callback, inputPropertyNames)
        inputPropertyNames = arguments[1];
        callback = arguments[0];
        outputPropertyName = undefined;
      } else {

        // The invocation is of the form model(propertyName, defaultValue)
        return addProperty(arguments[0], arguments[1]);
      }
    } else if(arguments.length === 3){
      outputPropertyName = arguments[0];
      callback = arguments[1];
      inputPropertyNames = arguments[2];
    }

    // inputPropertyNames may be a string of comma-separated property names,
    // or an array of property names.
    if(typeof inputPropertyNames === "string"){
      inputPropertyNames = inputPropertyNames.split(",").map(invoke("trim"));
    }

    var inputs = inputPropertyNames.map(function (propertyName){
      var property = getProperty(propertyName);
      if(typeof property === "undefined"){
        throw new Error([
          "The property \"",
          propertyName,
          "\" was referenced as a dependency for a reactive function before it was defined. ",
          "Please define each property first before referencing them in reactive functions."
        ].join(""));
      }
      return property;
    });

    // Create a new reactive property for the output and assign it to the model.
    if(outputPropertyName){
      var output = ReactiveProperty();
      output.propertyName = outputPropertyName;

      if(model[outputPropertyName]){
        throw new Error("The output property \"" + outputPropertyName + "\" is already defined.");
      }

      model[outputPropertyName] = output;
    }

    // If the number of arguments expected by the callback is one greater than the
    // number of inputs, then the last argument is the "done" callback, and this
    // reactive function will be set up to be asynchronous. The "done" callback should
    // be called with the new value of the output property asynchronously.
    var isAsynchronous = (callback.length === inputs.length + 1);
    if(isAsynchronous){
      reactiveFunctions.push(ReactiveFunction({
        inputs: inputs,
        callback: function (){

          // Convert the arguments passed into this function into an array.
          var args = Array.prototype.slice.call(arguments);

          // Push the "done" callback onto the args array.
          // We are actally passing the output reactive property here, invoking it
          // as the "done" callback will set the value of the output property.
          args.push(output);

          // Wrap in setTimeout to guarantee that the output property is set
          // asynchronously, outside of the current digest. This is necessary
          // to ensure that if developers inadvertently invoke the "done" callback
          // synchronously, their code will still have the expected behavior.
          setTimeout(function (){

            // Invoke the original callback with the args array as arguments.
            callback.apply(null, args);
          });
        }
      }));
    } else {
      reactiveFunctions.push(ReactiveFunction({
        inputs: inputs,
        output: output, // This may be undefined.
        callback: callback
      }));
    }
    return model;
  };

  // Gets a reactive property from the model by name.
  // Convenient for functional patterns like `propertyNames.map(getProperty)`
  function getProperty(propertyName){
    return model[propertyName];
  }

  // Adds a property to the model that is not exposed,
  // meaning that it is not included in the configuration object.
  function addProperty(propertyName, defaultValue){
    var property = ReactiveProperty(defaultValue);
    property.propertyName = propertyName;
    model[propertyName] = property;
    lastPropertyAdded = propertyName;
    return model;

    // TODO throw an error if the name is not available (e.g. another property name, "configuration" or "addPublicProperty").
  }

  // Exposes the last added property to the configuration.
  function expose(){

    // TODO test this
    // if(!isDefined(defaultValue)){
    //  throw new Error("model.addPublicProperty() is being " +
    //    "invoked with an undefined default value. Default values for exposed properties " +
    //    "must be defined, to guarantee predictable behavior. For exposed properties that " +
    //    "are optional and should have the semantics of an undefined value, " +
    //    "use null as the default value.");
    //}

    // TODO test this
    if(!lastPropertyAdded){
      throw Error("Expose() was called without first adding a property.");
    }

    var propertyName = lastPropertyAdded;

    if(!exposedProperties){
      exposedProperties = [];
    }
    exposedProperties.push(propertyName);

    // Destroy the previous reactive function that was listening for changes
    // in all exposed properties except the newly added one.
    // TODO think about how this might be done only once, at the same time isFinalized is set.
    if(configurationReactiveFunction){
      configurationReactiveFunction.destroy();
    }

    // Set up the new reactive function that will listen for changes
    // in all exposed properties including the newly added one.
    var inputPropertyNames = exposedProperties;

    //console.log(inputPropertyNames);
    configurationReactiveFunction = ReactiveFunction({
      inputs: inputPropertyNames.map(getProperty),
      output: configurationProperty,
      callback: function (){
        var configuration = {};
        inputPropertyNames.forEach(function (propertyName){
          var property = getProperty(propertyName);

          // Omit default values from the returned configuration object.
          if(property() !== property.default()){
            configuration[propertyName] = property();
          }
        });
        return configuration;
      }
    });

    // Support method chaining.
    return model;
  }

  function setConfiguration(newConfiguration){

    exposedProperties.forEach(function (propertyName){
      var property = getProperty(propertyName);
      var oldValue = property();
      var newValue;

      if(propertyName in newConfiguration){
        newValue = newConfiguration[propertyName];
      } else {
        newValue = property.default();
      }

      if(oldValue !== newValue){
        model[propertyName](newValue);
      }
    });

    return model;
  }

  // Destroys all reactive functions and properties that have been added to the model.
  function destroy(){

    // Destroy reactive functions.
    reactiveFunctions.forEach(invoke("destroy"));
    if(configurationReactiveFunction){
      configurationReactiveFunction.destroy();
    }

    // Destroy properties (removes listeners).
    Object.keys(model).forEach(function (propertyName){
      var property = model[propertyName];
      if(property.destroy){
        property.destroy();
      }
    });

    // Release references.
    reactiveFunctions = undefined;
    configurationReactiveFunction = undefined;
  }

  function call (fn){
    var args = Array.prototype.slice.call(arguments);
    args[0] = model;
    fn.apply(null, args);
    return model;
  };

  model.expose = expose;
  model.destroy = destroy;
  model.call = call;
  model.on = function (callback){

    // Ensure the callback is invoked asynchronously,
    // so that property values can be set inside it.
    return configurationProperty.on(function (newConfiguration){
      setTimeout(function (){
        callback(newConfiguration);
      }, 0);
    });
  };

  model.off = configurationProperty.off;

  // Expose digest on instances for convenience.
  model.digest = function (){
    ReactiveModel.digest();
    return model;
  };

  return model;
}

// Expose static functions from ReactiveFunction.
ReactiveModel.digest         = ReactiveFunction.digest;
ReactiveModel.serializeGraph = ReactiveFunction.serializeGraph;
ReactiveModel.link           = ReactiveFunction.link;

//ReactiveModel.nextFrame = ReactiveFunction.nextFrame;

module.exports = ReactiveModel;
<commit_msg>Single var pattern, cleanup<commit_after>// By Curran Kelleher
// Last updated May 2016

// See https://github.com/datavis-tech/reactive-function
var ReactiveFunction = require("reactive-function");

// See https://github.com/datavis-tech/reactive-property
var ReactiveProperty = require("reactive-property");

// Functional utility for invoking methods on collections.
function invoke(method){
  return function(d){
    return d[method]();
  };
}

// The constructor for reactive models.
// This function is exported as the public API of this module.
function ReactiveModel(){

  // An array of property names for exposed properties.
  var exposedProperties;

  // This is a string, the name of the last property added.
  // This is used in `expose()`;
  var lastPropertyAdded;

  // The configuration of the model is represented as an object and stored
  // in this reactive property. Note that only values for exposed properties
  // whose values differ from their defaults are included in the configuration object.
  // The purpose of the configuration accessor API is serialization and deserialization,
  // so default values are left out for a concise serialized form.
  var configurationProperty = ReactiveProperty();
  configurationProperty.propertyName = "configuration";

  // This is a reactive function set up to listen for changes in all
  // exposed properties and set the configurationProperty value.
  var configurationReactiveFunction;

  // An array of reactive functions that have been set up on this model.
  // These are tracked only so they can be destroyed in model.destroy().
  var reactiveFunctions = [];

  // The model instance object.
  // This is the value returned from the constructor.
  var model = function (){

    var outputPropertyName,
        callback,
        inputPropertyNames,
        inputs,
        output;

    if(arguments.length === 0){
      return configurationProperty();
    } else if(arguments.length === 1){
      if(typeof arguments[0] === "object"){

        // The invocation is of the form model(configuration)
        return setConfiguration(arguments[0]);
      } else {

        // The invocation is of the form model(propertyName)
        return addProperty(arguments[0]);
      }
    } else if(arguments.length === 2){
      if(typeof arguments[0] === "function"){

        // The invocation is of the form model(callback, inputPropertyNames)
        inputPropertyNames = arguments[1];
        callback = arguments[0];
        outputPropertyName = undefined;
      } else {

        // The invocation is of the form model(propertyName, defaultValue)
        return addProperty(arguments[0], arguments[1]);
      }
    } else if(arguments.length === 3){
      outputPropertyName = arguments[0];
      callback = arguments[1];
      inputPropertyNames = arguments[2];
    }

    // inputPropertyNames may be a string of comma-separated property names,
    // or an array of property names.
    if(typeof inputPropertyNames === "string"){
      inputPropertyNames = inputPropertyNames.split(",").map(invoke("trim"));
    }

    inputs = inputPropertyNames.map(function (propertyName){
      var property = getProperty(propertyName);
      if(typeof property === "undefined"){
        throw new Error([
          "The property \"",
          propertyName,
          "\" was referenced as a dependency for a reactive function before it was defined. ",
          "Please define each property first before referencing them in reactive functions."
        ].join(""));
      }
      return property;
    });

    // Create a new reactive property for the output and assign it to the model.
    if(outputPropertyName){
      output = ReactiveProperty();
      output.propertyName = outputPropertyName;

      if(model[outputPropertyName]){
        throw new Error("The output property \"" + outputPropertyName + "\" is already defined.");
      }

      model[outputPropertyName] = output;
    }

    // If the number of arguments expected by the callback is one greater than the
    // number of inputs, then the last argument is the "done" callback, and this
    // reactive function will be set up to be asynchronous. The "done" callback should
    // be called with the new value of the output property asynchronously.
    var isAsynchronous = (callback.length === inputs.length + 1);
    if(isAsynchronous){
      reactiveFunctions.push(ReactiveFunction({
        inputs: inputs,
        callback: function (){

          // Convert the arguments passed into this function into an array.
          var args = Array.prototype.slice.call(arguments);

          // Push the "done" callback onto the args array.
          // We are actally passing the output reactive property here, invoking it
          // as the "done" callback will set the value of the output property.
          args.push(output);

          // Wrap in setTimeout to guarantee that the output property is set
          // asynchronously, outside of the current digest. This is necessary
          // to ensure that if developers inadvertently invoke the "done" callback
          // synchronously, their code will still have the expected behavior.
          setTimeout(function (){

            // Invoke the original callback with the args array as arguments.
            callback.apply(null, args);
          });
        }
      }));
    } else {
      reactiveFunctions.push(ReactiveFunction({
        inputs: inputs,
        output: output, // This may be undefined.
        callback: callback
      }));
    }
    return model;
  };

  // Gets a reactive property from the model by name.
  // Convenient for functional patterns like `propertyNames.map(getProperty)`
  function getProperty(propertyName){
    return model[propertyName];
  }

  // Adds a property to the model that is not exposed,
  // meaning that it is not included in the configuration object.
  function addProperty(propertyName, defaultValue){
    var property = ReactiveProperty(defaultValue);
    property.propertyName = propertyName;
    model[propertyName] = property;
    lastPropertyAdded = propertyName;
    return model;

    // TODO throw an error if the name is not available (e.g. another property name, "configuration" or "addPublicProperty").
  }

  // Exposes the last added property to the configuration.
  function expose(){

    // TODO test this
    // if(!isDefined(defaultValue)){
    //  throw new Error("model.addPublicProperty() is being " +
    //    "invoked with an undefined default value. Default values for exposed properties " +
    //    "must be defined, to guarantee predictable behavior. For exposed properties that " +
    //    "are optional and should have the semantics of an undefined value, " +
    //    "use null as the default value.");
    //}

    // TODO test this
    if(!lastPropertyAdded){
      throw Error("Expose() was called without first adding a property.");
    }

    var propertyName = lastPropertyAdded;

    if(!exposedProperties){
      exposedProperties = [];
    }
    exposedProperties.push(propertyName);

    // Destroy the previous reactive function that was listening for changes
    // in all exposed properties except the newly added one.
    // TODO think about how this might be done only once, at the same time isFinalized is set.
    if(configurationReactiveFunction){
      configurationReactiveFunction.destroy();
    }

    // Set up the new reactive function that will listen for changes
    // in all exposed properties including the newly added one.
    var inputPropertyNames = exposedProperties;

    //console.log(inputPropertyNames);
    configurationReactiveFunction = ReactiveFunction({
      inputs: inputPropertyNames.map(getProperty),
      output: configurationProperty,
      callback: function (){
        var configuration = {};
        inputPropertyNames.forEach(function (propertyName){
          var property = getProperty(propertyName);

          // Omit default values from the returned configuration object.
          if(property() !== property.default()){
            configuration[propertyName] = property();
          }
        });
        return configuration;
      }
    });

    // Support method chaining.
    return model;
  }

  function setConfiguration(newConfiguration){

    exposedProperties.forEach(function (propertyName){
      var property = getProperty(propertyName);
      var oldValue = property();
      var newValue;

      if(propertyName in newConfiguration){
        newValue = newConfiguration[propertyName];
      } else {
        newValue = property.default();
      }

      if(oldValue !== newValue){
        model[propertyName](newValue);
      }
    });

    return model;
  }

  // Destroys all reactive functions and properties that have been added to the model.
  function destroy(){

    // Destroy reactive functions.
    reactiveFunctions.forEach(invoke("destroy"));
    if(configurationReactiveFunction){
      configurationReactiveFunction.destroy();
    }

    // Destroy properties (removes listeners).
    Object.keys(model).forEach(function (propertyName){
      var property = model[propertyName];
      if(property.destroy){
        property.destroy();
      }
    });

    // Release references.
    reactiveFunctions = undefined;
    configurationReactiveFunction = undefined;
  }

  function call (fn){
    var args = Array.prototype.slice.call(arguments);
    args[0] = model;
    fn.apply(null, args);
    return model;
  };

  model.expose = expose;
  model.destroy = destroy;
  model.call = call;
  model.on = function (callback){

    // Ensure the callback is invoked asynchronously,
    // so that property values can be set inside it.
    return configurationProperty.on(function (newConfiguration){
      setTimeout(function (){
        callback(newConfiguration);
      }, 0);
    });
  };

  model.off = configurationProperty.off;

  // Expose digest on instances for convenience.
  model.digest = function (){
    ReactiveModel.digest();
    return model;
  };

  return model;
}

// Expose static functions from ReactiveFunction.
ReactiveModel.digest         = ReactiveFunction.digest;
ReactiveModel.serializeGraph = ReactiveFunction.serializeGraph;
ReactiveModel.link           = ReactiveFunction.link;

//ReactiveModel.nextFrame = ReactiveFunction.nextFrame;

module.exports = ReactiveModel;
<|endoftext|>


<commit_before>var qs = require('querystring');

var debug = require('debug')('chirp-rest');
var OAuth = require('oauth-request');

module.exports = ChirpRest;

function ChirpRest(opt) {
    if(!(this instanceof ChirpRest)) {
        return new ChirpRest(opt);
    }

    if(!(opt.consumer && opt.consumer.public && opt.consumer.secret)) {
        throw new Error('consumer.public and consumer.secret are required');
    }

    if(!(opt.token && opt.token.public && opt.token.secret)) {
        throw new Error('token.public and token.secret are required');
    }

    this.consumer = opt.consumer;
    this.token    = opt.token;

    this.oauth = OAuth({
        consumer: this.consumer,
        token: this.token
    });
}

/**
 * debug
 *
 * @api private
 */
ChirpRest.prototype._log = debug;

ChirpRest.prototype.get = function(url, param, callback) {
    if(arguments.length === 2) {
        callback = param;
        param = {};
    }

    if(!url) {
        throw new Error('url is required');
    }

    if(!callback) {
        throw new Error('callback is required');
    }

    this._log('#get', url, param);

    this.oauth.get({
        url: url,
        qs: param,
        json: true
    }, callback);
};

ChirpRest.prototype.post = function(url, param, callback) {
    var self = this;

    if(arguments.length === 2) {
        callback = param;
        param = {};
    }

    if(!url) {
        throw new Error('url is required');
    }

    if(!callback) {
        throw new Error('callback is required');
    }

    this._log('#post', url, param);

    this.oauth.post({
        url: url,
        form: param,
        json: true
    }, callback);
};<commit_msg>add handle twitter err<commit_after>var qs = require('querystring');

var debug = require('debug')('chirp-rest');
var OAuth = require('oauth-request');

module.exports = ChirpRest;

function ChirpRest(opt) {
    if(!(this instanceof ChirpRest)) {
        return new ChirpRest(opt);
    }

    if(!(opt.consumer && opt.consumer.public && opt.consumer.secret)) {
        throw new Error('consumer.public and consumer.secret are required');
    }

    if(!(opt.token && opt.token.public && opt.token.secret)) {
        throw new Error('token.public and token.secret are required');
    }

    this.consumer = opt.consumer;
    this.token    = opt.token;

    this.oauth = OAuth({
        consumer: this.consumer,
        token: this.token
    });
}

/**
 * debug
 *
 * @api private
 */
ChirpRest.prototype._log = debug;

ChirpRest.prototype.get = function(url, param, callback) {
    if(arguments.length === 2) {
        callback = param;
        param = {};
    }

    if(!url) {
        throw new Error('url is required');
    }

    if(!callback) {
        throw new Error('callback is required');
    }

    this._log('#get', url, param);

    this.oauth.get({
        url: url,
        qs: param,
        json: true
    }, function(err, res, body) {
        if(err) {
            debug('#get request err', err);
            return callback(err);
        }

        if(res.statusCode != 200) {
            debug('#get twitter err', body);
            return callback(body);
        }

        debug('#get success');

        return callback(null, body);
    });
};

ChirpRest.prototype.post = function(url, param, callback) {
    var self = this;

    if(arguments.length === 2) {
        callback = param;
        param = {};
    }

    if(!url) {
        throw new Error('url is required');
    }

    if(!callback) {
        throw new Error('callback is required');
    }

    this._log('#post', url, param);

    this.oauth.post({
        url: url,
        form: param,
        json: true
    }, function(err, res, body) {
        if(err) {
            debug('#post request err', err);
            return callback(err);
        }

        if(res.statusCode != 200) {
            debug('#post twitter err', body);
            return callback(body);
        }

        debug('#post success');

        return callback(null, body);
    });
};<|endoftext|>


<commit_before>'use strict';

exports = module.exports = function (doc) {
  if (!doc) doc = {};
  if (typeof doc === 'string') doc = { cookie: doc };
  if (doc.cookie === undefined) doc.cookie = '';

  var self = {};
  self.get = function (key) {
    var cookiesSplat = doc.cookie.split(/;\s*/);
    for (var i = 0; i < cookiesSplat.length; i++) {
      var ps = cookiesSplat[i].split('=');
      var k = decodeURIComponent(ps[0]);
      if (k === key) return decodeURIComponent(ps[1]);
    }
  };

  self.set = function (key, value, opts) {
    if (!opts) opts = {};
    var newCookie = encodeURIComponent(key) + '=' + encodeURIComponent(value);

    if (opts.hasOwnProperty('expires')){
      newCookie += '; expires=' + opts.expires;
    }

    if (opts.hasOwnProperty('path')) {
      newCookie += '; path=' + opts.path;
    }

    if (opts.hasOwnProperty('domain')) {
      newCookie += '; domain=' + opts.domain;
    }

    if (opts.hasOwnProperty('secure')) {
      newCookie += '; secure';
    }

    doc.cookie = newCookie;

    return newCookie;
  };
  return self;
};

if (typeof document !== 'undefined') {
  var cookie = exports(document);
  exports.get = cookie.get;
  exports.set = cookie.set;
}
<commit_msg>Refactored main file<commit_after>'use strict';

var bake = function (doc){
  if(!doc) doc = {};
  if(typeof doc === 'string') doc = { cookie: doc };
  if(doc.cookie === undefined) doc.cookie = '';

  // Returning object
  var self = {
    get: function (key){
      var cookiesSplat = doc.cookie.split(/;\s*/);
      for (var i = 0; i < cookiesSplat.length; i++) {
        var ps = cookiesSplat[i].split('=');
        var k = decodeURIComponent(ps[0]);
        if (k === key) return decodeURIComponent(ps[1]);
      }
    },
    set: function (key, value, opts){
      // Checks before we start
      if (typeof key !== 'string' || typeof value !== 'string') return false;
      if (!opts) opts = {};

      // Creating new cookie string
      var newCookie = encodeURIComponent(key) + '=' + encodeURIComponent(value);
      if (opts.hasOwnProperty('expires')) newCookie += '; expires=' + opts.expires;
      if (opts.hasOwnProperty('path')) newCookie += '; path=' + opts.path;
      if (opts.hasOwnProperty('domain')) newCookie += '; domain=' + opts.domain;
      if (opts.hasOwnProperty('secure')) newCookie += '; secure';

      doc.cookie = newCookie;
      return newCookie;
    }
  };

  return self;
};

if (typeof document !== 'undefined') module.exports = exports = bake(document);
<|endoftext|>


<commit_before>/**
 * c3po : Lightweight protocols manager.
 *
 * Aimed to be used both sides (server side and/or browser side) to give isomorphic approach when designing object that need ressources.
 *
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * @licence MIT
 */
(function(define) {
	"use strict";
	define([], function() {
		var Request = function(request) {
			this.__c3po__ = true;
			this.original = request;
			var protoIndex;
			if (request && request[0] !== '<' && ((protoIndex = request.substring(0, 50).indexOf("::")) > -1)) {
				var parsed = c3po.parseProtocol(request.substring(0, protoIndex));
				this.protocol = parsed.protocol;
				this.method = parsed.method;
				this.args = parsed.args;
				this.pointer = request.substring(protoIndex + 2);
				this.interpolable = c3po.interpolator ? c3po.interpolator.isInterpolable(this.pointer) : false;
			}
		};
		Request.prototype = {
			exec: function(options, context) {
				if (!this.protocol)
					return this.original;
				options = options || options;
				var protocol = c3po.getInitialisedProtocol(this.protocol),
					uri = (this.interpolable && c3po.interpolator && context) ? c3po.interpolator.interpolate(this.pointer, context) : this.pointer,
					method = this.method;
				if (protocol && typeof protocol.then === 'function')
					return protocol.then(function(protocol) {
						return protocol[method](uri, options);
					});
				return protocol[method](uri, options);
			}
		};
		var c3po = {
			Request: Request,
			requestCache: {}, // simply set to null to avoid caching
			protocols: {
				dummy: { // dummy:: protocol for test and demo
					get: function(url) {
						return {
							dummy: url
						};
					}
				}
			},
			fromContext: null, // to use contextualised protocols namespace.
			interpolator: null,
			getProtocol: function(name) {
				var protocol = null;
				// first : look in contextualised namespace if any
				if (c3po.fromContext)
					protocol = c3po.fromContext(name);
				// or look in global namespace
				if (!protocol)
					protocol = c3po.protocols[name];
				if (!protocol)
					throw new Error("no protocol found with : ", name);
				return protocol;
			},
			getInitialisedProtocol: function(name) {
				var protocol = typeof name === 'string' ? c3po.getProtocol(name) : name;
				// manage _deep_flattener_
				if (protocol._deep_flattener_ && !protocol._deep_flattened_)
					return (protocol._deep_flattening_ ? protocol._deep_flattening_ : protocol.flatten())
						.then(function() {
							return c3po.getInitialisedProtocol(protocol);
						});
				// manage ocm resolution
				if (protocol._deep_ocm_)
					protocol = protocol();
				// manage initialisation
				if (protocol.init && !protocol.initialised) {
					var promise;
					if (protocol.initialising)
						promise = protocol.initialising;
					else
						promise = protocol.init();
					if (promise && typeof promise.then === 'function') {
						// async init case
						protocol.initialising = promise;
						return promise.then(function() {
							protocol.initialising = null;
							protocol.initialised = true;
							return protocol;
						});
					}
					protocol.initialised = true;
				}
				return protocol;
			},
			parseProtocol: function(protocol) {
				var output =   {
						method: "get"
					},
					argsPresence = protocol.indexOf("(");
				if (argsPresence > -1) {
					var parenthesis = protocol.substring(argsPresence + 1, protocol.length - 1);
					protocol = protocol.substring(0, argsPresence);
					if (parenthesis)
						output.args = parenthesis.split(",").map(function(s) {
							return s.trim();
						});
				}
				var splitted = protocol.split(".");
				if (splitted.length == 2) {
					protocol = splitted[0];
					output.method = splitted[1];
				}
				output.protocol = protocol;
				return output;
			},
			get: function(request, options, context) {
				if (!request.__c3po__) {
					if (c3po.requestCache && c3po.requestCache[request])
						request = c3po.requestCache[request];
					else {
						request = new c3po.Request(request);
						if (c3po.requestCache)
							c3po.requestCache[request.original] = request;
					}
				}
				return request.exec(options, context);
			},
			getAll: function(requests, options, context) {
				return requests.map(function(request) {
					return c3po.get(request, options, context);
				});
			}
		};
		return c3po;
	});
})(typeof define !== 'undefined' ? define : function(deps, factory) { // AMD/RequireJS format if available
	if (typeof module !== 'undefined')
		module.exports = factory(); // CommonJS environment
	else if (typeof window !== 'undefined')
		window.c3po = factory(null); // raw script, assign to c3po global
	else
		console.warn('c3po has not been mounted somewhere.');
});
<commit_msg>update inner doc title<commit_after>/**
 * c3po : Lightweight but powerful protocols manager.
 *
 * Aimed to be used both sides (server side and/or browser side) to give isomorphic approach when designing object that need ressources.
 *
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 * @licence MIT
 */
(function(define) {
	"use strict";
	define([], function() {
		var Request = function(request) {
			this.__c3po__ = true;
			this.original = request;
			var protoIndex;
			if (request && request[0] !== '<' && ((protoIndex = request.substring(0, 50).indexOf("::")) > -1)) {
				var parsed = c3po.parseProtocol(request.substring(0, protoIndex));
				this.protocol = parsed.protocol;
				this.method = parsed.method;
				this.args = parsed.args;
				this.pointer = request.substring(protoIndex + 2);
				this.interpolable = c3po.interpolator ? c3po.interpolator.isInterpolable(this.pointer) : false;
			}
		};
		Request.prototype = {
			exec: function(options, context) {
				if (!this.protocol)
					return this.original;
				options = options || options;
				var protocol = c3po.getInitialisedProtocol(this.protocol),
					uri = (this.interpolable && c3po.interpolator && context) ? c3po.interpolator.interpolate(this.pointer, context) : this.pointer,
					method = this.method;
				if (protocol && typeof protocol.then === 'function')
					return protocol.then(function(protocol) {
						return protocol[method](uri, options);
					});
				return protocol[method](uri, options);
			}
		};
		var c3po = {
			Request: Request,
			requestCache: {}, // simply set to null to avoid caching
			protocols: {
				dummy: { // dummy:: protocol for test and demo
					get: function(url) {
						return {
							dummy: url
						};
					}
				}
			},
			fromContext: null, // to use contextualised protocols namespace.
			interpolator: null,
			getProtocol: function(name) {
				var protocol = null;
				// first : look in contextualised namespace if any
				if (c3po.fromContext)
					protocol = c3po.fromContext(name);
				// or look in global namespace
				if (!protocol)
					protocol = c3po.protocols[name];
				if (!protocol)
					throw new Error("no protocol found with : ", name);
				return protocol;
			},
			getInitialisedProtocol: function(name) {
				var protocol = typeof name === 'string' ? c3po.getProtocol(name) : name;
				// manage _deep_flattener_
				if (protocol._deep_flattener_ && !protocol._deep_flattened_)
					return (protocol._deep_flattening_ ? protocol._deep_flattening_ : protocol.flatten())
						.then(function() {
							return c3po.getInitialisedProtocol(protocol);
						});
				// manage ocm resolution
				if (protocol._deep_ocm_)
					protocol = protocol();
				// manage initialisation
				if (protocol.init && !protocol.initialised) {
					var promise;
					if (protocol.initialising)
						promise = protocol.initialising;
					else
						promise = protocol.init();
					if (promise && typeof promise.then === 'function') {
						// async init case
						protocol.initialising = promise;
						return promise.then(function() {
							protocol.initialising = null;
							protocol.initialised = true;
							return protocol;
						});
					}
					protocol.initialised = true;
				}
				return protocol;
			},
			parseProtocol: function(protocol) {
				var output =   {
						method: "get"
					},
					argsPresence = protocol.indexOf("(");
				if (argsPresence > -1) {
					var parenthesis = protocol.substring(argsPresence + 1, protocol.length - 1);
					protocol = protocol.substring(0, argsPresence);
					if (parenthesis)
						output.args = parenthesis.split(",").map(function(s) {
							return s.trim();
						});
				}
				var splitted = protocol.split(".");
				if (splitted.length == 2) {
					protocol = splitted[0];
					output.method = splitted[1];
				}
				output.protocol = protocol;
				return output;
			},
			get: function(request, options, context) {
				if (!request.__c3po__) {
					if (c3po.requestCache && c3po.requestCache[request])
						request = c3po.requestCache[request];
					else {
						request = new c3po.Request(request);
						if (c3po.requestCache)
							c3po.requestCache[request.original] = request;
					}
				}
				return request.exec(options, context);
			},
			getAll: function(requests, options, context) {
				return requests.map(function(request) {
					return c3po.get(request, options, context);
				});
			}
		};
		return c3po;
	});
})(typeof define !== 'undefined' ? define : function(deps, factory) { // AMD/RequireJS format if available
	if (typeof module !== 'undefined')
		module.exports = factory(); // CommonJS environment
	else if (typeof window !== 'undefined')
		window.c3po = factory(null); // raw script, assign to c3po global
	else
		console.warn('c3po has not been mounted somewhere.');
});
<|endoftext|>


<commit_before>import { PropTypes } from 'react';
import { requireNativeComponent, View } from 'react-native';

var iface = {
    name: 'PhotoView',
    propTypes: {
        src: PropTypes.string,
        ...View.propTypes // include the default view properties
    },
};

module.exports = requireNativeComponent('PhotoView', iface);<commit_msg>scaleType prop type added to index.js<commit_after>import { PropTypes } from 'react';
import { requireNativeComponent, View } from 'react-native';

var iface = {
    name: 'PhotoView',
    propTypes: {
        src: PropTypes.string,
	scaleType: PropTypes.string,
        ...View.propTypes // include the default view properties
    },
};

module.exports = requireNativeComponent('PhotoView', iface);
<|endoftext|>


<commit_before>module.exports = function (babel) {
  var t = babel.types;

  var path = require('path');

  function getImportPath(file, relativeImportPath) {
    var filename = file.opts.filename;
    var filePath = filename.replace(/[^\/]+$/, '');
    var result = path.join(filePath, relativeImportPath);
    return result;
  }

  function getImportModuleName(file, importPath) {
    var importedModulePath = getImportPath(file, importPath);

    // There should be a better way
    var importedModuleFile = t.cloneDeep(file);
    importedModuleFile.opts = t.cloneDeep(file.opts);
    importedModuleFile.opts.filename = importedModuleFile.opts.filenameRelative = importedModulePath + '.js';
    var UmdFormatter = file.moduleFormatter.constructor;
    var result = new UmdFormatter(importedModuleFile).getModuleName();
    return result;
  }

  function SystemImportExpressionTransformer(file, params) {
    this.file = file;
    var param = params[0];
    this.importedModuleLiteral = t.literal(param.node.value);

    var moduleName = getImportModuleName(this.file, this.importedModuleLiteral.value);
    this.moduleNameLiteral = t.literal(moduleName);
  }

  SystemImportExpressionTransformer.prototype.getGlobalIdentifier = function () {
    if (this.globalIdentifier) {
      return this.globalIdentifier;
    }
    this.globalIdentifier = t.identifier('global');
    return this.globalIdentifier;
  };

  SystemImportExpressionTransformer.prototype.getGlobalVarDeclaration = function () {
    if (this.globalVarDeclaration) {
      return this.globalVarDeclaration;
    }
    this.globalVarDeclaration = t.variableDeclaration('var', [t.variableDeclarator(this.getGlobalIdentifier(), t.identifier('window'))]);
    return this.globalVarDeclaration;
  };

  SystemImportExpressionTransformer.prototype.getAmdTest = function () {
    var globalIdentifier = this.getGlobalIdentifier();
    // typeof global.define === 'function' && global.define.amd
    var amdTest = t.logicalExpression('&&',
      t.binaryExpression('===',
        t.unaryExpression('typeof', t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        )),
        t.literal('function')
      ),
      t.memberExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        ),
        t.identifier('amd')
      )
    );
    return amdTest;
  };

  SystemImportExpressionTransformer.prototype.getAmdRequire = function (module) {
    var globalIdentifier = this.getGlobalIdentifier();
    // global.require(['localforageSerializer'], resolve, reject);
    var amdRequire = t.expressionStatement(
      t.callExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('require')
        ),
        [
          t.arrayExpression([module]),
          t.identifier('resolve'),
          t.identifier('reject')
        ]
      )
    );
    return amdRequire;
  };

  SystemImportExpressionTransformer.prototype.getCommonJSTest = function () {
    // typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'
    var commonJSTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('exports')
        ),
        t.binaryExpression('!==',
          t.unaryExpression('typeof', t.identifier('require')),
          t.literal('undefined')
        )
      )
    );
    return commonJSTest;
  };

  SystemImportExpressionTransformer.prototype.getComponentTest = function () {
    var globalIdentifier = this.getGlobalIdentifier();
    // typeof module !== 'undefined' && module.component && global.require && global.require.loader === 'component'
    var componentTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('component')
        ),
        t.logicalExpression('&&',
          t.memberExpression(
            globalIdentifier,
            t.identifier('require')
          ),
          t.binaryExpression('===',
            t.memberExpression(
              t.memberExpression(
                globalIdentifier,
                t.identifier('require')
              ),
              t.identifier('loader')
            ),
            t.literal('component')
          )
        )
      )
    );
    return componentTest;
  };

  SystemImportExpressionTransformer.prototype.getCommonJSRequire = function (module) {
    // resolve(require('./../utils/serializer'));
    var commonJSRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [
          t.callExpression(
            t.identifier('require'),
            [module]
          )
        ]
      )
    );
    return commonJSRequire;
  };

  SystemImportExpressionTransformer.prototype.getGlobalRequire = function (module) {
    var globalIdentifier = this.getGlobalIdentifier();
    // resolve(global.localforageSerializer);
    var globalMemberExpression = t.memberExpression(
      globalIdentifier,
      module
    );
    globalMemberExpression.computed = true;
    var globalRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [globalMemberExpression]
      )
    );
    return globalRequire;
  };

  SystemImportExpressionTransformer.prototype.createTransformedExpression = function () {
    var globalVarDeclaration = this.getGlobalVarDeclaration();

    var amdTest = this.getAmdTest();

    var amdRequire = this.getAmdRequire(this.moduleNameLiteral);

    var commonJSTest = this.getCommonJSTest();

    var componentTest = this.getComponentTest();

    var commonJSRequire = this.getCommonJSRequire(this.importedModuleLiteral);

    var globalRequire = this.getGlobalRequire(this.moduleNameLiteral);

    var commonJSOrComponentTest = t.logicalExpression('||', commonJSTest, componentTest);

    var moduleImportExpressions;
    if (this.file.opts.modules === 'amd') {
      moduleImportExpressions = [globalVarDeclaration, amdRequire];
    } else if (this.file.opts.modules === 'common') {
      moduleImportExpressions = [commonJSRequire];
    } else {
      var umdRequire = t.ifStatement(amdTest,
        t.blockStatement([amdRequire]),
        t.ifStatement(commonJSOrComponentTest,
          t.blockStatement([commonJSRequire]),
          t.blockStatement([globalRequire])
        )
      );
      moduleImportExpressions = [globalVarDeclaration, umdRequire];
    }

    var newPromiseExpression = t.newExpression(t.identifier('Promise'), [
      t.functionExpression(null,
        [t.identifier('resolve'), t.identifier('reject')],
        t.blockStatement(moduleImportExpressions)
      )
    ]);
    return newPromiseExpression;
  };

  return new babel.Transformer('system-import-transformer', {
    CallExpression: function (node, parent, scope, file) {
      if (this.get('callee').matchesPattern('System.import')) {
        var params = this.get('arguments');
        if (params.length && params[0].isLiteral()) {
          var transformer = new SystemImportExpressionTransformer(file, params);
          var transformedExpression = transformer.createTransformedExpression();
          if (transformedExpression) {
            return t.expressionStatement(transformedExpression);
          }
        }
      }
    }
  });
};
<commit_msg>feat: add support for environments without the window object<commit_after>module.exports = function (babel) {
  var t = babel.types;

  var path = require('path');

  function getImportPath(file, relativeImportPath) {
    var filename = file.opts.filename;
    var filePath = filename.replace(/[^\/]+$/, '');
    var result = path.join(filePath, relativeImportPath);
    return result;
  }

  function getImportModuleName(file, importPath) {
    var importedModulePath = getImportPath(file, importPath);

    // There should be a better way
    var importedModuleFile = t.cloneDeep(file);
    importedModuleFile.opts = t.cloneDeep(file.opts);
    importedModuleFile.opts.filename = importedModuleFile.opts.filenameRelative = importedModulePath + '.js';
    var UmdFormatter = file.moduleFormatter.constructor;
    var result = new UmdFormatter(importedModuleFile).getModuleName();
    return result;
  }

  function SystemImportExpressionTransformer(file, params) {
    this.file = file;
    var param = params[0];
    this.importedModuleLiteral = t.literal(param.node.value);

    var moduleName = getImportModuleName(this.file, this.importedModuleLiteral.value);
    this.moduleNameLiteral = t.literal(moduleName);
  }

  SystemImportExpressionTransformer.prototype.getGlobalIdentifier = function () {
    if (this.globalIdentifier) {
      return this.globalIdentifier;
    }

    var name = 'system-import-transformer-global-identifier';
    var ref = t.conditionalExpression(
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('window')),
        t.literal('undefined')
      ),
      t.identifier('window'),
      t.identifier('self')
    );
    this.globalIdentifier = this.getOrCreateHelper(name, ref);
    return this.globalIdentifier;
  };

  SystemImportExpressionTransformer.prototype.getOrCreateHelper = function (name, ref) {
    var declar = this.file.declarations[name];
    if (declar) {
      return declar;
    }

    var uid = this.file.declarations[name] = this.file.scope.generateUidIdentifier(name);
    this.file.usedHelpers[name] = true;

    if (t.isFunctionExpression(ref) && !ref.id) {
        ref.body._compact = true;
        ref._generated = true;
        ref.id = uid;
        ref.type = "FunctionDeclaration";
        this.file.attachAuxiliaryComment(ref);
        this.file.path.unshiftContainer("body", ref);
    } else {
        ref._compact = true;
        this.file.scope.push({
            id: uid,
            init: ref,
            unique: true
        });
    }

    return uid;
  };

  SystemImportExpressionTransformer.prototype.getAmdTest = function () {
    var globalIdentifier = this.getGlobalIdentifier();
    // typeof global.define === 'function' && global.define.amd
    var amdTest = t.logicalExpression('&&',
      t.binaryExpression('===',
        t.unaryExpression('typeof', t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        )),
        t.literal('function')
      ),
      t.memberExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('define')
        ),
        t.identifier('amd')
      )
    );
    return amdTest;
  };

  SystemImportExpressionTransformer.prototype.getAmdRequire = function (module) {
    var globalIdentifier = this.getGlobalIdentifier();
    // global.require(['localforageSerializer'], resolve, reject);
    var amdRequire = t.expressionStatement(
      t.callExpression(
        t.memberExpression(
          globalIdentifier,
          t.identifier('require')
        ),
        [
          t.arrayExpression([module]),
          t.identifier('resolve'),
          t.identifier('reject')
        ]
      )
    );
    return amdRequire;
  };

  SystemImportExpressionTransformer.prototype.getCommonJSTest = function () {
    // typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'
    var commonJSTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('exports')
        ),
        t.binaryExpression('!==',
          t.unaryExpression('typeof', t.identifier('require')),
          t.literal('undefined')
        )
      )
    );
    return commonJSTest;
  };

  SystemImportExpressionTransformer.prototype.getComponentTest = function () {
    var globalIdentifier = this.getGlobalIdentifier();
    // typeof module !== 'undefined' && module.component && global.require && global.require.loader === 'component'
    var componentTest = t.logicalExpression('&&',
      t.binaryExpression('!==',
        t.unaryExpression('typeof', t.identifier('module')),
        t.literal('undefined')
      ),
      t.logicalExpression('&&',
        t.memberExpression(
          t.identifier('module'),
          t.identifier('component')
        ),
        t.logicalExpression('&&',
          t.memberExpression(
            globalIdentifier,
            t.identifier('require')
          ),
          t.binaryExpression('===',
            t.memberExpression(
              t.memberExpression(
                globalIdentifier,
                t.identifier('require')
              ),
              t.identifier('loader')
            ),
            t.literal('component')
          )
        )
      )
    );
    return componentTest;
  };

  SystemImportExpressionTransformer.prototype.getCommonJSRequire = function (module) {
    // resolve(require('./../utils/serializer'));
    var commonJSRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [
          t.callExpression(
            t.identifier('require'),
            [module]
          )
        ]
      )
    );
    return commonJSRequire;
  };

  SystemImportExpressionTransformer.prototype.getGlobalRequire = function (module) {
    var globalIdentifier = this.getGlobalIdentifier();
    // resolve(global.localforageSerializer);
    var globalMemberExpression = t.memberExpression(
      globalIdentifier,
      module
    );
    globalMemberExpression.computed = true;
    var globalRequire = t.expressionStatement(
      t.callExpression(
        t.identifier('resolve'), [globalMemberExpression]
      )
    );
    return globalRequire;
  };

  SystemImportExpressionTransformer.prototype.createTransformedExpression = function () {
    var amdTest = this.getAmdTest();

    var amdRequire = this.getAmdRequire(this.moduleNameLiteral);

    var commonJSTest = this.getCommonJSTest();

    var componentTest = this.getComponentTest();

    var commonJSRequire = this.getCommonJSRequire(this.importedModuleLiteral);

    var globalRequire = this.getGlobalRequire(this.moduleNameLiteral);

    var commonJSOrComponentTest = t.logicalExpression('||', commonJSTest, componentTest);

    var moduleImportExpressions;
    if (this.file.opts.modules === 'amd') {
      moduleImportExpressions = [amdRequire];
    } else if (this.file.opts.modules === 'common') {
      moduleImportExpressions = [commonJSRequire];
    } else {
      var umdRequire = t.ifStatement(amdTest,
        t.blockStatement([amdRequire]),
        t.ifStatement(commonJSOrComponentTest,
          t.blockStatement([commonJSRequire]),
          t.blockStatement([globalRequire])
        )
      );
      moduleImportExpressions = [umdRequire];
    }

    var newPromiseExpression = t.newExpression(t.identifier('Promise'), [
      t.functionExpression(null,
        [t.identifier('resolve'), t.identifier('reject')],
        t.blockStatement(moduleImportExpressions)
      )
    ]);
    return newPromiseExpression;
  };

  return new babel.Transformer('system-import-transformer', {
    CallExpression: function (node, parent, scope, file) {
      if (this.get('callee').matchesPattern('System.import')) {
        var params = this.get('arguments');
        if (params.length && params[0].isLiteral()) {
          var transformer = new SystemImportExpressionTransformer(file, params);
          var transformedExpression = transformer.createTransformedExpression();
          if (transformedExpression) {
            return t.expressionStatement(transformedExpression);
          }
        }
      }
    }
  });
};
<|endoftext|>


<commit_before>
<commit_msg>Compile for dist<commit_after>module.exports = require("./lib/injector_wrapper").injector;
<|endoftext|>


<commit_before>const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const webpack = require('webpack');
const makeConfig = require('./webpack');

function makeDefaultConfig(cwd) {
	const f = path.join(cwd, 'webpack.config.js');
	const t = fs.statSync(f);
	return t.isFile ? require(f) : makeConfig();
}

function start(opts) {
	const options = opts || {};
	const port = options.port || process.env.PORT || 8000;
	const cwd = options.cwd || process.cwd();
	const config = options.webpack || makeDefaultConfig(cwd);

	const app = express();
	const compiler = webpack(config);

	app.use(morgan('dev'));
	app.use(cors());
	app.use(helmet());

	app.use(cookieParser);

	// parse application/x-www-form-urlencoded
	app.use(bodyParser.urlencoded({ extended: false }));

	// parse application/json
	app.use(bodyParser.json());

	function logErrors(err, req, res, next) {
		if (err) {
			console.error(err.stack);
		}
		next(err);
	}
	app.use(logErrors);

	app.use(require('webpack-dev-middleware')(compiler, {
		noInfo: true,
		publicPath: config.output.publicPath,
		stats: 'errors-only',
	}));

	app.use(require('webpack-hot-middleware')(compiler));

	if (_.isFunction(options.extendApp)) {
		options.extendApp(app);
	}

	if (_.isFunction(options.api)) {
		app.use(options.api());
	} else if (_.isObject(options.api)) {
		app.use(options.api);
	}

	app.use(express.static(cwd));

	// otherwise return index.html
	app.get('/*', (req, res) => {
		res.sendFile(path.join(cwd, 'index.html'));
	});

	app.use((err, req, res, next) => { // eslint-disable-line
		if (err) {
			console.log(err);
			res.status(500).send('bad code path');
		}
	});

	app.listen(port, '0.0.0.0', (err) => {
		if (err) {
			console.log(err);
			return;
		}

		console.log('Listening at http://0.0.0.0:%s', port);
	});
}

module.exports = {
	startServer: start,
	makeWebpackConfig: makeConfig,
};
<commit_msg>fix cookierParser<commit_after>const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const helmet = require('helmet');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const webpack = require('webpack');
const makeConfig = require('./webpack');

function makeDefaultConfig(cwd) {
	const f = path.join(cwd, 'webpack.config.js');
	const t = fs.statSync(f);
	return t.isFile ? require(f) : makeConfig();
}

function start(opts) {
	const options = opts || {};
	const port = options.port || process.env.PORT || 8000;
	const cwd = options.cwd || process.cwd();
	const config = options.webpack || makeDefaultConfig(cwd);

	const app = express();
	const compiler = webpack(config);

	app.use(morgan('dev'));
	app.use(cors());
	app.use(helmet());

	app.use(cookieParser());

	// parse application/x-www-form-urlencoded
	app.use(bodyParser.urlencoded({ extended: false }));

	// parse application/json
	app.use(bodyParser.json());

	function logErrors(err, req, res, next) {
		if (err) {
			console.error(err.stack);
		}
		next(err);
	}
	app.use(logErrors);

	app.use(require('webpack-dev-middleware')(compiler, {
		noInfo: true,
		publicPath: config.output.publicPath,
		stats: 'errors-only',
	}));

	app.use(require('webpack-hot-middleware')(compiler));

	if (_.isFunction(options.extendApp)) {
		options.extendApp(app);
	}

	if (_.isFunction(options.api)) {
		app.use(options.api());
	} else if (_.isObject(options.api)) {
		app.use(options.api);
	}

	app.use(express.static(cwd));

	// otherwise return index.html
	app.get('/*', (req, res) => {
		res.sendFile(path.join(cwd, 'index.html'));
	});

	app.use((err, req, res, next) => { // eslint-disable-line
		if (err) {
			console.log(err);
			res.status(500).send('bad code path');
		}
	});

	app.listen(port, '0.0.0.0', (err) => {
		if (err) {
			console.log(err);
			return;
		}

		console.log('Listening at http://0.0.0.0:%s', port);
	});
}

module.exports = {
	startServer: start,
	makeWebpackConfig: makeConfig,
};
<|endoftext|>


<commit_before>"use strict";
var express = require("express");
var app = express();
var io = require('socket.io')(server);
var server = require('http').Server(app);
var bodyParser = require('body-parser');
var _ = require('lodash');

var spaceMan = require("./lib/spaceManager.js");
var DeviceOrchestrator = require('./lib/DeviceOrchestrator');

var api = require("./routes/api");
var deviceViews = require('./routes/devices');

var spaceManOne = new spaceMan(200);

server.listen(8080);
app.use(express.static('public'));
app.set('view engine', 'jade');

app.get('/', function (req, res) {
  res.render('index');
});

// Mounting sub route trees
app.use('/api', require('./routes/api'));
app.use('/devices', require('./routes/devices'));

var doc = new DeviceOrchestrator({io});

var sense = require('./lib/signals/sensor');
var term = require('./lib/signals/terminal');

doc.sequence('entrance')
  .addRelay(sense.entrance, term.entranceTerm)
  .done();

devoc.listen();

console.log("Listening on port: 8080");
<commit_msg>adding more about sequences<commit_after>"use strict";
var express = require("express");
var app = express();
var io = require('socket.io')(server);
var server = require('http').Server(app);
var bodyParser = require('body-parser');
var _ = require('lodash');

var spaceMan = require("./lib/spaceManager.js");
var DeviceOrchestrator = require('./lib/DeviceOrchestrator');

var api = require("./routes/api");
var deviceViews = require('./routes/devices');

var spaceManOne = new spaceMan(200);

server.listen(8080);
app.use(express.static('public'));
app.set('view engine', 'jade');

app.get('/', function (req, res) {
  res.render('index');
});

// Mounting sub route trees
app.use('/api', require('./routes/api'));
app.use('/devices', require('./routes/devices'));

var doc = new DeviceOrchestrator({io});

// the templates for the signals should be stored in the signals subdirectory
// These are not simplemented
var sense = require('./lib/signals/sensor');
var term = require('./lib/signals/terminal');
var gate = require('./lib/signals/gate')

// This should be the entrance sequence
doc.sequence('entrance')
  .addRelay(sense.entrance.hi, term.qr.display)
  .addRelay(term.qr.payload, gate.entranceGate.open)
  .addRelay(gate.entranceGate.opened, DeviceOrchestrator.noReponse)
  .addRelay([sense.entranceAG.hi, sense.entranceAG.low], gate.entranceGate.close)
  .addRelay(gate.entranceGate.closed, DeviceOrchestrator.complete);

devoc.listen([
  'entrance',
  'parking',
  'exit'
]); // this call invokes the io.on('connection') function

console.log("Listening on port: 8080");
<|endoftext|>


<commit_before>"use strict";
var fs = require("fs");

var status = 500;
var toobusy = false;
var stopping = false;

function setStatus(code) {
	if (!Number.isInteger(code) || code < 1 || code > 999) {
		var e = new Error("status should be an integer between 1 and 999");
		e.status = code;
		throw e;
	}
	status = code;
}

function getStatus() {
	return status;
}

/**
 * returns 503 if server is toobusy, status (as defined by setStatus) otherwise.
 */
function route(req, res) {
	if (toobusy && toobusy()) {
		res.sendStatus(503).end();
	} else {
		res.sendStatus(status).end();
	}
}

/**
 * adds a `Connection: close` to all responses if app.get('stopping') is true.
 */
function gracefulShutdownKeepaliveConnections(req, res, next) {
	if (stopping === true) {
		res.set("Connection", "close");
	}
	next();
}

function enableTooBusy(lag) {
	if (typeof lag === "undefined") {
		lag = 70;
	}
	if (!Number.isInteger(lag) || lag < 10) {
		var e = new Error("lag should be an integer greater than 10");
		e.lag = lag;
		throw e;
	}
	toobusy = require("toobusy-js");
	toobusy.maxLag(lag);
}

/**
 * - logs shutdown to graylog (if log4js logger provided).
 * - sets `stopping` to true.
 * - dumps error in terminationFile if provided.
 */
function shutdown(signal, error, cb, terminationFile, logger) {
	status = 503;
	var reason;
	if (error) {
		if (logger && logger.fatal) {
			let uError = {};
			const errorKeys = Object.keys(error);
			for (let index = 0; index < errorKeys.length; index++) {
				const key = errorKeys[index];
				uError[`_${key}`] = error[key];
			}
			logger.fatal(
				{ GELF: true, _signal: signal, _stack: error.stack, ...uError },
				error.message
			);
		}
		reason = `${signal}\n${error.message}\n${error.stack}`;
	} else {
		if (logger && logger.info) {
			logger.info({ GELF: true, _signal: signal }, "shutdown");
		}
		reason = shutdown;
	}
	if (stopping === true) {
		return;
	}
	stopping = true;

	function callback() {
		if (cb) {
			return cb(signal ? 1 : 0);
		}
	}

	if (terminationFile) {
		fs.writeFile(terminationFile, reason, function (err) {
			if (err) {
				console.error(err);
			}
			callback();
		});
	} else {
		callback();
	}
}

module.exports = {
	setStatus: setStatus,
	getStatus: getStatus,
	route: route,
	shutdown: shutdown,
	enableTooBusy: enableTooBusy,
	gracefulShutdownKeepaliveConnections: gracefulShutdownKeepaliveConnections,
};
<commit_msg>set reason to shutdown when not defined<commit_after>"use strict";
var fs = require("fs");

var status = 500;
var toobusy = false;
var stopping = false;

function setStatus(code) {
	if (!Number.isInteger(code) || code < 1 || code > 999) {
		var e = new Error("status should be an integer between 1 and 999");
		e.status = code;
		throw e;
	}
	status = code;
}

function getStatus() {
	return status;
}

/**
 * returns 503 if server is toobusy, status (as defined by setStatus) otherwise.
 */
function route(req, res) {
	if (toobusy && toobusy()) {
		res.sendStatus(503).end();
	} else {
		res.sendStatus(status).end();
	}
}

/**
 * adds a `Connection: close` to all responses if app.get('stopping') is true.
 */
function gracefulShutdownKeepaliveConnections(req, res, next) {
	if (stopping === true) {
		res.set("Connection", "close");
	}
	next();
}

function enableTooBusy(lag) {
	if (typeof lag === "undefined") {
		lag = 70;
	}
	if (!Number.isInteger(lag) || lag < 10) {
		var e = new Error("lag should be an integer greater than 10");
		e.lag = lag;
		throw e;
	}
	toobusy = require("toobusy-js");
	toobusy.maxLag(lag);
}

/**
 * - logs shutdown to graylog (if log4js logger provided).
 * - sets `stopping` to true.
 * - dumps error in terminationFile if provided.
 */
function shutdown(signal, error, cb, terminationFile, logger) {
	status = 503;
	var reason;
	if (error) {
		if (logger && logger.fatal) {
			let uError = {};
			const errorKeys = Object.keys(error);
			for (let index = 0; index < errorKeys.length; index++) {
				const key = errorKeys[index];
				uError[`_${key}`] = error[key];
			}
			logger.fatal(
				{ GELF: true, _signal: signal, _stack: error.stack, ...uError },
				error.message
			);
		}
		reason = `${signal}\n${error.message}\n${error.stack}`;
	} else {
		if (logger && logger.info) {
			logger.info({ GELF: true, _signal: signal }, "shutdown");
		}
		reason = "shutdown";
	}
	if (stopping === true) {
		return;
	}
	stopping = true;

	function callback() {
		if (cb) {
			return cb(signal ? 1 : 0);
		}
	}

	if (terminationFile) {
		fs.writeFile(terminationFile, reason, function (err) {
			if (err) {
				console.error(err);
			}
			callback();
		});
	} else {
		callback();
	}
}

module.exports = {
	setStatus: setStatus,
	getStatus: getStatus,
	route: route,
	shutdown: shutdown,
	enableTooBusy: enableTooBusy,
	gracefulShutdownKeepaliveConnections: gracefulShutdownKeepaliveConnections,
};
<|endoftext|>


<commit_before>'use strict';

/**
 *
 * The ESLint rules below are listed in the order they appear on the
 * ESLint rule page (http://eslint.org/docs/rules/). All rules that
 * appear on the page are listed below as it will be easier to keep
 * in sync when new rules are added or old rules removed.
 *
 */

module.exports = {

  "rules": {

    /**
     * Possible Errors
     * http://eslint.org/docs/rules/#possible-errors
     */
    "no-await-in-loop": "off",                                                    // http://eslint.org/docs/rules/no-await-in-loop
    "no-cond-assign": ["error", "always"],                                        // http://eslint.org/docs/rules/no-cond-assign
    "no-console": "warn",                                                         // http://eslint.org/docs/rules/no-console
    "no-constant-condition": "warn",                                              // http://eslint.org/docs/rules/no-constant-condition
    "no-control-regex": "off",                                                    // http://eslint.org/docs/rules/no-control-regex
    "no-debugger": "warn",                                                        // http://eslint.org/docs/rules/no-debugger

    /**
     * Best Practices
     * http://eslint.org/docs/rules/#best-practices
     */
    "accessor-pairs": "off",                                                      // http://eslint.org/docs/rules/accessor-pairs

    /**
     * Strict Mode
     * http://eslint.org/docs/rules/#strict-mode
     */
    "strict": "off",                                                              // http://eslint.org/docs/rules/strict

    /**
     * Variables
     * http://eslint.org/docs/rules/#variables
     */
    // "init-declarations":                                                       // http://eslint.org/docs/rules/init-declarations

    /**
     * Node.js and CommonJS
     * http://eslint.org/docs/rules/#nodejs-and-commonjs
     */

    /**
     * Stylistic Issues
     * http://eslint.org/docs/rules/#stylistic-issues
     */
    "array-bracket-spacing": ["error", "never"],                                  // http://eslint.org/docs/rules/array-bracket-spacing

    /**
     * ECMAScript 6
     * http://eslint.org/docs/rules/#ecmascript-6
     */
    "arrow-body-style": ["error", "as-needed"]                                   // http://eslint.org/docs/rules/arrow-body-style

  }

};
<commit_msg>Adding in rules for Variables<commit_after>'use strict';

/**
 *
 * The ESLint rules below are listed in the order they appear on the
 * ESLint rule page (http://eslint.org/docs/rules/). All rules that
 * appear on the page are listed below as it will be easier to keep
 * in sync when new rules are added or old rules removed.
 *
 */

module.exports = {

  "rules": {

    /**
     * Possible Errors
     * http://eslint.org/docs/rules/#possible-errors
     */
    "no-await-in-loop": "off",                                                    // http://eslint.org/docs/rules/no-await-in-loop
    "no-cond-assign": ["error", "always"],                                        // http://eslint.org/docs/rules/no-cond-assign
    "no-console": "warn",                                                         // http://eslint.org/docs/rules/no-console
    "no-constant-condition": "warn",                                              // http://eslint.org/docs/rules/no-constant-condition
    "no-control-regex": "off",                                                    // http://eslint.org/docs/rules/no-control-regex
    "no-debugger": "warn",                                                        // http://eslint.org/docs/rules/no-debugger

    /**
     * Best Practices
     * http://eslint.org/docs/rules/#best-practices
     */
    "accessor-pairs": "off",                                                      // http://eslint.org/docs/rules/accessor-pairs

    /**
     * Strict Mode
     * http://eslint.org/docs/rules/#strict-mode
     */
    "strict": "off",                                                              // http://eslint.org/docs/rules/strict

    /**
     * Variables
     * http://eslint.org/docs/rules/#variables
     */
    "init-declarations": "off",                                                   // http://eslint.org/docs/rules/init-declarations
    "no-catch-shadow": "off",                                                     // http://eslint.org/docs/rules/no-catch-shadow
    "no-delete-var": "error",                                                     // http://eslint.org/docs/rules/no-delete-var
    "no-label-var": "warning",                                                    // http://eslint.org/docs/rules/no-label-var
    "no-restricted-globals": "off",                                               // http://eslint.org/docs/rules/no-restricted-globals
    "no-shadow-restricted-names": "error",                                        // http://eslint.org/docs/rules/no-shadow-restricted-names
    "no-shadow": "error",                                                         // http://eslint.org/docs/rules/no-shadow
    "no-undef-init": "error",                                                     // http://eslint.org/docs/rules/no-undef-init
    "no-undef": "error",                                                          // http://eslint.org/docs/rules/no-undef
    "no-undefined": "error",                                                      // http://eslint.org/docs/rules/no-undefined
    "no-unused-vars": ["error", {
      "vars": "local",
      "args": "after-used"
    }],                                                                           // http://eslint.org/docs/rules/no-unused-vars
    "no-use-before-define": "error",                                              // http://eslint.org/docs/rules/no-use-before-define

    /**
     * Node.js and CommonJS
     * http://eslint.org/docs/rules/#nodejs-and-commonjs
     */

    /**
     * Stylistic Issues
     * http://eslint.org/docs/rules/#stylistic-issues
     */
    "array-bracket-spacing": ["error", "never"],                                  // http://eslint.org/docs/rules/array-bracket-spacing

    /**
     * ECMAScript 6
     * http://eslint.org/docs/rules/#ecmascript-6
     */
    "arrow-body-style": ["error", "as-needed"]                                   // http://eslint.org/docs/rules/arrow-body-style

  }

};
<|endoftext|>