<commit_before>var fs = require('fs'),
	path = require('path'),
	_ = require('lodash'),
	compile = require('node-tsc').compile;

var createTypeScriptPreprocessor = function(args, config, logger, helper) {
	config = config || {};

	var log = logger.create('preprocessor.typescript');
	var defaultOptions = {
		bare: true,
		sourceMap: false
	};

	var options = helper.merge(defaultOptions, args.options || {}, config.options || {});

	var transformPath = args.transformPath || config.transformPath || function(filepath) {
		return filepath.replace(/\.ts$/, '.js');
	};

	return function(content, file, done) {
		log.debug('preprocessing "%s".', file.originalPath);
		file.path = transformPath(file.originalPath);

		// Clone the options because tsc.compile could mutate them
		var opts = helper._.clone(options);

		try {
			tsc(file.originalPath, file.path, opts, function(error, output) {
				if (error) throw error;

				if (opts.sourceMap) {
					sourceMapAsDataUri(content, file, file.path + '.map', function(datauri) {
						fs.unlink(file.path + '.map');
						output = output.replace(/\/\/# sourceMappingURL=.+\.js\.map\r?\n?/i, '');
						output += '\n//@ sourceMappingURL=' + datauri + '\n';
						done(output);
					});
				} else {
					done(output);
				}

			}, log);
		} catch(e) {
			log.error('%s\n  at %s', e.message, file.originalPath);
			return;
		}
	};
};

function sourceMapAsDataUri(content, file, sourceMapPath, callback) {
	fs.readFile(sourceMapPath, 'utf8', function(error, text) {
		if (error) throw error;
		var map = JSON.parse(text);
		map.sources[0] = path.basename(file.originalPath);
		map.sourcesContent = [content];
		map.file = path.basename(file.path);
		callback('data:application/json;charset=utf-8;base64,' + new Buffer(JSON.stringify(map)).toString('base64'));
	});
}

function tsc(input, output, options, callback, log) {

	if (!output) {
		output = input.replace(/\.ts$/, '.js');
	}

	var args = _.clone(options);

	if (!('module' in args)) {
		args.out = output;
	}

	var opts = {files: [input], args: args};

	if (options.compiler) {
		delete args.compiler;
		opts.compiler = options.compiler;
	}

	compile(opts, function(err) {
		log.error(err);
	});

	log.debug('preprocessed');

	fs.readFile(output, 'utf8', function(error, content) {
		if (error) {
			callback(error);
			return;
		}
		fs.unlink(output);
		callback(null, content);
	});
}

createTypeScriptPreprocessor.$inject = ['args', 'config.typescriptPreprocessor', 'logger', 'helper'];

// PUBLISH DI MODULE
module.exports = {
	'preprocessor:typescript': ['factory', createTypeScriptPreprocessor]
};
<commit_msg>fix: chaining preprocessors<commit_after>var fs = require('fs'),
	path = require('path'),
	_ = require('lodash'),
	compile = require('node-tsc').compile;

var createTypeScriptPreprocessor = function(args, config, logger, helper) {
	config = config || {};

	var log = logger.create('preprocessor.typescript');
	var defaultOptions = {
		bare: true,
		sourceMap: false
	};

	var options = helper.merge(defaultOptions, args.options || {}, config.options || {});

	var transformPath = args.transformPath || config.transformPath || function(filepath) {
		return filepath.replace(/\.ts$/, '.js');
	};

	return function(content, file, done) {
		log.debug('preprocessing "%s".', file.originalPath);
		file.path = transformPath(file.originalPath);

		// Clone the options because tsc.compile could mutate them
		var opts = helper._.clone(options);

		try {
			tsc(file.originalPath, file.path, content, opts, function(error, output) {
				if (error) throw error;

				if (opts.sourceMap) {
					sourceMapAsDataUri(content, file, file.path + '.map', function(datauri) {
						fs.unlink(file.path + '.map');
						output = output.replace(/\/\/# sourceMappingURL=.+\.js\.map\r?\n?/i, '');
						output += '\n//@ sourceMappingURL=' + datauri + '\n';
						done(output);
					});
				} else {
					done(output);
				}

			}, log);
		} catch(e) {
			log.error('%s\n  at %s', e.message, file.originalPath);
			return;
		}
	};
};

function sourceMapAsDataUri(content, file, sourceMapPath, callback) {
	fs.readFile(sourceMapPath, 'utf8', function(error, text) {
		if (error) throw error;
		var map = JSON.parse(text);
		map.sources[0] = path.basename(file.originalPath);
		map.sourcesContent = [content];
		map.file = path.basename(file.path);
		callback('data:application/json;charset=utf-8;base64,' + new Buffer(JSON.stringify(map)).toString('base64'));
	});
}

function tsc(inPath, outPath, content, options, callback, log) {

	if (!outPath) {
		outPath = inPath.replace(/\.ts$/, '.js');
	}

	var args = _.clone(options);

	if (!('module' in args)) {
		args.out = outPath;
	}

	var tempInPath  = inPath + '.ktp.ts';
	var tempOutPath = inPath + '.ktp.js';
	var opts = {files: [tempInPath], args: args};

	fs.writeFileSync(tempInPath, content);

	if (options.compiler) {
		delete args.compiler;
		opts.compiler = options.compiler;
	}

	compile(opts, function(err) {
		log.error(err);
	});

	fs.unlinkSync(tempInPath);

	if (fs.existsSync(outPath)) {
		fs.unlinkSync(outPath);
	}

	log.debug('preprocessed');

	fs.readFile(tempOutPath, 'utf8', function(readErr, content) {
		if (readErr) {
			callback(readErr);
			return;
		}
		fs.unlinkSync(tempOutPath);
		callback(null, content);
	});
}

createTypeScriptPreprocessor.$inject = ['args', 'config.typescriptPreprocessor', 'logger', 'helper'];

// PUBLISH DI MODULE
module.exports = {
	'preprocessor:typescript': ['factory', createTypeScriptPreprocessor]
};
<|endoftext|>


<commit_before>/*!
 * verbalize <https://github.com/jonschlinkert/verbalize>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var EventLogger = require('./lib/event-logger');
var utils = require('./lib/utils');
var util = require('util');
var use = require('use');

/**
 * Expose `Verbalize`
 */

module.exports = Verbalize;

/**
 * Create an instance of `Verbalize` with the given `options`.
 *
 * ```js
 * var logger = new Verbalize({verbose: true});
 * ```
 * @param {Object} `options`
 * @api public
 */

function Verbalize(options) {
  if (!(this instanceof Verbalize)) {
    return new Verbalize(options);
  }
  // EventLogger.call(this);
  this.define('cache', {});
  this.options = options || {};
  this.verbose = {};
  use(this);
}

/**
 * Inherit EventLogger
 */

util.inherits(Verbalize, EventLogger);

/**
 * Base formatting.
 *
 * @return {String} `msg`
 * @api public
 */
function toArray(args) {
  if (typeof args === 'string') {
    args = [args];
  } if (!Array.isArray(args) && args.length) {
    args = [].slice.call(args);
  } else {
    args = [].concat.apply([].slice.call(arguments));
  }
  return args;
}

Verbalize.prototype._format = function(args) {
  args = toArray.apply(null, arguments);

  if (args.length > 0) {
    args[0] = String(args[0]);
  }
  return util.format.apply(util, args);
};

/**
 * Stylize the given `msg` with the specified `color`.
 *
 * @param {String} `color` The name of the color to use
 * @param {String} `msg` The args to stylize.
 * @return {String}
 */

Verbalize.prototype.stylize = function(color, args) {
  args = toArray(args);
  var len = args.length;
  var res = [];
  var idx = -1;

  var strip = this.options.stripColor === true;
  while (++idx < len) {
    var arg = args[idx];
    if (strip) {
      res.push(utils.stripColor(arg));
    } else {
      res.push(arg);
    }
  }
  return this.write.apply(this, res);
};

/**
 * Write to the console.
 *
 * @return {String} `msg`
 * @api public
 */

Verbalize.prototype._write = function(msg) {
  process.stdout.write(utils.markup(msg || ''));
  return this;
};

/**
 * Write to the console followed by a newline. A blank
 * line is returned if no value is passed.
 *
 * @return {String} `msg`
 * @api public
 */

Verbalize.prototype._writeln = function(msg) {
  return this._write((msg || '') + '\n');
};

/**
 * Write output.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.write = function() {
  return this._write(this._format(arguments));
};

/**
 * Write output followed by a newline.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.writeln = function() {
  return this._writeln(this._format(arguments));
};

/**
 * Style a basic separator.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.sep = function(str) {
  return this._sep || (this._sep = this.gray(str || ' · '));
};

/**
 * Log a message.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.log = function() {
  return this.stylize('white', arguments);
};

/**
 * Define non-enumerable property `key` with the given value.
 *
 * @param {String} `key`
 * @param {any} `value`
 * @return {String}
 * @api public
 */

Verbalize.prototype.define = function(key, value) {
  utils.define(this, key, value);
  return this;
};
<commit_msg>add `method` and `style` methods for setting up methods and styles on the logger. move `stylize` to `styles` plugin move `toArray` to utils add `component-emitter` to emit when methods are created<commit_after>/*!
 * verbalize <https://github.com/jonschlinkert/verbalize>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 */

'use strict';

var Emitter = require('component-emitter');
var utils = require('./lib/utils');
var util = require('util');
var use = require('use');

/**
 * Expose `Verbalize`
 */

module.exports = Verbalize;

/**
 * Create an instance of `Verbalize` with the given `options`.
 *
 * ```js
 * var logger = new Verbalize({verbose: true});
 * ```
 * @param {Object} `options`
 * @api public
 */

function Verbalize(options) {
  if (!(this instanceof Verbalize)) {
    return new Verbalize(options);
  }
  this.define('cache', {});
  this.define('stack', []);
  this.define('invoking', false);
  this.options = options || {};
  use(this);
}

/**
 * Mixin `Emitter` prototype methods
 */

Emitter(Verbalize.prototype);

Verbalize.prototype.method = function(name, fn) {
  utils.set(this.cache, ['methods', name], fn);
  this.addMethod(name, 'methods', function() {
    if (this.invoking) {
      return fn.apply(this, arguments);
    }
    return this.invoke(arguments);
  }.bind(this));
};

Verbalize.prototype.style = function(name, fn) {
  utils.set(this.cache, ['styles', name], fn);
  this.addMethod(name, 'styles', function() {
    if (this.invoking) {
      return fn.apply(this, arguments);
    }
    return this.invoke(arguments);
  }.bind(this));
};

Verbalize.prototype.addMethod = function(name, type, fn) {
  fn.__proto__ = this;
  this.define(name, {
    enumerable: true,
    configurable: true,
    get: function() {
      this.stack.push({
        type: type,
        name: name,
        fn: utils.get(this.cache, [type, name])
      });
      return fn;
    }
  });
  this.emit('addMethod', name);
};

Verbalize.prototype.invoke = function(args) {
  this.invoking = true;
  var context = {
    stack: this.stack,
    args: args,
    write: true
  };

  var len = this.stack.length, i = -1;
  var res = args[0];

  while(++i < len) {
    var ctx = this.stack[i];
    switch(ctx.type) {
      case 'styles':
        res = ctx.fn.call(this, res);
        break;

      case 'methods':
      default: {
        ctx.fn.call(this, context);
      }
    }
    if (context.write === false) break;
  }
  if (context.write) {
    this.writeln.apply(this, [res]);
  }
  this.stack = [];
  this.invoking = false;
  return this;
};

/**
 * Base formatting.
 *
 * @return {String} `msg`
 * @api public
 */

Verbalize.prototype._format = function(args) {
  args = utils.toArray.apply(null, arguments);

  if (args.length > 0) {
    args[0] = String(args[0]);
  }
  return util.format.apply(util, args);
};

/**
 * Write to the console.
 *
 * @return {String} `msg`
 * @api public
 */

Verbalize.prototype._write = function(msg) {
  process.stdout.write(utils.markup(msg || ''));
  return this;
};

/**
 * Write to the console followed by a newline. A blank
 * line is returned if no value is passed.
 *
 * @return {String} `msg`
 * @api public
 */

Verbalize.prototype._writeln = function(msg) {
  return this._write((msg || '') + '\n');
};

/**
 * Write output.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.write = function() {
  return this._write(this._format(arguments));
};

/**
 * Write output followed by a newline.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.writeln = function() {
  return this._writeln(this._format(arguments));
};

/**
 * Style a basic separator.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.sep = function(str) {
  return this._sep || (this._sep = this.gray(str || ' · '));
};

/**
 * Log a message.
 *
 * @return {String}
 * @api public
 */

Verbalize.prototype.log = function() {
  return this.stylize('white', arguments);
};

/**
 * Define non-enumerable property `key` with the given value.
 *
 * @param {String} `key`
 * @param {any} `value`
 * @return {String}
 * @api public
 */

Verbalize.prototype.define = function(key, value) {
  utils.define(this, key, value);
  return this;
};
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Small helper for checking if input is an Integer {number}.
 * @param {object} object to check
 * @see http://stackoverflow.com/a/14794066
 */
function isInt(object) {
  return !isNaN(object) && !isNaN(parseInt(object)) && parseInt(Number(object)) == object;
}

/**
 * DelegableProxy, multi-level deepened proxy.
 * If any of the underlying object is modified, the primary delegate is invoked.
 */

var DelegableProxy = function () {
  _createClass(DelegableProxy, null, [{
    key: 'wire',

    /**
     * @param {object} object An object to proxy add/mod/del via callback method.
     * @param {proxyCallback} delegate Callback which is invoked for some actions.
     * @param {boolean} shouldClone create a clean clone of the whole data structure
     */
    value: function wire(object, delegate, shouldClone) {
      if (object === null) {
        throw new Error('Why would one use Proxy with a null object?');
      } else {
        if (shouldClone) {
          var cloned = JSON.parse(JSON.stringify(object));
          return new DelegableProxy(cloned, delegate);
        }
        return new DelegableProxy(object, delegate);
      }
    }

    /**
     * Small helper function to decouple from the derived object.
     * @param {object} ref mother object to invoke {proxyCallback}
     * @param {object} obj to wire
     * @param {integer} index [-1]
     * @param {boolean} isRootObject whether the sender is the root object or not
     */

  }, {
    key: 'relax',
    value: function relax(ref, obj, index) {
      var delegate = function delegate(action, position) {
        ref.notifyDelegate(action, position, false);
      };
      return new DelegableProxy(obj, delegate, index);
    }
  }]);

  function DelegableProxy(object, delegate, index) {
    _classCallCheck(this, DelegableProxy);

    if (object === null) {
      throw new Error('Why would one use Proxy without a proper object to follow?');
    }
    if (typeof delegate !== 'function') {
      throw new Error('Why would one use Proxy without a proper delegate function?');
    }
    this.index = index !== undefined ? index : -1;
    this.delegate = delegate;
    this.handler = this.createHandler();
    this.wired = new WeakSet();
    this.ensureRecursiveWiring(object);
    return new Proxy(object, this.handler);
  }

  _createClass(DelegableProxy, [{
    key: 'createHandler',
    value: function createHandler() {
      var self = this;
      // return true to accept the changes
      return {
        deleteProperty: function deleteProperty(target, property) {
          self.notifyDelegate('del', self.formatProperty(property), true);
          return true;
        },
        set: function set(target, property, value, receiver) {
          var hasOldValue = target[property] !== undefined;
          // if key does not exist but value is an object, wrap it!
          if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
            target[property] = DelegableProxy.relax(self, value);
          } else {
            target[property] = value;
          }
          // array pushes always triggers this method twice
          if (property === 'length') {
            return true;
          }
          // object changes (for instance added new method) should not be delegated
          if (property === '__proto__') {
            return true;
          }
          // notify delegate
          var action = hasOldValue ? 'mod' : 'add';
          self.notifyDelegate(action, self.formatProperty(property), true);
          return true;
        }
      };
    }
  }, {
    key: 'ensureRecursiveWiring',
    value: function ensureRecursiveWiring(object) {
      if (this.wired.has(object)) {
        console.log(object, 'is already wired, no further traverse');
        return;
      }
      this.wired.add(object);
      // end condition
      var isObject = (typeof object === 'undefined' ? 'undefined' : _typeof(object)) !== 'object';
      if (isObject) {
        return;
      }
      // go deeper
      var self = this;
      var keys = Object.keys(object);
      keys.forEach(function (k) {
        var o = object[k];
        // not eligible for Proxy
        if ((typeof o === 'undefined' ? 'undefined' : _typeof(o)) !== 'object') {
          return;
        }
        // if key is numeric, pass the current index for locating the root object later on
        if (isInt(k)) {
          var i = keys.indexOf(k);
          object[k] = DelegableProxy.relax(self, o, i);
          return;
        }
        object[k] = DelegableProxy.relax(self, o);
      });
    }

    /**
     * As we only want to track indices of an array and not keys, short check.
     * @param {object} property
     * @returns -1 or index
     */

  }, {
    key: 'formatProperty',
    value: function formatProperty(property) {
      if (!isInt(property)) {
        return -1;
      }
      return parseInt(property);
    }

    /**
     * Callback which is invoked for each add/mode/del.
     *
     * @callback proxyCallback
     * @param {string} action may be one of {add, del, mod}.
     * @param {number} position resultant, this is currently the index of the root object, which was altered.
     * @param {boolean} isRootObject whether the sender is the root object or not
     */

  }, {
    key: 'notifyDelegate',
    value: function notifyDelegate(action, position, isRootObject) {
      if (!isRootObject) {
        action = 'mod';
      }
      if (this.index < 0) {
        return this.delegate(action, position, isRootObject);
      }
      return this.delegate(action, this.index, isRootObject);
    }
  }]);

  return DelegableProxy;
}();

exports.default = DelegableProxy;
<commit_msg>Removed build version<commit_after><|endoftext|>


<commit_before>// Determines if the current browser is Internet Explorer.
module.exports = /*@cc_on!@*/false
<commit_msg>d3plus.client.ie now detects IE11+<commit_after>// Determines if the current browser is Internet Explorer.
module.exports = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);
<|endoftext|>


<commit_before>'use strict';
const electron = require('electron');
const app = electron.app;
const AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
const P = require('bluebird');
const _ = require('lodash');

//var ipcMain = P.promisifyAll(require('electron').ipcMain);

var ec2 = P.promisifyAll(new AWS.EC2());
console.log('ec2');

const ipcMain = require('electron').ipcMain;

var template = {
	"AWSTemplateFormatVersion" : "version date",
	"Description" : "",
	"Metadata" : {},
	"Parameters" : {},
	"Mappings" : {},
	"Conditions" : {},
	"Resources" : {},
	"Outputs" : {}
};

function populateBlock(block, body) {
	block.Properties = _.reduce(block.Properties, function(result, n, key) {
		result[key] = body[key];
		return result;
	}, {});
	return block;
}

function recursiveReplace(object, newPattern, oldPattern) {
	_.forIn(object, function (val, key) {
		console.log('Recursive Run');
		if(val === oldPattern) {
			console.log('Replacing at ' + val);
			object[key] = newPattern
		}
		//console.log(key);
		if (_.isArray(val)) {
			console.log('Recursing on an array ' + val);
			val.forEach(function(el) {
				if (_.isObject(el)) {
					recursiveReplace(el, newPattern, oldPattern);
				}
			});
		}
		if (_.isObject(object[key])) {
			console.log('Recursing on an object ' + key);
			recursiveReplace(object[key], newPattern, oldPattern);
		}
	});
}

function addResource(resource) {
	console.log('block');
	console.log('Recursive rename');
	recursiveReplace(template.Resources, '{ Ref: ' + resource.name + ' }', resource.id);
	//console.log(resource.block);
	template.Resources[resource.name] = populateBlock(resource.block, resource.body);
}

function removeResource(resource) {
	console.log('block');
	console.log(resource.block);
	recursiveReplace(template.Resources, resource.id, '{ Ref: ' + resource.name + ' }');
	delete template.Resources[resource.name];
}

ipcMain.on('get-resource-request', function(event, arg) {
	console.log('Got resource request');
	console.log(arg);
	var params = {};
	switch(arg) {
		case "AWS::EC2::VPC":
			params = { call: ec2.describeVpcsAsync({}) };
			break;
		case "AWS::EC2::SUBNET":
			params = { call: ec2.describeSubnetsAsync({}) };
			break;
	};
	params
		.call
		.then(function(data) {
			console.log('Sending data');
			//console.log(data);
			data.type = arg;
			event.sender.send('get-resource-reply', data);
		})
		.catch(function(e) {
			console.log(e);
		});
});

ipcMain.on('get-template-request', function(event, arg) {
	console.log('Received get template request');
	event.sender.send('get-template-reply', template);
});

ipcMain.on('open-template-window', function(event) {
	console.log('Received request to open template window.');
	if(!templateWindow) {
		templateWindow = createTemplateWindow();
	}
});

ipcMain.on('add-to-template-request', function(event, res) {
	console.log('Added resource to template');
	console.log(res);
	addResource(res);
	event.sender.send('add-to-template-reply');
});

ipcMain.on('remove-from-template-request', function(event, res) {
	console.log('Removed resource from template');
	removeResource(res);
	event.sender.send('remove-from-template-reply');
});

// report crashes to the Electron project
require('crash-reporter').start();

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// prevent window being garbage collected
let mainWindow;
let templateWindow;

function onMainClosed() {
	mainWindow = null;
}

function onTemplateClosed() {
	templateWindow = null;
}

function createMainWindow() {
	const win = new electron.BrowserWindow({
		width: 1200,
		height: 800
	});

	win.loadURL(`file://${__dirname}/ui/index.html`);
	win.on('closed', onMainClosed, 'main');
	return win;
}

function createTemplateWindow() {
	const win = new electron.BrowserWindow({
		width: 1200,
		height: 800
	});

	win.loadURL(`file://${__dirname}/template/index.html`);
	win.on('closed', onTemplateClosed, 'template');
	return win;
}

app.on('window-all-closed', () => {
	app.quit();
});

app.on('activate-with-no-open-windows', () => {
	console.log('activate-with-no-open-windows');
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	console.log('Ready');
	mainWindow = createMainWindow();
});
<commit_msg>Improved replacement function.<commit_after>'use strict';
const electron = require('electron');
const app = electron.app;
const AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
const P = require('bluebird');
const _ = require('lodash');

//var ipcMain = P.promisifyAll(require('electron').ipcMain);

var ec2 = P.promisifyAll(new AWS.EC2());
console.log('ec2');

const ipcMain = require('electron').ipcMain;

var template = {
	"AWSTemplateFormatVersion" : "version date",
	"Description" : "",
	"Metadata" : {},
	"Parameters" : {},
	"Mappings" : {},
	"Conditions" : {},
	"Resources" : {},
	"Outputs" : {}
};

function populateBlock(block, body) {
	block.Properties = _.reduce(block.Properties, function(result, n, key) {
		result[key] = body[key];
		return result;
	}, {});
	return block;
}

function recursiveReplace(object, newPattern, oldPattern) {
	_.forIn(object, function (val, key) {
		console.log('Recursive Run');
		if(val === oldPattern) {
			console.log('Replacing at ' + val);
			object[key] = newPattern
		}
		//console.log(key);
		if (_.isArray(val)) {
			console.log('Recursing on an array ' + val);
			val.forEach(function(el) {
				if (_.isObject(el)) {
					recursiveReplace(el, newPattern, oldPattern);
				}
			});
		}
		if (_.isObject(object[key])) {
			console.log('Recursing on an object ' + key);
			recursiveReplace(object[key], newPattern, oldPattern);
		}
	});
}

function addResource(resource) {
	console.log('block');
	console.log('Recursive rename');
	recursiveReplace(template.Resources, '{ Ref: ' + resource.name + ' }', resource.id);
	//console.log(resource.block);
	var newResource = populateBlock(resource.block, resource.body);
	_.each(template.Resources, function(val, key) {
		console.log('Checking ' + key);
		console.log('Match: ' + key.replace('-resource',''));
		recursiveReplace(newResource, '{ Ref: ' + key + ' }', key.replace('-resource',''))
	});
	template.Resources[resource.name] = newResource;
}

function removeResource(resource) {
	console.log('block');
	console.log(resource.block);
	recursiveReplace(template.Resources, resource.id, '{ Ref: ' + resource.name + ' }');
	delete template.Resources[resource.name];
}

ipcMain.on('get-resource-request', function(event, arg) {
	console.log('Got resource request');
	console.log(arg);
	var params = {};
	switch(arg) {
		case "AWS::EC2::VPC":
			params = { call: ec2.describeVpcsAsync({}) };
			break;
		case "AWS::EC2::SUBNET":
			params = { call: ec2.describeSubnetsAsync({}) };
			break;
	};
	params
		.call
		.then(function(data) {
			console.log('Sending data');
			//console.log(data);
			data.type = arg;
			event.sender.send('get-resource-reply', data);
		})
		.catch(function(e) {
			console.log(e);
		});
});

ipcMain.on('get-template-request', function(event, arg) {
	console.log('Received get template request');
	event.sender.send('get-template-reply', template);
});

ipcMain.on('open-template-window', function(event) {
	console.log('Received request to open template window.');
	if(!templateWindow) {
		templateWindow = createTemplateWindow();
	}
});

ipcMain.on('add-to-template-request', function(event, res) {
	console.log('Added resource to template');
	console.log(res);
	addResource(res);
	event.sender.send('add-to-template-reply');
});

ipcMain.on('remove-from-template-request', function(event, res) {
	console.log('Removed resource from template');
	removeResource(res);
	event.sender.send('remove-from-template-reply');
});

// report crashes to the Electron project
require('crash-reporter').start();

// adds debug features like hotkeys for triggering dev tools and reload
require('electron-debug')();

// prevent window being garbage collected
let mainWindow;
let templateWindow;

function onMainClosed() {
	mainWindow = null;
}

function onTemplateClosed() {
	templateWindow = null;
}

function createMainWindow() {
	const win = new electron.BrowserWindow({
		width: 1200,
		height: 800
	});

	win.loadURL(`file://${__dirname}/ui/index.html`);
	win.on('closed', onMainClosed, 'main');
	return win;
}

function createTemplateWindow() {
	const win = new electron.BrowserWindow({
		width: 1200,
		height: 800
	});

	win.loadURL(`file://${__dirname}/template/index.html`);
	win.on('closed', onTemplateClosed, 'template');
	return win;
}

app.on('window-all-closed', () => {
	app.quit();
});

app.on('activate-with-no-open-windows', () => {
	console.log('activate-with-no-open-windows');
	if (!mainWindow) {
		mainWindow = createMainWindow();
	}
});

app.on('ready', () => {
	console.log('Ready');
	mainWindow = createMainWindow();
});
<|endoftext|>


<commit_before>'use strict';
const {promisify} = require('util');
const fs = require('fs');
const path = require('path');
const replaceExt = require('replace-ext');
const PluginError = require('plugin-error');
const through = require('through2');

const readFile = promisify(fs.readFile);
const stat = promisify(fs.stat);

// Ignore missing file error
function fsOperationFailed(stream, sourceFile, error) {
	if (error.code !== 'ENOENT') {
		stream.emit('error', new PluginError('gulp-changed', error, {
			fileName: sourceFile.path
		}));
	}

	stream.push(sourceFile);
}

// Only push through files changed more recently than the destination files
async function compareLastModifiedTime(stream, sourceFile, targetPath) {
	// TODO: Use the `stat` `bigint` option when targeting Node.js 10 and Gulp supports it
	const targetStat = await stat(targetPath);

	if (sourceFile.stat && sourceFile.stat.mtimeMs > targetStat.mtimeMs) {
		stream.push(sourceFile);
	}
}

// Only push through files with different contents than the destination files
async function compareContents(stream, sourceFile, targetPath) {
	const targetData = await readFile(targetPath);

	if (sourceFile.isNull() || !sourceFile.contents.equals(targetData)) {
		stream.push(sourceFile);
	}
}

module.exports = (destination, options) => {
	options = {
		cwd: process.cwd(),
		hasChanged: compareLastModifiedTime,
		...options
	};

	if (!destination) {
		throw new PluginError('gulp-changed', '`dest` required');
	}

	if (options.transformPath !== undefined && typeof options.transformPath !== 'function') {
		throw new PluginError('gulp-changed', '`options.transformPath` needs to be a function');
	}

	return through.obj(function (file, encoding, callback) {
		const dest2 = typeof destination === 'function' ? destination(file) : destination;
		let newPath = path.resolve(options.cwd, dest2, file.relative);

		if (options.extension) {
			newPath = replaceExt(newPath, options.extension);
		}

		if (options.transformPath) {
			newPath = options.transformPath(newPath);

			if (typeof newPath !== 'string') {
				throw new PluginError('gulp-changed', '`options.transformPath` needs to return a string');
			}
		}

		(async () => {
			try {
				await options.hasChanged(this, file, newPath);
			} catch (error) {
				fsOperationFailed(this, file, error);
			}

			callback();
		})();
	});
};

module.exports.compareLastModifiedTime = compareLastModifiedTime;
module.exports.compareContents = compareContents;

<commit_msg>Fix `compareLastModifiedTime` for Gulp 4 (#78)<commit_after>'use strict';
const {promisify} = require('util');
const fs = require('fs');
const path = require('path');
const replaceExt = require('replace-ext');
const PluginError = require('plugin-error');
const through = require('through2');

const readFile = promisify(fs.readFile);
const stat = promisify(fs.stat);

// Ignore missing file error
function fsOperationFailed(stream, sourceFile, error) {
	if (error.code !== 'ENOENT') {
		stream.emit('error', new PluginError('gulp-changed', error, {
			fileName: sourceFile.path
		}));
	}

	stream.push(sourceFile);
}

// Only push through files changed more recently than the destination files
async function compareLastModifiedTime(stream, sourceFile, targetPath) {
	// TODO: Use the `stat` `bigint` option when targeting Node.js 10 and Gulp supports it
	const targetStat = await stat(targetPath);

	if (sourceFile.stat && Math.floor(sourceFile.stat.mtimeMs) > Math.floor(targetStat.mtimeMs)) {
		stream.push(sourceFile);
	}
}

// Only push through files with different contents than the destination files
async function compareContents(stream, sourceFile, targetPath) {
	const targetData = await readFile(targetPath);

	if (sourceFile.isNull() || !sourceFile.contents.equals(targetData)) {
		stream.push(sourceFile);
	}
}

module.exports = (destination, options) => {
	options = {
		cwd: process.cwd(),
		hasChanged: compareLastModifiedTime,
		...options
	};

	if (!destination) {
		throw new PluginError('gulp-changed', '`dest` required');
	}

	if (options.transformPath !== undefined && typeof options.transformPath !== 'function') {
		throw new PluginError('gulp-changed', '`options.transformPath` needs to be a function');
	}

	return through.obj(function (file, encoding, callback) {
		const dest2 = typeof destination === 'function' ? destination(file) : destination;
		let newPath = path.resolve(options.cwd, dest2, file.relative);

		if (options.extension) {
			newPath = replaceExt(newPath, options.extension);
		}

		if (options.transformPath) {
			newPath = options.transformPath(newPath);

			if (typeof newPath !== 'string') {
				throw new PluginError('gulp-changed', '`options.transformPath` needs to return a string');
			}
		}

		(async () => {
			try {
				await options.hasChanged(this, file, newPath);
			} catch (error) {
				fsOperationFailed(this, file, error);
			}

			callback();
		})();
	});
};

module.exports.compareLastModifiedTime = compareLastModifiedTime;
module.exports.compareContents = compareContents;

<|endoftext|>


<commit_before>const browser = typeof window === 'object';

function noop () {
  // poop
}

function hrtime () {
  return browser ? performance.now() : new Date().getTime();
}

module.exports = function (func, opts = {}) {
  let elapsed = 0
  let runs = 0;

  after = opts.after || noop;
  before = opts.before || noop;
  time = opts.time || 1000;

  while (elapsed < time) {
    const arg = before() || [];
    const now = hrtime();
    func.apply(null, arg);
    elapsed += hrtime() - now;
    after();
    ++runs;
  }

  return Promise.resolve(runs / (time / 1000));
};
<commit_msg>fix: fix undefined errors that weren't happening in node for some reason<commit_after>const browser = typeof window === 'object';

function noop () {
  // poop
}

function hrtime () {
  return browser ? performance.now() : new Date().getTime();
}

module.exports = function (func, opts = {}) {
  let elapsed = 0
  let runs = 0;

  const after = opts.after || noop;
  const before = opts.before || noop;
  const time = opts.time || 1000;

  while (elapsed < time) {
    const arg = before() || [];
    const now = hrtime();
    func.apply(null, arg);
    elapsed += hrtime() - now;
    after();
    ++runs;
  }

  return Promise.resolve(runs / (time / 1000));
};
<|endoftext|>


<commit_before>//  Imports
var express = require('express')
var db = require('mongodb')
var passport = require('passport')
var Strategy = require('passport-local').Strategy
var connectEnsure = require('connect-ensure-login')
//  Passport setup
passport.use(new Strategy(
  function(username, password, cb) {
    db.users.findByUsername(username, function(err, user) {
      if (err) { return cb(err) }
      if (!user) { return cb(null, false) }
      if (user.password != password) { return cb(null, false) }
      return cb(null, user)
    })
  }
))

passport.serializeUser(function(user, cb) {
  cb(null, user.id)
})

passport.deserializeUser(function(id, cb) {
  db.users.findById(id, function (err, user) {
    if (err) { return cb(err) }
    cb(null, user)
  })
})

var app = express()

app.use('/pdf', express.static(__dirname + '/node_modules/pdfmake/build'))
app.use(express.static('public'))
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs')

app.use(require('express-session')({
  secret: 'Brother, May I have some oats?',
  resave: false,
  saveUninitialized: false }
))

app.use(passport.initialize())
app.use(passport.session())

app.get('/',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    res.render('index')
})

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

app.post('/login',
  passport.authenticate(
    'local',
    {
      successReturnToOrRedirect: '/',
      failureRedirect: '/login'
    }
  )
)

app.get('/addPal',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    res.render('addPal')
  }
)

app.post('/addPal',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    //TODO
  }
)

app.get('/getPal',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    //TODO
  }
)

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res) {
  res.status(404).send('uh')
})

const PORT = 8080
app.listen(PORT, function () {
  console.log('Web Services App listening on port ' + PORT)
})
<commit_msg>mongo suff<commit_after>//  Imports
var express = require('express')
var MongoClient = require('mongodb').MongoClient
var passport = require('passport')
var Strategy = require('passport-local').Strategy
var connectEnsure = require('connect-ensure-login')
//  Passport setup
passport.use(new Strategy(
  function(username, password, cb) {
    db.users.findByUsername(username, function(err, user) {
      if (err) { return cb(err) }
      if (!user) { return cb(null, false) }
      if (user.password != password) { return cb(null, false) }
      return cb(null, user)
    })
  }
))

passport.serializeUser(function(user, cb) {
  cb(null, user.id)
})

passport.deserializeUser(function(id, cb) {
  db.users.findById(id, function (err, user) {
    if (err) { return cb(err) }
    cb(null, user)
  })
})

// Connection URL
var dbURL = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(dbURL, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");
  //db.close();
});

var app = express()

app.use('/pdf', express.static(__dirname + '/node_modules/pdfmake/build'))
app.use(express.static('public'))
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs')

app.use(require('express-session')({
  secret: 'Brother, May I have some oats?',
  resave: false,
  saveUninitialized: false }
))

app.use(passport.initialize())
app.use(passport.session())

app.get('/',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    res.render('index')
})

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

app.post('/login',
  passport.authenticate(
    'local',
    {
      successReturnToOrRedirect: '/',
      failureRedirect: '/login'
    }
  )
)

app.get('/addPal',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    res.render('addPal')
  }
)

app.post('/addPal',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    //TODO
  }
)

app.get('/getPal',
  //connectEnsure.ensureLoggedIn('/login'),
  function(req, res) {
    //TODO
  }
)

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res) {
  res.status(404).send('uh')
})

const PORT = 8080
app.listen(PORT, function () {
  console.log('Web Services App listening on port ' + PORT)
})
<|endoftext|>


<commit_before>/**
  * The seeder interface provides the ability to handle all operations, that
  * are not DDL specific and thus not a migration.
  *
  * These operations are currently, but not limited to:
  *
  * inserting data
  * removing data
  * searching data
  * truncating whole tables
  *
  * This functionality is provided in two ways to the user. First there are
  * traditional seeder. You can call them whenever you want, and how often
  * you want. This results into a use case, that make seeders might only used
  * for development and not to use them in a deployment process.
  *
  * Here the second way of usage steps in, the version controlled seeders, in
  * short VC Seeds.
  * There is technically no big difference between them, except the following
  * details:
  *
  * A VC Seed can be called from a migration, via seed.execute and seed.link. A
  * normal seeder can not. Also A VC Seeder has a down and up function, like
  * the way the migrations work, the static instead has a truncate function,
  * which gets called before the seed function. As a seeder often wants to
  * truncate tables or just delete data from a table.
  * And last but not least, a VC Seed can not be executed if it was executed
  * before, you need to roll back it first, it's in short handled like
  * migrations are. A normal seed can be executed just as often as you want
  * without rollback your data at any time.
  *
  * To note: If you rollback a migration, linked to a seeder, db-migrate will
  * also rollback the seed. This is also a reason why you can't rollback a
  * specific migration, you would going to break that much, you probably loose
  * a bunch of valueable time.
  */

var Promise = require('bluebird');

function _l( field ) {

  return { type: 'lookup', field: field };
}

function insert(table, options, callback) {

  var foreignLinkage = this.foreignLinkage[table];

  for(var o = 0; o < options.length; ++o)
  {
    var option = Object.keys(options[o]);

    for(var i = 0; i < option.length; ++i) {

      if (typeof(options[option[i]]) === 'object') {

        if (options[option[i]].type === 'lookup') {

          if (!options[option[i]].table) {

            if (foreignLinkage[option[i]]) {

              options[option[i]].table = foreignLinkage[option[i]].table;
              options[option[i]].field = foreignLinkage[option[i]].field;
            }
            else {

              return Promise.reject('missing foreign key linkage!').
                nodeify(callback);
            }
          }
        }
      }
    }
  }

  return lookup(options)
  .then(function(){

    return this.driver.insert(options);
  })
  .catch(function(e) {

    throw e;
  })
  .nodeify(callback);
}

function lookup(options) {

  var lookups = [],
      i = 0;

  for(var o = 0; o < options.length; ++o)
  {
    var option = Object.keys(options[o]);

    for(; i < option.length; ++i) {

      if (typeof(options[option]) === 'object') {

        if (options[option].type === 'lookup') {

          lookups.push(this.driver.lookup(options[option])
          .catch(function(err) {

            throw err;
          }));
        }
      }
    }
  }

  return Promise.settle(lookups);
}

var SeederInterface = {

    lookup: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    insert: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    delete: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    runSql: function() {

        arguments[arguments.length - 1]('not implemented');
    },
};

module.exports = SeederInterface;
module.exports.deprecated = {

};
module.exports.extending = {

    _l: function( field ) {

        return { type: 'lookup', field: field };
    }
};
<commit_msg>add needed functions to seeder interface<commit_after>/**
  * The seeder interface provides the ability to handle all operations, that
  * are not DDL specific and thus not a migration.
  *
  * These operations are currently, but not limited to:
  *
  * inserting data
  * removing data
  * searching data
  * truncating whole tables
  *
  * This functionality is provided in two ways to the user. First there are
  * traditional seeder. You can call them whenever you want, and how often
  * you want. This results into a use case, that make seeders might only used
  * for development and not to use them in a deployment process.
  *
  * Here the second way of usage steps in, the version controlled seeders, in
  * short VC Seeds.
  * There is technically no big difference between them, except the following
  * details:
  *
  * A VC Seed can be called from a migration, via seed.execute and seed.link. A
  * normal seeder can not. Also A VC Seeder has a down and up function, like
  * the way the migrations work, the static instead has a truncate function,
  * which gets called before the seed function. As a seeder often wants to
  * truncate tables or just delete data from a table.
  * And last but not least, a VC Seed can not be executed if it was executed
  * before, you need to roll back it first, it's in short handled like
  * migrations are. A normal seed can be executed just as often as you want
  * without rollback your data at any time.
  *
  * To note: If you rollback a migration, linked to a seeder, db-migrate will
  * also rollback the seed. This is also a reason why you can't rollback a
  * specific migration, you would going to break that much, you probably loose
  * a bunch of valueable time.
  */

var Promise = require('bluebird');

function _l( field ) {

  return { type: 'lookup', field: field };
}

function insert(table, options, callback) {

  var foreignLinkage = this.foreignLinkage[table];

  for(var o = 0; o < options.length; ++o)
  {
    var option = Object.keys(options[o]);

    for(var i = 0; i < option.length; ++i) {

      if (typeof(options[option[i]]) === 'object') {

        if (options[option[i]].type === 'lookup') {

          if (!options[option[i]].table) {

            if (foreignLinkage[option[i]]) {

              options[option[i]].table = foreignLinkage[option[i]].table;
              options[option[i]].field = foreignLinkage[option[i]].field;
            }
            else {

              return Promise.reject('missing foreign key linkage!').
                nodeify(callback);
            }
          }
        }
      }
    }
  }

  return lookup(options)
  .then(function(){

    return this.driver.insert(options);
  })
  .catch(function(e) {

    throw e;
  })
  .nodeify(callback);
}

function lookup(options) {

  var lookups = [],
      i = 0;

  for(var o = 0; o < options.length; ++o)
  {
    var option = Object.keys(options[o]);

    for(; i < option.length; ++i) {

      if (typeof(options[option]) === 'object') {

        if (options[option].type === 'lookup') {

          lookups.push(this.driver.lookup(options[option])
          .catch(function(err) {

            throw err;
          }));
        }
      }
    }
  }

  return Promise.settle(lookups);
}

var SeederInterface = {

    lookup: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    insert: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    delete: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    runSql: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    buildWhereClause: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    quoteDDLArr: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    quoteArr: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    escapeString: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    escape: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    escapeDDL: function() {

        arguments[arguments.length - 1]('not implemented');
    },

    checkDBMS: function() {

        arguments[arguments.length - 1]('not implemented');
    }

};

module.exports = SeederInterface;
module.exports.deprecated = {

};
module.exports.extending = {

    _l: function( field ) {

        return { type: 'lookup', field: field };
    }
};
<|endoftext|>


<commit_before>var phantom = require('phantom')
  , http = require('http');

phantom.create(function(phantom) {
    http.createServer(function (req, res) {
        if(req.url == '/favicon.ico' || req.url == '/') return;
        console.log('getting', req.url);
        phantom.createPage(function(page) {
            page.open(req.url.substr(1), function (status) {
                if ('fail' === status) {
                    res.writeHead(404);
                    res.end();
                } else {
                    setTimeout(function(){
                        page.evaluate(function () {
                            return document && document.getElementsByTagName('html')[0].innerHTML
                        }, function(documentHTML) {
                            var matches = documentHTML.match(/<script(?:.*?)>(?:.*?)<\/script>/g);

                            for( var i = 0; i < matches.length; i++) {
                                documentHTML = documentHTML.replace(matches[i], '');
                            }
                            res.writeHead(200, {'Content-Type': 'text/html'});
                            res.end(documentHTML);
                        });
                    }, 50);
                };
            });
        });
    }).listen(3000);
    console.log('Server running on port 3000');
});<commit_msg>adding port from env<commit_after>var phantom = require('phantom')
  , http = require('http');

phantom.create(function(phantom) {
    http.createServer(function (req, res) {
        if(req.url == '/favicon.ico' || req.url == '/') return;
        console.log('getting', req.url);
        phantom.createPage(function(page) {
            page.open(req.url.substr(1), function (status) {
                if ('fail' === status) {
                    res.writeHead(404);
                    res.end();
                } else {
                    setTimeout(function(){
                        page.evaluate(function () {
                            return document && document.getElementsByTagName('html')[0].innerHTML
                        }, function(documentHTML) {
                            var matches = documentHTML.match(/<script(?:.*?)>(?:.*?)<\/script>/g);

                            for( var i = 0; i < matches.length; i++) {
                                documentHTML = documentHTML.replace(matches[i], '');
                            }
                            res.writeHead(200, {'Content-Type': 'text/html'});
                            res.end(documentHTML);
                        });
                    }, 50);
                };
            });
        });
    }).listen(process.env.PORT || 3000);
    console.log('Server running on port ' + (process.env.PORT || 3000));
});<|endoftext|>


<commit_before>/**
 * coverage-code-regex <https://github.com/regexps/coverage-code-regex>
 *
 * Copyright (c) 2014-2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

module.exports = function coverageCodeRegex() {
  return /(?:__cov_(?:[\w\W\S.,$]{1,22})\.(?:.{1})\[\'(?:\d{1,})\'\]\+\+\;)/;
};
<commit_msg>update regex<commit_after>/**
 * coverage-code-regex <https://github.com/regexps/coverage-code-regex>
 *
 * Copyright (c) 2014-2015 Charlike Mike Reagent, contributors.
 * Released under the MIT license.
 */

'use strict';

module.exports = function coverageCodeRegex() {
  // e.g. __cov_abc.s['12'][0][2][1]
  return /(?:__cov_(?:[\w\W\S.,$]{1,22})\.(?:.{1})\[\'(?:\d{1,})\'\](?:\[(?:\d{1,})\])*?\+\+\;)/;
};
<|endoftext|>


<commit_before>'use strict';

//
// NOTE: It is usable but not finished yet.
// TODO: Remove code duplication
//

var assert = require('assert');
var util = require('util');

function makeReport(path, explanation) {
  var prefix     = '',
      parameters = [ explanation ],
      index,
      length     = path.length;

  if (arguments.length > 2) {
    parameters.concat(Array.prototype.slice.call(arguments, 2));
  }

  if (length > 0) {
    prefix += 'At object';

    for (index = 0; index < length; index += 1) {
      prefix += '[' + JSON.stringify(path[index]) + ']';
    }

    prefix += ': ';
  }

  return prefix + util.format.apply(parameters);
}

function ensureEqualValues(path, actual, expected) {
  var actualKind   = Object.prototype.toString.call(actual),
      expectedKind = Object.prototype.toString.call(expected);

  assert.strictEqual(actualKind, expectedKind,
    makeReport(path, 'Objects must be of same type'));

  if (actual === expected) {
    return;

  } else if (Number.isNaN(actual) && Number.isNaN(expected)) {
    return;

  } else {
    assert.strictEqual(
      Object.getPrototypeOf(actual),
      Object.getPrototypeOf(expected),
      makeReport(path, 'Objects has different prototypes'));

    if (actual instanceof Array &&
        expected instanceof Array) {
      ensureEqualArrays(path, actual, expected);

    } else if (actual instanceof Date &&
               expected instanceof Date) {
      ensureEqualDates(path, actual, expected);

    } else if (actual instanceof RegExp &&
               expected instanceof RegExp) {
      ensureEqualRegexps(path, actual, expected);

    } else {
      ensureEqualObjects(path, actual, expected);
    }
  }
}

function ensureEqualArrays(path, actual, expected) {
  var index, length;

  assert.strictEqual(actual.length, expected.length,
    makeReport(path, 'Arrays are not of same length'));

  for (index = 0, length = actual.length; index < length; index += 1) {
    ensureEqualValues(path.concat(index), actual[index], expected[index]);
  }
}

function ensureEqualDates(path, actual, expected) {
  var actualTime   = actual.getTime(),
      expectedTime = expected.getTime();

  assert.strictEqual(actualTime, expectedTime,
    makeReport(path,
      "Dates' timestamps are not equal (actual: %j, expected: %j)",
      actualTime,
      expectedTime));
}

function ensureEqualRegexps(path, actual, expected) {
  assert.strictEqual(actual.source, expected.source,
    makeReport(path,
      "Regexps' `source` properties are not equal (actual: %j, expected: %j)",
      actual.source,
      expected.source));

  assert.strictEqual(actual.lastIndex, expected.lastIndex,
    makeReport(path,
      "Regexps' `lastIndex` properties are not equal (actual: %j, expected: %j)",
      actual.lastIndex,
      expected.lastIndex));

  assert.strictEqual(actual.ignoreCase, expected.ignoreCase,
    makeReport(path,
      "Regexps' `ignoreCase` flags are not at same state (actual: %j, expected: %j)",
      actual.ignoreCase,
      expected.ignoreCase));

  assert.strictEqual(actual.global, expected.global,
    makeReport(path,
      "Regexps' `global` flags are not at same state (actual: %j, expected: %j)",
      actual.global,
      expected.global));

  assert.strictEqual(actual.multiline, expected.multiline,
    makeReport(path,
      "Regexps' `multiline` flags are not at same state (actual: %j, expected: %j)",
      actual.multiline,
      expected.multiline));
}

function ensureEqualObjects(path, actual, expected) {
  var actualKeys   = Object.keys(actual),
      expectedKeys = Object.keys(expected),
      index, length, key;

  assert.strictEqual(actualKeys.length, expectedKeys.length,
    makeReport(path, 'Objects has different numbers of own properies.'));

  actualKeys.sort();
  expectedKeys.sort();

  length = actualKeys.length;

  for (index = 0; index < length; index += 1) {
    assert.strictEqual(actualKeys[index], expectedKeys[index],
      makeReport(path, 'Objects has different sets of own properties.'));
  }

  for (index = 0; index < length; index += 1) {
    key = actualKeys[index];
    ensureEqualValues(path.concat(key), actual[key], expected[key]);
  }
}

function fullEqual(value1, value2) {
  assert.doesNotThrow(function () {
    ensureEqualValues([], value1, value2);
  });
}

function notFullEqual(value1, value2) {
  assert.throws(function () {
    ensureEqualValues([], value1, value2);
  });
}

module.exports.fullEqual    = fullEqual;
module.exports.notFullEqual = notFullEqual;
<commit_msg>Fix top-level asserts to expect corrent exceptions.<commit_after>'use strict';

//
// NOTE: It is usable but not finished yet.
// TODO: Remove code duplication
//

var assert = require('assert');
var util = require('util');

function makeReport(path, explanation) {
  var prefix     = '',
      parameters = [ explanation ],
      index,
      length     = path.length;

  if (arguments.length > 2) {
    parameters.concat(Array.prototype.slice.call(arguments, 2));
  }

  if (length > 0) {
    prefix += 'At object';

    for (index = 0; index < length; index += 1) {
      prefix += '[' + JSON.stringify(path[index]) + ']';
    }

    prefix += ': ';
  }

  return prefix + util.format.apply(parameters);
}

function ensureEqualValues(path, actual, expected) {
  var actualKind   = Object.prototype.toString.call(actual),
      expectedKind = Object.prototype.toString.call(expected);

  assert.strictEqual(actualKind, expectedKind,
    makeReport(path, 'Objects must be of same type'));

  if (actual === expected) {
    return;

  } else if (Number.isNaN(actual) && Number.isNaN(expected)) {
    return;

  } else {
    assert.strictEqual(
      Object.getPrototypeOf(actual),
      Object.getPrototypeOf(expected),
      makeReport(path, 'Objects has different prototypes'));

    if (actual instanceof Array &&
        expected instanceof Array) {
      ensureEqualArrays(path, actual, expected);

    } else if (actual instanceof Date &&
               expected instanceof Date) {
      ensureEqualDates(path, actual, expected);

    } else if (actual instanceof RegExp &&
               expected instanceof RegExp) {
      ensureEqualRegexps(path, actual, expected);

    } else {
      ensureEqualObjects(path, actual, expected);
    }
  }
}

function ensureEqualArrays(path, actual, expected) {
  var index, length;

  assert.strictEqual(actual.length, expected.length,
    makeReport(path, 'Arrays are not of same length'));

  for (index = 0, length = actual.length; index < length; index += 1) {
    ensureEqualValues(path.concat(index), actual[index], expected[index]);
  }
}

function ensureEqualDates(path, actual, expected) {
  var actualTime   = actual.getTime(),
      expectedTime = expected.getTime();

  assert.strictEqual(actualTime, expectedTime,
    makeReport(path,
      "Dates' timestamps are not equal (actual: %j, expected: %j)",
      actualTime,
      expectedTime));
}

function ensureEqualRegexps(path, actual, expected) {
  assert.strictEqual(actual.source, expected.source,
    makeReport(path,
      "Regexps' `source` properties are not equal (actual: %j, expected: %j)",
      actual.source,
      expected.source));

  assert.strictEqual(actual.lastIndex, expected.lastIndex,
    makeReport(path,
      "Regexps' `lastIndex` properties are not equal (actual: %j, expected: %j)",
      actual.lastIndex,
      expected.lastIndex));

  assert.strictEqual(actual.ignoreCase, expected.ignoreCase,
    makeReport(path,
      "Regexps' `ignoreCase` flags are not at same state (actual: %j, expected: %j)",
      actual.ignoreCase,
      expected.ignoreCase));

  assert.strictEqual(actual.global, expected.global,
    makeReport(path,
      "Regexps' `global` flags are not at same state (actual: %j, expected: %j)",
      actual.global,
      expected.global));

  assert.strictEqual(actual.multiline, expected.multiline,
    makeReport(path,
      "Regexps' `multiline` flags are not at same state (actual: %j, expected: %j)",
      actual.multiline,
      expected.multiline));
}

function ensureEqualObjects(path, actual, expected) {
  var actualKeys   = Object.keys(actual),
      expectedKeys = Object.keys(expected),
      index, length, key;

  assert.strictEqual(actualKeys.length, expectedKeys.length,
    makeReport(path, 'Objects has different numbers of own properies.'));

  actualKeys.sort();
  expectedKeys.sort();

  length = actualKeys.length;

  for (index = 0; index < length; index += 1) {
    assert.strictEqual(actualKeys[index], expectedKeys[index],
      makeReport(path, 'Objects has different sets of own properties.'));
  }

  for (index = 0; index < length; index += 1) {
    key = actualKeys[index];
    ensureEqualValues(path.concat(key), actual[key], expected[key]);
  }
}

function fullEqual(value1, value2) {
  assert.doesNotThrow(function () {
    ensureEqualValues([], value1, value2);
  }, assert.AssertionError);
}

function notFullEqual(value1, value2) {
  assert.throws(function () {
    ensureEqualValues([], value1, value2);
  }, assert.AssertionError);
}

module.exports.fullEqual    = fullEqual;
module.exports.notFullEqual = notFullEqual;
<|endoftext|>


<commit_before>var fs = require('fs'),
	path = require('path'),
	es = require('event-stream'),
	gutil = require('gulp-util'),
	glob = require('glob'),
	_ = require('lodash');

var DIRECTIVE_REGEX = /^[\/\s#]*?=\s*?((?:require|include|jshtml)(?:_tree|_directory)?)\s+(.*$)/mg;
var COMMENT_REGEX = /\s*([^\s=]+)\s*=/;
var EXTENSION = {
	jshtml: 'jshtml'
};

var requiredFiles = {},
	extensions = [],
	basePath = '',
	autoExtension = '',
	partialPrefix = '',
	fileProcess = '';

module.exports = function (params) {
	params = params || {};
	requiredFiles = {};
	extensions = [];
	basePath = '';
	autoExtension = '';
	partialPrefix = '';
	fileProcess = '';

	if (params.extensions) {
		extensions = typeof params.extensions === 'string' ? [params.extensions] : params.extensions;
	}
	if (params.basePath) {
		basePath = typeof params.basePath === 'string' ? path.normalize(process.cwd() + path.sep + params.basePath) : '';
	}
	if (params.autoExtension) {
		autoExtension = typeof params.autoExtension === 'boolean' ? params.autoExtension : false;
	}
	if (params.partialPrefix) {
		partialPrefix = typeof params.partialPrefix === 'boolean' ? params.partialPrefix : false;
	}
	if (params.fileProcess) {
		fileProcess = typeof params.fileProcess === 'function' ? params.fileProcess : undefined;
	}

	function include(file, callback) {
		if (file.isNull()) {
			return callback(null, file);
		}

		if (file.isStream()) {
			throw new gutil.PluginError('gulp-nwayo-include', 'stream not supported');
		}

		if (file.isBuffer()) {
			requiredFiles = {};
			var newText = expand(String(file.contents), file.path);
			file.contents = new Buffer(newText);
		}

		callback(null, file);
	}

	return es.map(include);
};

function expand(fileContents, filePath) {
	var regexMatch,
		matches = [],
		returnText = fileContents,
		delta = 0,
		i = 0, j, max;

	DIRECTIVE_REGEX.lastIndex = 0;

	while (regexMatch = DIRECTIVE_REGEX.exec(fileContents)) {
		matches.push(regexMatch);
	}

	max = matches.length;
	while (i++ < max) {
		var match = matches[i-1],
			original = match[0],
			directiveType = match[1],
			originalFilename = match[2],
			start = match.index + delta,
			end = start + original.length,
			comment = getCommentStyle(original),
			thisMatchText = "",
			newMatchText = "",
			files = globMatch(match, filePath),
			fileName = "",
			whitespace = null;

		if (directiveType.indexOf("_tree") !== -1 || directiveType.indexOf("_directory") !== -1) {
			thisMatchText += original + "\n";
		}

		for (j = 0; j < files.length; j++) {
			fileName = files[j];

			if ((directiveType.indexOf('require') !== -1 || directiveType.indexOf('jshtml') !== -1) && requiredFiles[fileName]) {
				newMatchText = comment + ' [gulp-nwayo-include] -- Skipping ' + originalFilename + ', already included.';
			} else {

				var fileContent = String(fs.readFileSync(fileName));

				if (fileProcess) {
					fileContent = fileProcess({
						fullPath: fileName,
						rawPath: fileName.substr(basePath.length),
						content: fileContent
					});
				}

				newMatchText = expand(fileContent, fileName);

				// jsrender template loading
				if (directiveType.indexOf('jshtml') !== -1) {
					var pathDirName = path.dirname(fileName);
					var pathSeparator = pathDirName.indexOf(path.sep) !== -1;
					var component = pathDirName.split(pathSeparator ? path.sep : '/').slice(-2,-1);
					var name = ( component + '_' + path.basename(fileName,'.'+EXTENSION.jshtml) ).replace(/-/g, '_').toLowerCase();

					// camel case the resulting name
					var camelCase = name.split('_');
					for (c = 0; c < camelCase.length; c++) {
						if (c !== 0) {
							camelCase[c] = camelCase[c].charAt(0).toUpperCase() + camelCase[c].substring(1);
						}
					}
					name = camelCase.join('');

					 // cleanup from https://github.com/alanshaw/grunt-template-client
					newMatchText = newMatchText.replace(/^\s+|\s+$|[\r\n]+/gm, '').replace(/'/g, "\\'");

					// write directive
					newMatchText = 'app.tmpl.' + name + ' = $.templates(\''+ name +'\', \'' + newMatchText + '\');';
				}
			}

		   //Try to retain the same indent level from the original include line
			whitespace = original.match(/^\s+/);
			if (whitespace) {
				//Discard newlines
				whitespace = whitespace[0].replace("\n", "");

				//Is there some whitespace left?
				if (whitespace) {
					newMatchText = addLeadingWhitespace(whitespace, newMatchText);
				}
			}

			thisMatchText += newMatchText + "\n";

			if (directiveType.indexOf('require') !== -1 || directiveType.indexOf('include') !== -1 || directiveType.indexOf('jshtml') !== -1) {
				requiredFiles[fileName] = true;
			}
		}

		thisMatchText = thisMatchText || original;

		returnText = replaceStringByIndices(returnText, start, end, thisMatchText);

		// push start to match new length
		delta += thisMatchText.length - original.length;
	}

	return returnText ? returnText : fileContents;
}

function globMatch(match, filePath) {
	var directiveType = match[1],
		relativeFilePath = match[2],
		files = [],
		globs = [],
		negations = [];

	if (directiveType.indexOf('_tree') !== -1) {
		relativeFilePath = relativeFilePath.concat('/**/*');
		directiveType = directiveType.replace('_tree', '');
	}

	if (directiveType.indexOf('_directory') !== -1) {
		relativeFilePath = relativeFilePath.concat('/*');
		directiveType = directiveType.replace('_directory', '');
	}

	if (directiveType === 'require' || directiveType === 'include' || directiveType === 'jshtml') {
		if (relativeFilePath.charAt(0) === '[') {
			relativeFilePath = eval(relativeFilePath);
			for (var i = 0; i < relativeFilePath.length; i++) {
				if (relativeFilePath[i].charAt(0) === '!') {
					negations.push(relativeFilePath[i].slice(1));
				} else {
					globs.push(relativeFilePath[i]);
				}
			}
		} else {
			globs.push(relativeFilePath);
		}

		var j;
		for (j = 0; j < globs.length; j++) {
			var globFiles = _internalGlob(globs[j], filePath, directiveType);
			files = union(files, globFiles);
		}

		for (j = 0; j < negations.length; j++) {
			var negationFiles = _internalGlob(negations[j].substring(1), filePath, directiveType);
			files = difference(files, negationFiles);
		}
	}

	return files;
}

function _internalGlob(thisGlob, filePath, directiveType) {
	var
		ext =
			(autoExtension) ?
				'.' + ( (EXTENSION[directiveType]) ?
					EXTENSION[directiveType] :
					 _.last(filePath.split('.'))
				) :
				'',
		folderPath = path.dirname(filePath),
		fullPath = path.join((basePath !== '') ? basePath : folderPath, thisGlob.replace(/['"]/g, '') + ext),
		files;

	files = glob.sync(fullPath, {
		mark: true
	});

	if (!files.length) {

		// Try a partial prefix
		if (partialPrefix) {
			var elements = fullPath.split('/');
			elements[elements.length-1] = '_'+elements[elements.length-1];
			var fullPath2 = elements.join('/');

			files = glob.sync(fullPath2, {
				mark: true
			});

			if (!files.length) {
				throw new gutil.PluginError('gulp-nwayo-include', 'File \''+fullPath+'\' not found');
			}

		} else {
			throw new gutil.PluginError('gulp-nwayo-include', 'File \''+fullPath+'\' not found');
		}
	}

	files = files.filter(function (fileName) {
		var slashSplit = fileName.split(/[\\\/]/),
			thisExtension = fileName.split('.').pop();

		//Ignore directories
		if (slashSplit.pop() === '')
			return false;

		//Check for allowable extensions if specified, otherwise allow all extensions
		if (extensions.length > 0 && extensions.indexOf(thisExtension) === -1) {
			return false;
		}

		return true;

	});

	return files;
}

function replaceStringByIndices(string, start, end, replacement) {
	return string.substring(0, start) + replacement + string.substring(end);
}

function addLeadingWhitespace(whitespace, string) {
	return string.split("\n").map(function(line) {
		return whitespace + line;
	}).join("\n");
}

function getCommentStyle(string) {
	var matches = COMMENT_REGEX.exec(string);
	return (matches) ? matches[1] : '';
}

//We can't use lo-dash's union function because it wouldn't support this: ["*.js", "app.js"], which requires app.js to come last
function union(arr1, arr2) {
	if (arr1.length === 0) {
		return arr2;
	}

	var index;
	for (var i = 0; i < arr2.length; i++) {
		if ((index = arr1.indexOf(arr2[i])) !== -1) {
			arr1.splice(index, 1);
		}
	}
	return arr1.concat(arr2);
}

function difference(arr1, arr2) {
	var index;
	for (var i = 0; i < arr2.length; i++) {
		while ((index = arr1.indexOf(arr2[i])) !== -1) {
			arr1.splice(index, 1);
		}
	}
	return arr1;
}

<commit_msg>Correction du partialPrefix sur Windows<commit_after>var fs = require('fs'),
	path = require('path'),
	es = require('event-stream'),
	gutil = require('gulp-util'),
	glob = require('glob'),
	_ = require('lodash');

var DIRECTIVE_REGEX = /^[\/\s#]*?=\s*?((?:require|include|jshtml)(?:_tree|_directory)?)\s+(.*$)/mg;
var COMMENT_REGEX = /\s*([^\s=]+)\s*=/;
var EXTENSION = {
	jshtml: 'jshtml'
};

var requiredFiles = {},
	extensions = [],
	basePath = '',
	autoExtension = '',
	partialPrefix = '',
	fileProcess = '';

module.exports = function (params) {
	params = params || {};
	requiredFiles = {};
	extensions = [];
	basePath = '';
	autoExtension = '';
	partialPrefix = '';
	fileProcess = '';

	if (params.extensions) {
		extensions = typeof params.extensions === 'string' ? [params.extensions] : params.extensions;
	}
	if (params.basePath) {
		basePath = typeof params.basePath === 'string' ? path.normalize(process.cwd() + path.sep + params.basePath) : '';
	}
	if (params.autoExtension) {
		autoExtension = typeof params.autoExtension === 'boolean' ? params.autoExtension : false;
	}
	if (params.partialPrefix) {
		partialPrefix = typeof params.partialPrefix === 'boolean' ? params.partialPrefix : false;
	}
	if (params.fileProcess) {
		fileProcess = typeof params.fileProcess === 'function' ? params.fileProcess : undefined;
	}

	function include(file, callback) {
		if (file.isNull()) {
			return callback(null, file);
		}

		if (file.isStream()) {
			throw new gutil.PluginError('gulp-nwayo-include', 'stream not supported');
		}

		if (file.isBuffer()) {
			requiredFiles = {};
			var newText = expand(String(file.contents), file.path);
			file.contents = new Buffer(newText);
		}

		callback(null, file);
	}

	return es.map(include);
};

function expand(fileContents, filePath) {
	var regexMatch,
		matches = [],
		returnText = fileContents,
		delta = 0,
		i = 0, j, max;

	DIRECTIVE_REGEX.lastIndex = 0;

	while (regexMatch = DIRECTIVE_REGEX.exec(fileContents)) {
		matches.push(regexMatch);
	}

	max = matches.length;
	while (i++ < max) {
		var match = matches[i-1],
			original = match[0],
			directiveType = match[1],
			originalFilename = match[2],
			start = match.index + delta,
			end = start + original.length,
			comment = getCommentStyle(original),
			thisMatchText = "",
			newMatchText = "",
			files = globMatch(match, filePath),
			fileName = "",
			whitespace = null;

		if (directiveType.indexOf("_tree") !== -1 || directiveType.indexOf("_directory") !== -1) {
			thisMatchText += original + "\n";
		}

		for (j = 0; j < files.length; j++) {
			fileName = files[j];

			if ((directiveType.indexOf('require') !== -1 || directiveType.indexOf('jshtml') !== -1) && requiredFiles[fileName]) {
				newMatchText = comment + ' [gulp-nwayo-include] -- Skipping ' + originalFilename + ', already included.';
			} else {

				var fileContent = String(fs.readFileSync(fileName));

				if (fileProcess) {
					fileContent = fileProcess({
						fullPath: fileName,
						rawPath: fileName.substr(basePath.length),
						content: fileContent
					});
				}

				newMatchText = expand(fileContent, fileName);

				// jsrender template loading
				if (directiveType.indexOf('jshtml') !== -1) {
					var pathDirName = path.dirname(fileName);
					var pathSeparator = pathDirName.indexOf(path.sep) !== -1;
					var component = pathDirName.split(pathSeparator ? path.sep : '/').slice(-2,-1);
					var name = ( component + '_' + path.basename(fileName,'.'+EXTENSION.jshtml) ).replace(/-/g, '_').toLowerCase();

					// camel case the resulting name
					var camelCase = name.split('_');
					for (c = 0; c < camelCase.length; c++) {
						if (c !== 0) {
							camelCase[c] = camelCase[c].charAt(0).toUpperCase() + camelCase[c].substring(1);
						}
					}
					name = camelCase.join('');

					 // cleanup from https://github.com/alanshaw/grunt-template-client
					newMatchText = newMatchText.replace(/^\s+|\s+$|[\r\n]+/gm, '').replace(/'/g, "\\'");

					// write directive
					newMatchText = 'app.tmpl.' + name + ' = $.templates(\''+ name +'\', \'' + newMatchText + '\');';
				}
			}

		   //Try to retain the same indent level from the original include line
			whitespace = original.match(/^\s+/);
			if (whitespace) {
				//Discard newlines
				whitespace = whitespace[0].replace("\n", "");

				//Is there some whitespace left?
				if (whitespace) {
					newMatchText = addLeadingWhitespace(whitespace, newMatchText);
				}
			}

			thisMatchText += newMatchText + "\n";

			if (directiveType.indexOf('require') !== -1 || directiveType.indexOf('include') !== -1 || directiveType.indexOf('jshtml') !== -1) {
				requiredFiles[fileName] = true;
			}
		}

		thisMatchText = thisMatchText || original;

		returnText = replaceStringByIndices(returnText, start, end, thisMatchText);

		// push start to match new length
		delta += thisMatchText.length - original.length;
	}

	return returnText ? returnText : fileContents;
}

function globMatch(match, filePath) {
	var directiveType = match[1],
		relativeFilePath = match[2],
		files = [],
		globs = [],
		negations = [];

	if (directiveType.indexOf('_tree') !== -1) {
		relativeFilePath = relativeFilePath.concat('/**/*');
		directiveType = directiveType.replace('_tree', '');
	}

	if (directiveType.indexOf('_directory') !== -1) {
		relativeFilePath = relativeFilePath.concat('/*');
		directiveType = directiveType.replace('_directory', '');
	}

	if (directiveType === 'require' || directiveType === 'include' || directiveType === 'jshtml') {
		if (relativeFilePath.charAt(0) === '[') {
			relativeFilePath = eval(relativeFilePath);
			for (var i = 0; i < relativeFilePath.length; i++) {
				if (relativeFilePath[i].charAt(0) === '!') {
					negations.push(relativeFilePath[i].slice(1));
				} else {
					globs.push(relativeFilePath[i]);
				}
			}
		} else {
			globs.push(relativeFilePath);
		}

		var j;
		for (j = 0; j < globs.length; j++) {
			var globFiles = _internalGlob(globs[j], filePath, directiveType);
			files = union(files, globFiles);
		}

		for (j = 0; j < negations.length; j++) {
			var negationFiles = _internalGlob(negations[j].substring(1), filePath, directiveType);
			files = difference(files, negationFiles);
		}
	}

	return files;
}

function _internalGlob(thisGlob, filePath, directiveType) {
	var
		ext =
			(autoExtension) ?
				'.' + ( (EXTENSION[directiveType]) ?
					EXTENSION[directiveType] :
					 _.last(filePath.split('.'))
				) :
				'',
		folderPath = path.dirname(filePath),
		fullPath = path.join((basePath !== '') ? basePath : folderPath, thisGlob.replace(/['"]/g, '') + ext),
		files;

	files = glob.sync(fullPath, {
		mark: true
	});

	if (!files.length) {

		// Try a partial prefix
		if (partialPrefix) {
			var pathSeparator = (fullPath.indexOf(path.sep) !== -1) ? path.sep : '/';
			var elements = fullPath.split(pathSeparator);
			elements[elements.length-1] = '_'+elements[elements.length-1];
			var fullPath2 = elements.join(pathSeparator);

			files = glob.sync(fullPath2, {
				mark: true
			});

			if (!files.length) {
				throw new gutil.PluginError('gulp-nwayo-include', 'File \''+fullPath+'\' not found');
			}

		} else {
			throw new gutil.PluginError('gulp-nwayo-include', 'File \''+fullPath+'\' not found');
		}
	}

	files = files.filter(function (fileName) {
		var slashSplit = fileName.split(/[\\\/]/),
			thisExtension = fileName.split('.').pop();

		//Ignore directories
		if (slashSplit.pop() === '')
			return false;

		//Check for allowable extensions if specified, otherwise allow all extensions
		if (extensions.length > 0 && extensions.indexOf(thisExtension) === -1) {
			return false;
		}

		return true;

	});

	return files;
}

function replaceStringByIndices(string, start, end, replacement) {
	return string.substring(0, start) + replacement + string.substring(end);
}

function addLeadingWhitespace(whitespace, string) {
	return string.split("\n").map(function(line) {
		return whitespace + line;
	}).join("\n");
}

function getCommentStyle(string) {
	var matches = COMMENT_REGEX.exec(string);
	return (matches) ? matches[1] : '';
}

//We can't use lo-dash's union function because it wouldn't support this: ["*.js", "app.js"], which requires app.js to come last
function union(arr1, arr2) {
	if (arr1.length === 0) {
		return arr2;
	}

	var index;
	for (var i = 0; i < arr2.length; i++) {
		if ((index = arr1.indexOf(arr2[i])) !== -1) {
			arr1.splice(index, 1);
		}
	}
	return arr1.concat(arr2);
}

function difference(arr1, arr2) {
	var index;
	for (var i = 0; i < arr2.length; i++) {
		while ((index = arr1.indexOf(arr2[i])) !== -1) {
			arr1.splice(index, 1);
		}
	}
	return arr1;
}

<|endoftext|>


<commit_before>'use strict'

const resolveBirthDate = require('birthdate-from-id')
const capitalize = require('capitalize')
const resolveFullName = require('./lib/resolve-full-name')

module.exports = (dsf) => {
  if (!dsf) {
    throw new Error('Missing required input: dsf object')
  }

  let contact = {}

  contact.personalIdNumber = dsf.FODT.toString() + dsf.PERS.toString()
  contact.birthDate = resolveBirthDate(`${dsf.FODT}${dsf.PERS}`)
  contact.firstName = capitalize.words(dsf['NAVN-F'].toLowerCase())
  contact.middleName = dsf['NAVN-M'] && dsf['NAVN-M'].length > 0 ? capitalize.words(dsf['NAVN-M'].toLowerCase()) : ''
  contact.lastName = capitalize.words(dsf['NAVN-S'].toLowerCase())
  contact.fullName = resolveFullName(contact.firstName, contact.middleName, contact.lastName)
  contact.address = capitalize.words(dsf.ADR ? dsf.ADR.toLowerCase() : '')
  contact.zip = dsf.POSTN || ''
  contact.city = capitalize.words(dsf.POSTS ? dsf.POSTS.toLowerCase() : '')
  contact.gender = dsf.KJONN ? (dsf.KJONN === 'M' ? 'Male' : 'Female') : ''
  contact.alive = dsf.STAT ? (dsf.STAT !== 'DØD') : ''
  contact.motherIdNumber = dsf['MOR-FODT'] ? (dsf['MOR-FODT'].toString() + dsf['MOR-PERS'].toString()) : ''
  contact.fatherIdNumber = dsf['FAR-FODT'] ? (dsf['FAR-FODT'].toString() + dsf['FAR-PERS'].toString()) : ''
  contact.spouseIdNumber = dsf['EKT-FODT'] ? (dsf['EKT-FODT'].toString() + dsf['EKT-PERS'].toString()) : ''
  contact.children = []
  if (dsf['Barn']) {
    contact.children = Array.isArray(dsf['Barn']) ? dsf['Barn'] : [dsf['Barn']]
    contact.children = contact.children.map(child => (
      {
        childIdNumber: child['BAR-FODT'].toString() + child['BAR-PERS'].toString()
      }
    ))
  }

  return contact
}
<commit_msg>Checks if parent/spouse/child has a personal id<commit_after>'use strict'

const resolveBirthDate = require('birthdate-from-id')
const capitalize = require('capitalize')
const resolveFullName = require('./lib/resolve-full-name')

module.exports = (dsf) => {
  if (!dsf) {
    throw new Error('Missing required input: dsf object')
  }

  let contact = {}

  contact.personalIdNumber = dsf.FODT.toString() + dsf.PERS.toString()
  contact.birthDate = resolveBirthDate(`${dsf.FODT}${dsf.PERS}`)
  contact.firstName = capitalize.words(dsf['NAVN-F'].toLowerCase())
  contact.middleName = dsf['NAVN-M'] && dsf['NAVN-M'].length > 0 ? capitalize.words(dsf['NAVN-M'].toLowerCase()) : ''
  contact.lastName = capitalize.words(dsf['NAVN-S'].toLowerCase())
  contact.fullName = resolveFullName(contact.firstName, contact.middleName, contact.lastName)
  contact.address = capitalize.words(dsf.ADR ? dsf.ADR.toLowerCase() : '')
  contact.zip = dsf.POSTN || ''
  contact.city = capitalize.words(dsf.POSTS ? dsf.POSTS.toLowerCase() : '')
  contact.gender = dsf.KJONN ? (dsf.KJONN === 'M' ? 'Male' : 'Female') : ''
  contact.alive = dsf.STAT ? (dsf.STAT !== 'DØD') : ''
  contact.motherIdNumber = dsf['MOR-FODT'] && dsf['MOR-PERS'] ? (dsf['MOR-FODT'].toString() + dsf['MOR-PERS'].toString()) : ''
  contact.fatherIdNumber = dsf['FAR-FODT'] && dsf['FAR-PERS'] ? (dsf['FAR-FODT'].toString() + dsf['FAR-PERS'].toString()) : ''
  contact.spouseIdNumber = dsf['EKT-FODT'] && dsf['EKT-PERS'] ? (dsf['EKT-FODT'].toString() + dsf['EKT-PERS'].toString()) : ''
  contact.children = []
  if (dsf['Barn']) {
    contact.children = Array.isArray(dsf['Barn']) ? dsf['Barn'] : [dsf['Barn']]
    contact.children = contact.children.filter(child => child['BAR-FODT'] && child['BAR-PERS'])
    contact.children = contact.children.map(child => (
      {
        childIdNumber: child['BAR-FODT'].toString() + child['BAR-PERS'].toString()
      }
    ))
  }

  return contact
}
<|endoftext|>


<commit_before>
module.exports = function(fn) {
  var debug = require('debug')('express-interceptor');

  return function(req,res,next){
    var methods = fn(req,res);
    _validateParams(methods);

    var originalEnd = res.end;
    var originalWrite = res.write;
    var chunks = [];
    var isIntercepting;
    var isFirstWrite = true;

    function intercept(rawChunk, encoding){
      if(isFirstWrite){
        isFirstWrite = false;
        isIntercepting = methods.isInterceptable();
      }
      debug('isIntercepting? %s', isIntercepting);
      if (isIntercepting){
        // collect all the parts of a response
        if(rawChunk){
          var chunk = rawChunk
          if (rawChunk !== null && !Buffer.isBuffer(chunk) && encoding !== 'buffer') {
            if (!encoding) {
              chunk = new Buffer(rawChunk)
            } else {
              chunk = new Buffer(rawChunk, encoding)
            }
          }
          chunks.push(chunk);
        }
        if(typeof cb === 'function'){
          cb();
        }
      }
      return isIntercepting;
    }

    res.write = function(chunk, encoding, cb) {
      debug('write called');
      if( !intercept(chunk,encoding) ){
        originalWrite.apply(res, arguments);
      }
    };

    function afterSend(oldBody, newBody){
      if(typeof methods.afterSend === 'function'){
        process.nextTick(function() {
          debug('methods.afterSend running now, body size: %s %s',oldBody.length, newBody.length);
          methods.afterSend(oldBody, newBody);
        });
      }
    }

    res.end = function(chunk, encoding, cb) {
      debug('end called');
      var args = Array.prototype.slice.call(arguments);
      if( intercept(chunk,encoding) ){
        isIntercepting = false;
        var oldBody = Buffer.concat(chunks).toString('utf-8');
        if (methods.intercept){
          if(typeof methods.intercept !== 'function'){
            throw new Error('`send` must be a function with the body to be sent as the only param');
          }
          res.removeHeader('Content-Length');
          // allow the user to re-write response
          methods.intercept(oldBody, function(newBody) {
            args[0] = newBody;
            originalEnd.apply(res,args);
            afterSend(oldBody,newBody);
          });
        } else {
          debug(' methods.send isnt defined');
          afterSend(oldBody,oldBody);
          originalEnd.apply(res,args);
        }
      } else {
        originalEnd.apply(res,args);
      }
    };
    next();
  };
};

var VALID_PARAMS = ['isInterceptable', 'intercept', 'afterSend'];
function _validateParams(methods){
  for(var k in methods){
    if (VALID_PARAMS.indexOf(k) < 0){
      throw(new Error(k+' isn\'t a valid param (' + VALID_PARAMS.join(', ') + ')'));
    }
  }

  if (!('isInterceptable' in methods)){
    throw('isInterceptable is a required param (function)');
  }
}
<commit_msg>better style in middleware definition<commit_after>
module.exports = function(fn) {
  var debug = require('debug')('express-interceptor');

  return function(req, res, next) {
    var methods = fn(req, res);
    _validateParams(methods);

    var originalEnd = res.end;
    var originalWrite = res.write;
    var chunks = [];
    var isIntercepting;
    var isFirstWrite = true;

    function intercept(rawChunk, encoding) {
      if (isFirstWrite) {
        isFirstWrite = false;
        isIntercepting = methods.isInterceptable();
      }

      debug('isIntercepting? %s', isIntercepting);
      if (isIntercepting) {
        // collect all the parts of a response
        if (rawChunk) {
          var chunk = rawChunk
          if (rawChunk !== null && !Buffer.isBuffer(chunk) && encoding !== 'buffer') {
            if (!encoding) {
              chunk = new Buffer(rawChunk)
            } else {
              chunk = new Buffer(rawChunk, encoding)
            }
          }
          chunks.push(chunk);
        }
        if (typeof cb === 'function') {
          cb();
        }
      }

      return isIntercepting;
    }

    res.write = function(chunk, encoding, cb) {
      debug('write called');
      if(!intercept(chunk,encoding)) {
        originalWrite.apply(res, arguments);
      }
    };

    function afterSend(oldBody, newBody) {
      if (typeof methods.afterSend === 'function') {
        process.nextTick(function() {
          debug('methods.afterSend running now, body size: %s %s', oldBody.length, newBody.length);
          methods.afterSend(oldBody, newBody);
        });
      }
    }

    res.end = function(chunk, encoding, cb) {
      debug('end called');
      var args = Array.prototype.slice.call(arguments);

      if (intercept(chunk,encoding)) {
        isIntercepting = false;
        var oldBody = Buffer.concat(chunks).toString('utf-8');

        if (methods.intercept) {
          if (typeof methods.intercept !== 'function') {
            throw new Error('`send` must be a function with the body to be sent as the only param');
          }

          res.removeHeader('Content-Length');
          // allow the user to re-write response
          methods.intercept(oldBody, function(newBody) {
            args[0] = newBody;
            originalEnd.apply(res,args);
            afterSend(oldBody,newBody);
          });
        } else {
          debug(' methods.send isnt defined');
          afterSend(oldBody, oldBody);
          originalEnd.apply(res, args);
        }

      } else {
        originalEnd.apply(res, args);
      }

    };

    next();
  };
};

var VALID_PARAMS = ['isInterceptable', 'intercept', 'afterSend'];
function _validateParams(methods) {
  for (var k in methods) {
    if (VALID_PARAMS.indexOf(k) < 0) {
      throw(new Error(k+' isn\'t a valid param (' + VALID_PARAMS.join(', ') + ')'));
    }
  }

  if (!('isInterceptable' in methods)) {
    throw('isInterceptable is a required param (function)');
  }
}
<|endoftext|>


<commit_before>/**
 * @fileOverview Code of web worker thead used for file reading and  hash calculation.
 * @author Zoltan Toth-Czifra
 * @license New (3 clause) BSD license - see LICENSE file.
 *
 * Copyright (C) Zoltan Toth-Czifra
 */

// If Sha1 object is not present in a combined JS, we include it.
// @todo Support more hashing algorithms.
if ( "undefined" === typeof Sha1 )
{
    importScripts( 'hashes/sha1.js' );
}

/**
 * Sha1 object used for hash calculation (included in package).
 *
 * This is used globally for the whole file and not the chunk.
 * Its result is sent with the last chunk.
 *
 * @requires Sha1
 */
var oSha1Whole        = new Sha1();

/**
 * Events handler for when the thread is messaged.
 *
 * @param {object} oEvent Object containing data sent from other theads (data attribute).
 */
self.addEventListener('message', function( oEvent )
{
    var oSha1Chunk       = new Sha1();
    var oFile            = oEvent.data.file;
    var nFileSize        = oEvent.data.file.size;
    var nChunkSize       = oEvent.data.chunkSize;
    var nOffset          = oEvent.data.offset;
    var bLast            = oEvent.data.last;
    var oChunk           = sliceFile ( oFile, nOffset, nChunkSize );
    var sHash;
    var oResponse;

    // We need this callback because Firefox does not support sync file reading.
    // Chrome does. We hide this infomation in the readChunk function.
    readChunk( oChunk, function( sBinary )
    {
        // Feeding chunk hash.
        oSha1Chunk.feed( sBinary, false );
        // Feeding file hash.
        oSha1Whole.feed( sBinary, false );

        sHash = oSha1Chunk.finalize();

        oResponse = {
            "offset"    : nOffset,
            "size"      : Math.min( nChunkSize, ( nFileSize - nOffset ) ),
            "binary"    : sBinary,
            "hash"      : sHash
        };

        // If it's the last piece, we give the overall hash and size too.
        if ( bLast )
        {
            oResponse["entire_size"] = nFileSize;
            oResponse["entire_hash"] = oSha1Whole.finalize();
        }

        postMessage( oResponse );
    } );
});

/**
 * Slices a file object to a blob from a certain offset with a certain length.
 *
 * Webkit browsers don't implement the standard slice method, so we need this function.
 *
 * @param {object} oFile File object from file input.
 * @param {number} nOffset Offset in the file in bytes telling the first byte.
 * @param {number} nLength LEngth of the blob.
 * @return {object} Blob object with the slice.
 */
var sliceFile = function( oFile, nOffset, nLength )
{
    if ( "undefined" === typeof oFile.slice && "undefined" !== typeof oFile.webkitSlice )
    {
        // We are in Chrome.
        sliceFile = function( oFile, nOffset, nLength )
        {
            // Note the 2nd parameter is not length but end offset.
            return oFile.webkitSlice( nOffset, nOffset + nLength );
        }
    }
    else
    {
        // We use the standard way.
        sliceFile = function( oFile, nOffset, nLength )
        {
            return oFile.slice( nOffset, nLength );
        }
    }

    return sliceFile( oFile, nOffset, nLength );
}

/**
 * Wrapper around synchronous and asynchronous file reading methods.
 *
 * Not all browsers support the preferrred synchronous file reading so we
 * need to trick with callbacks.
 *
 * @param {object} oChunk Blog object of the file chunk to read.
 * @param {callback} fpCallback Function to call with the binary input when reading is finished.
 */
var readChunk = function( oChunk, fpCallback )
{
    /**
     * FileReaderSync or FileReader object used for file read.
     *
     * The object depends on the support, FileReaderSync is preferred.
     *
     * @requires FileReaderSync|FileReader
     */
    var oFileReader = null;

    if ( "undefined" !== typeof FileReaderSync )
    {
        oFileReader = new FileReaderSync();

        readChunk = function( oChunk, fpCallback )
        {
            fpCallback( oFileReader.readAsBinaryString( oChunk ) );
        }
    }
    else if ( "undefined" !== typeof FileReader )
    {
        oFileReader = new FileReader();

        readChunk = function( oChunk, fpCallback )
        {
            oFileReader.onload = function( oEvent )
            {
                 fpCallback( oEvent.target.result );
            }
            oFileReader.readAsBinaryString( oChunk );
        }
    }
    else
    {
        throw new Error( 'File API is not supported in this browser.' );
    }

    return readChunk ( oChunk, fpCallback );
}
<commit_msg>Define sliceFile with mozSlice in addition to webkitSlice.<commit_after>/**
 * @fileOverview Code of web worker thead used for file reading and  hash calculation.
 * @author Zoltan Toth-Czifra
 * @license New (3 clause) BSD license - see LICENSE file.
 *
 * Copyright (C) Zoltan Toth-Czifra
 */

// If Sha1 object is not present in a combined JS, we include it.
// @todo Support more hashing algorithms.
if ( "undefined" === typeof Sha1 )
{
    importScripts( 'hashes/sha1.js' );
}

/**
 * Sha1 object used for hash calculation (included in package).
 *
 * This is used globally for the whole file and not the chunk.
 * Its result is sent with the last chunk.
 *
 * @requires Sha1
 */
var oSha1Whole        = new Sha1();

/**
 * Events handler for when the thread is messaged.
 *
 * @param {object} oEvent Object containing data sent from other theads (data attribute).
 */
self.addEventListener('message', function( oEvent )
{
    var oSha1Chunk       = new Sha1();
    var oFile            = oEvent.data.file;
    var nFileSize        = oEvent.data.file.size;
    var nChunkSize       = oEvent.data.chunkSize;
    var nOffset          = oEvent.data.offset;
    var bLast            = oEvent.data.last;
    var oChunk           = sliceFile ( oFile, nOffset, nChunkSize );
    var sHash;
    var oResponse;

    // We need this callback because Firefox does not support sync file reading.
    // Chrome does. We hide this infomation in the readChunk function.
    readChunk( oChunk, function( sBinary )
    {
        // Feeding chunk hash.
        oSha1Chunk.feed( sBinary, false );
        // Feeding file hash.
        oSha1Whole.feed( sBinary, false );

        sHash = oSha1Chunk.finalize();

        oResponse = {
            "offset"    : nOffset,
            "size"      : Math.min( nChunkSize, ( nFileSize - nOffset ) ),
            "binary"    : sBinary,
            "hash"      : sHash
        };

        // If it's the last piece, we give the overall hash and size too.
        if ( bLast )
        {
            oResponse["entire_size"] = nFileSize;
            oResponse["entire_hash"] = oSha1Whole.finalize();
        }

        postMessage( oResponse );
    } );
});

/**
 * Slices a file object to a blob from a certain offset with a certain length.
 *
 * Webkit browsers don't implement the standard slice method, so we need this function.
 *
 * @param {object} oFile File object from file input.
 * @param {number} nOffset Offset in the file in bytes telling the first byte.
 * @param {number} nLength LEngth of the blob.
 * @return {object} Blob object with the slice.
 */
var sliceFile = function( oFile, nOffset, nLength )
{
    if ( "undefined" !== typeof oFile.webkitSlice )
    {
        // We are in Chrome.
        sliceFile = function( oFile, nOffset, nLength )
        {
            // Note the 2nd parameter is not length but end offset.
            return oFile.webkitSlice( nOffset, nOffset + nLength );
        }
    }
    else if ( "undefined" !== typeof oFile.mozSlice )
    {
        // We are in Firefox.
        sliceFile = function( oFile, nOffset, nLength )
        {
            // Note the 2nd parameter is not length but end offset.
            return oFile.mozSlice( nOffset, nOffset + nLength );
        }
    }
    else
    {
        // We use the standard way.
        sliceFile = function( oFile, nOffset, nLength )
        {
            return oFile.slice( nOffset, nLength );
        }
    }

    return sliceFile( oFile, nOffset, nLength );
}

/**
 * Wrapper around synchronous and asynchronous file reading methods.
 *
 * Not all browsers support the preferrred synchronous file reading so we
 * need to trick with callbacks.
 *
 * @param {object} oChunk Blog object of the file chunk to read.
 * @param {callback} fpCallback Function to call with the binary input when reading is finished.
 */
var readChunk = function( oChunk, fpCallback )
{
    /**
     * FileReaderSync or FileReader object used for file read.
     *
     * The object depends on the support, FileReaderSync is preferred.
     *
     * @requires FileReaderSync|FileReader
     */
    var oFileReader = null;

    if ( "undefined" !== typeof FileReaderSync )
    {
        oFileReader = new FileReaderSync();

        readChunk = function( oChunk, fpCallback )
        {
            fpCallback( oFileReader.readAsBinaryString( oChunk ) );
        }
    }
    else if ( "undefined" !== typeof FileReader )
    {
        oFileReader = new FileReader();

        readChunk = function( oChunk, fpCallback )
        {
            oFileReader.onload = function( oEvent )
            {
                 fpCallback( oEvent.target.result );
            }
            oFileReader.readAsBinaryString( oChunk );
        }
    }
    else
    {
        throw new Error( 'File API is not supported in this browser.' );
    }

    return readChunk ( oChunk, fpCallback );
}
<|endoftext|>