<commit_before>const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');
const SVGOptimizer = require('broccoli-svg-optimizer');
const Symbolizer = require('broccoli-symbolizer');
const InlinePacker = require('./inline-packer');
const ViewerAssetsBuilder = require('./viewer-assets-builder');
const ViewerBuilder = require('./viewer-builder');
const validateOptions = require('./validate-options');
const defaultGenerators = require('./default-generators');

// GLOBAL_OPTIONS can be defined as both a root or strategy specific option.
const GLOBAL_OPTIONS = ['sourceDirs', 'stripPath', 'optimizer'];

const symbolsLoaderScript = fs.readFileSync(
  path.join(__dirname, '../symbols-loader.html'), 'utf8'
);

function mergeTreesIfNeeded(trees, options) {
  return trees.length === 1 ? trees[0] : new MergeTrees(trees, options);
}

function memoize(fn) {
  let cache = {};

  return function() {
    let cacheKey = JSON.stringify(arguments);
    cache[cacheKey] = cache[cacheKey] || fn.apply(this, arguments);
    return cache[cacheKey];
  };
}

module.exports = {
  name: 'ember-svg-jar',

  isDevelopingAddon() {
    return false;
  },

  included(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      // eslint-disable-next-line no-param-reassign
      app = app.app;
    }

    this.initializeOptions(app.options.svgJar, app.env);
  },

  treeForPublic() {
    let trees = [];

    if (this.options.viewer.enabled) {
      trees.push(this.getViewerTree());

      if (this.options.viewer.embed) {
        trees.push(this._super.treeForPublic.apply(this, arguments));
      }
    }

    if (this.hasSymbolStrategy()) {
      trees.push(this.getSymbolStrategyTree());
    }

    return mergeTreesIfNeeded(trees);
  },

  treeForApp(appTree) {
    let trees = [appTree];

    if (this.hasInlineStrategy()) {
      trees.push(this.getInlineStrategyTree());
    }

    return mergeTreesIfNeeded(trees, { overwrite: true });
  },

  contentFor(type) {
    let includeLoader =
        this.hasSymbolStrategy() && this.optionFor('symbol', 'includeLoader');

    if (type === 'body' && includeLoader) {
      return symbolsLoaderScript
        .replace('{{FILE_PATH}}', this.optionFor('symbol', 'outputFile'));
    }

    return '';
  },

  initializeOptions(options, env) {
    this.options = _.merge({
      sourceDirs: ['public'],
      strategy: 'inline',
      stripPath: true,
      optimizer: {},
      persist: true,

      viewer: {
        enabled: env === 'development',
        embed: env === 'development'
      },

      inline: {
        idGen: defaultGenerators.inlineIdGen,
        copypastaGen: defaultGenerators.inlineCopypastaGen
      },

      symbol: {
        idGen: defaultGenerators.symbolIdGen,
        copypastaGen: defaultGenerators.symbolCopypastaGen,
        outputFile: '/assets/symbols.svg',
        prefix: '',
        includeLoader: true
      }
    }, options || {});

    validateOptions(this.options);
    this.options.strategy = _.castArray(this.options.strategy);
  },

  optionFor(strategy, optionName) {
    return _.isUndefined(this.options[strategy][optionName])
      ? GLOBAL_OPTIONS.indexOf(optionName) !== -1 && this.options[optionName]
      : this.options[strategy][optionName];
  },

  sourceDirsFor(strategy) {
    return this.optionFor(strategy, 'sourceDirs')
      .filter((sourceDir) => fs.existsSync(sourceDir));
  },

  optimizedSvgsFor: memoize(function(strategy) {
    let sourceDirs = this.sourceDirsFor(strategy);
    let svgFiles = new Funnel(mergeTreesIfNeeded(sourceDirs), {
      include: ['**/*.svg']
    });

    let svgoConfig = this.optionFor(strategy, 'optimizer');
    if (svgoConfig) {
      svgFiles = new SVGOptimizer(svgFiles, {
        svgoConfig,
        persist: this.options.persist
      });
    }

    return svgFiles;
  }),

  originalSvgsFor(strategy) {
    let sourceDirs = this.sourceDirsFor(strategy);

    return new Funnel(mergeTreesIfNeeded(sourceDirs), {
      include: ['**/*.svg'],
      destDir: '__original__'
    });
  },

  getViewerTree() {
    let idGenOpts = {
      symbol: {
        prefix: this.optionFor('symbol', 'prefix')
      }
    };

    let viewerBuilderNodes = this.options.strategy.map((strategy) => {
      let inputNode = new MergeTrees([
        this.optimizedSvgsFor(strategy),
        this.originalSvgsFor(strategy)
      ]);

      return new ViewerAssetsBuilder(inputNode, {
        strategy,
        idGen: this.optionFor(strategy, 'idGen'),
        idGenOpts: idGenOpts[strategy],
        copypastaGen: this.optionFor(strategy, 'copypastaGen'),
        stripPath: this.optionFor(strategy, 'stripPath'),
        outputFile: `${strategy}.json`,
        ui: this.ui
      });
    });

    return new ViewerBuilder(mergeTreesIfNeeded(viewerBuilderNodes), {
      outputFile: 'svg-jar.json',
      hasManyStrategies: this.options.strategy.length > 1
    });
  },

  getInlineStrategyTree() {
    return new InlinePacker(this.optimizedSvgsFor('inline'), {
      idGen: this.optionFor('inline', 'idGen'),
      stripPath: this.optionFor('inline', 'stripPath'),
      outputFile: 'inline-assets.js'
    });
  },

  getSymbolStrategyTree() {
    return new Symbolizer(this.optimizedSvgsFor('symbol'), {
      idGen: this.optionFor('symbol', 'idGen'),
      stripPath: this.optionFor('symbol', 'stripPath'),
      outputFile: this.optionFor('symbol', 'outputFile'),
      prefix: this.optionFor('symbol', 'prefix'),
      persist: this.options.persist
    });
  },

  hasInlineStrategy() {
    return this.options.strategy.indexOf('inline') !== -1;
  },

  hasSymbolStrategy() {
    return this.options.strategy.indexOf('symbol') !== -1;
  }
};
<commit_msg>Switch to memoize from lodash<commit_after>const fs = require('fs');
const path = require('path');
const _ = require('lodash');
const Funnel = require('broccoli-funnel');
const MergeTrees = require('broccoli-merge-trees');
const SVGOptimizer = require('broccoli-svg-optimizer');
const Symbolizer = require('broccoli-symbolizer');
const InlinePacker = require('./inline-packer');
const ViewerAssetsBuilder = require('./viewer-assets-builder');
const ViewerBuilder = require('./viewer-builder');
const validateOptions = require('./validate-options');
const defaultGenerators = require('./default-generators');

// GLOBAL_OPTIONS can be defined as both a root or strategy specific option.
const GLOBAL_OPTIONS = ['sourceDirs', 'stripPath', 'optimizer'];

const symbolsLoaderScript = fs.readFileSync(
  path.join(__dirname, '../symbols-loader.html'), 'utf8'
);

function mergeTreesIfNeeded(trees, options) {
  return trees.length === 1 ? trees[0] : new MergeTrees(trees, options);
}

module.exports = {
  name: 'ember-svg-jar',

  isDevelopingAddon() {
    return false;
  },

  included(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      // eslint-disable-next-line no-param-reassign
      app = app.app;
    }

    this.initializeOptions(app.options.svgJar, app.env);
  },

  treeForPublic() {
    let trees = [];

    if (this.options.viewer.enabled) {
      trees.push(this.getViewerTree());

      if (this.options.viewer.embed) {
        trees.push(this._super.treeForPublic.apply(this, arguments));
      }
    }

    if (this.hasSymbolStrategy()) {
      trees.push(this.getSymbolStrategyTree());
    }

    return mergeTreesIfNeeded(trees);
  },

  treeForApp(appTree) {
    let trees = [appTree];

    if (this.hasInlineStrategy()) {
      trees.push(this.getInlineStrategyTree());
    }

    return mergeTreesIfNeeded(trees, { overwrite: true });
  },

  contentFor(type) {
    let includeLoader =
        this.hasSymbolStrategy() && this.optionFor('symbol', 'includeLoader');

    if (type === 'body' && includeLoader) {
      return symbolsLoaderScript
        .replace('{{FILE_PATH}}', this.optionFor('symbol', 'outputFile'));
    }

    return '';
  },

  initializeOptions(options, env) {
    this.options = _.merge({
      sourceDirs: ['public'],
      strategy: 'inline',
      stripPath: true,
      optimizer: {},
      persist: true,

      viewer: {
        enabled: env === 'development',
        embed: env === 'development'
      },

      inline: {
        idGen: defaultGenerators.inlineIdGen,
        copypastaGen: defaultGenerators.inlineCopypastaGen
      },

      symbol: {
        idGen: defaultGenerators.symbolIdGen,
        copypastaGen: defaultGenerators.symbolCopypastaGen,
        outputFile: '/assets/symbols.svg',
        prefix: '',
        includeLoader: true
      }
    }, options || {});

    validateOptions(this.options);
    this.options.strategy = _.castArray(this.options.strategy);
  },

  optionFor(strategy, optionName) {
    return _.isUndefined(this.options[strategy][optionName])
      ? GLOBAL_OPTIONS.indexOf(optionName) !== -1 && this.options[optionName]
      : this.options[strategy][optionName];
  },

  sourceDirsFor(strategy) {
    return this.optionFor(strategy, 'sourceDirs')
      .filter((sourceDir) => fs.existsSync(sourceDir));
  },

  optimizedSvgsFor: _.memoize(function(strategy) {
    let sourceDirs = this.sourceDirsFor(strategy);
    let svgFiles = new Funnel(mergeTreesIfNeeded(sourceDirs), {
      include: ['**/*.svg']
    });

    let svgoConfig = this.optionFor(strategy, 'optimizer');
    if (svgoConfig) {
      svgFiles = new SVGOptimizer(svgFiles, {
        svgoConfig,
        persist: this.options.persist
      });
    }

    return svgFiles;
  }),

  originalSvgsFor(strategy) {
    let sourceDirs = this.sourceDirsFor(strategy);

    return new Funnel(mergeTreesIfNeeded(sourceDirs), {
      include: ['**/*.svg'],
      destDir: '__original__'
    });
  },

  getViewerTree() {
    let idGenOpts = {
      symbol: {
        prefix: this.optionFor('symbol', 'prefix')
      }
    };

    let viewerBuilderNodes = this.options.strategy.map((strategy) => {
      let inputNode = new MergeTrees([
        this.optimizedSvgsFor(strategy),
        this.originalSvgsFor(strategy)
      ]);

      return new ViewerAssetsBuilder(inputNode, {
        strategy,
        idGen: this.optionFor(strategy, 'idGen'),
        idGenOpts: idGenOpts[strategy],
        copypastaGen: this.optionFor(strategy, 'copypastaGen'),
        stripPath: this.optionFor(strategy, 'stripPath'),
        outputFile: `${strategy}.json`,
        ui: this.ui
      });
    });

    return new ViewerBuilder(mergeTreesIfNeeded(viewerBuilderNodes), {
      outputFile: 'svg-jar.json',
      hasManyStrategies: this.options.strategy.length > 1
    });
  },

  getInlineStrategyTree() {
    return new InlinePacker(this.optimizedSvgsFor('inline'), {
      idGen: this.optionFor('inline', 'idGen'),
      stripPath: this.optionFor('inline', 'stripPath'),
      outputFile: 'inline-assets.js'
    });
  },

  getSymbolStrategyTree() {
    return new Symbolizer(this.optimizedSvgsFor('symbol'), {
      idGen: this.optionFor('symbol', 'idGen'),
      stripPath: this.optionFor('symbol', 'stripPath'),
      outputFile: this.optionFor('symbol', 'outputFile'),
      prefix: this.optionFor('symbol', 'prefix'),
      persist: this.options.persist
    });
  },

  hasInlineStrategy() {
    return this.options.strategy.indexOf('inline') !== -1;
  },

  hasSymbolStrategy() {
    return this.options.strategy.indexOf('symbol') !== -1;
  }
};
<|endoftext|>


<commit_before>'use strict'

const { Router } = require('express')
const router = Router()

const session = require('../controllers/session')
const wishlist = require('../controllers/wishlist')

router.post('/register', session.register)

router.post('/login', session.login)

router.post('/api/addToWishlist', wishlist.addToWishlist)

router.get('/api/getWishlist', wishlist.getWishlist)

module.exports = router<commit_msg>added remove from wishlist route to routes index.js<commit_after>'use strict'

const { Router } = require('express')
const router = Router()

const session = require('../controllers/session')
const wishlist = require('../controllers/wishlist')

router.post('/register', session.register)

router.post('/login', session.login)

router.post('/api/addToWishlist', wishlist.addToWishlist)

router.get('/api/getWishlist', wishlist.getWishlist)

router.post('/api/removeFromWishlist', wishlist.removeFromWishlist)

module.exports = router<|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var util = require('util');
var events = require('events');

var glob = require('glob');
var Spider = require('./spider.js');
var Optimizer = require('./optimizer.js');
var Convertor = require('./convertor.js');

var copyFile = function (srcpath, destpath) {
	var contents = fs.readFileSync(srcpath);
	fs.writeFileSync(destpath, contents);
};

var FontSpider = function (src, options) {

	if (typeof src === 'string') {
		src = glob.sync(src);
	} else {
		var srcs = [];
		src.forEach(function (item) {
			srcs = srcs.concat(glob.sync(item));
		});
		src = srcs;
	}

	options = options || {};

	this.src = src;
	this.options = options;
};

FontSpider.prototype = {

	constructor: FontSpider,

	onoutput: function (data) {},
	onerror: function (data) {},
	onend: function (data) {},

	start: function () {

		var that = this;
		var src = this.src;
		var options = this.options;

		var debug = options.debug;
		var ignore = options.ignore;
		var chars = options.chars;
		var backup = options.backup !== false;

		var BACKUP_EXTNAME = '.backup';

		new Spider(src, function (error, data) {

			if (error) {
				throw error;
			}

			var result = [];

			data.forEach(function (item) {

		        // 忽略的字体
		        if (ignore && ignore.indexOf(item.name) !== -1) {
		            return;
		        }

		        var includeChars = '';
		        var chars = item.chars;

		        if (typeof chars === 'string') {
		            includeChars = chars;
		        } else if (typeof chars === 'object') {
		            includeChars = chars[item.name];
		        }

		        // 除重
		        includeChars.split('').forEach(function (char) {
		            if (item.chars.indexOf(char) === -1) {
		                chars += char;
		            }
		        });

		        // 如果没有使用任何字符，则不处理字体
		        if (!chars) {
		        	return;
		        }

		        // 找到 .ttf 的字体文件
		        var src, dest;
		        item.files.forEach(function (file) {
		            var extname = path.extname(file).toLocaleLowerCase();

			        if (error) {
			        	return;
			        }

		            if (extname !== '.ttf') {
		            	return;
		            }

	            	if (fs.existsSync(file)) {

		            	if (backup && fs.existsSync(file + BACKUP_EXTNAME)) {
		            		// 使用备份的字体
		            		src = file + BACKUP_EXTNAME;
		            	} else {
		            		src = file;
		            		// 备份字体，这样可以反复处理
		            		backup && copyFile(src, src + BACKUP_EXTNAME);
		            	}

		            	dest = file;
	            	} else {

		            	error = {
		            		code: 1,
		            		message: '"' + file + '" file not found.'
		            	};
		            	that.onerror(error);
		            }

		        });

		        if (error) {
		        	return;
		        }

		        if (!src) {
	            	error = {
	            		code: 2,
	            		message: '".ttf" file not found.'
	            	};
	            	that.onerror(error);
		            return;
		        }

	            dest = dest || src;
	            var dirname = path.dirname(dest);
	            var extname = path.extname(dest);
	            var basename = path.basename(dest, extname);
	            var out = path.join(dirname, basename);
	            var stat = fs.statSync(src);

	            var optimizer = new Optimizer(src);
	            var optimizerResult = optimizer.minify(dest, chars);

	            if (optimizerResult.code !== 0) {

	            	if (optimizerResult.code === Optimizer.COMMAND_NOT_FOUND) {
		            	error = {
		            		code: 3,
		            		message: 'Please install perl. See: http://www.perl.org'
		            	};
	            	} else {
		            	error = {
		            		code: 4,
		            		message: 'Optimizer error.\n' + src,
		            		result: optimizerResult.output
		            	};
	            	}

	            	that.onerror(error);

	            	return;
	            }

	            var info = {
	            	fontName: item.name,
	            	includeChars: chars.replace(/[\n\r\t]/g, ''),
	            	originalSize: stat.size,
	            	output: [{
	            		file: path.relative('./', dest),
	            		size: fs.statSync(dest).size
	            	}]
	            };

	            var convertor = new Convertor(dest);

	            item.files.forEach(function (file) {

	                var extname = path.extname(file).toLocaleLowerCase();
	                var type = extname.replace('.', '');

	                if (type === 'ttf') {
	                    return;
	                }

	                if (typeof convertor[type] === 'function') {
	                    convertor[type](file);

	                    info.output.push({
	                    	file: path.relative('./', file),
	                    	size: fs.statSync(file).size
	                    });

	                } else {
		            	console.warn('File ' + path.relative('./', file) + ' not created.')
	                }

	            });

	            result.push(info);
	            that.onoutput(info);

			});

			that.onend(result);

		}, debug);

	}
};

module.exports = FontSpider;
<commit_msg>优化错误处理<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var util = require('util');
var events = require('events');

var glob = require('glob');
var Spider = require('./spider.js');
var Optimizer = require('./optimizer.js');
var Convertor = require('./convertor.js');

var copyFile = function (srcpath, destpath) {
	var contents = fs.readFileSync(srcpath);
	fs.writeFileSync(destpath, contents);
};

var FontSpider = function (src, options) {

	if (typeof src === 'string') {
		src = glob.sync(src);
	} else {
		var srcs = [];
		src.forEach(function (item) {
			srcs = srcs.concat(glob.sync(item));
		});
		src = srcs;
	}

	options = options || {};
	Object.keys(FontSpider.defaults).forEach(function (key) {
		if (options[key] === undefined) {
			options[key] = FontSpider.defaults[key];
		}
	});

	this.src = src;
	this.options = options;
};

FontSpider.BACKUP_EXTNAME = '.backup';
FontSpider.defaults = {
	debug: false,
	silent: false,
	backup: true,
	ignore: [],
	map: []
};

FontSpider.prototype = {

	constructor: FontSpider,

	onoutput: function (data) {},
	onerror: function (data) {},
	onend: function (data) {},

	start: function () {

		var that = this;
		var src = this.src;
		var options = this.options;
		var backup = options.backup !== false;

		var BACKUP_EXTNAME = FontSpider.BACKUP_EXTNAME;

		new Spider(src, options, function (error, data) {

			if (error) {
				that.onerror(error);
				return;
			}

			var result = [];

			data.forEach(function (item) {

		        var chars = item.chars;

		        // 如果没有使用任何字符，则不处理字体
		        if (!chars) {
		        	return;
		        }

		        // 找到 .ttf 的字体文件
		        var src, dest;
		        item.files.forEach(function (file) {
		            var extname = path.extname(file).toLocaleLowerCase();

			        if (error) {
			        	return;
			        }

		            if (extname !== '.ttf') {
		            	return;
		            }

	            	if (fs.existsSync(file)) {

		            	if (backup && fs.existsSync(file + BACKUP_EXTNAME)) {
		            		// 使用备份的字体
		            		src = file + BACKUP_EXTNAME;
		            	} else {
		            		src = file;
		            		// 备份字体，这样可以反复处理
		            		backup && copyFile(src, src + BACKUP_EXTNAME);
		            	}

		            	dest = file;
	            	} else {

		            	error = {
		            		code: 1,
		            		message: '"' + file + '" file not found'
		            	};
		            	that.onerror(error);
		            }

		        });

		        if (error) {
		        	return;
		        }

		        if (!src) {
	            	error = {
	            		code: 2,
	            		message: '"' + item.name  + '"' + ' did not find tureType fonts'
	            	};
	            	that.onerror(error);
		            return;
		        }

	            dest = dest || src;
	            var dirname = path.dirname(dest);
	            var extname = path.extname(dest);
	            var basename = path.basename(dest, extname);
	            var out = path.join(dirname, basename);
	            var stat = fs.statSync(src);

	            var optimizer = new Optimizer(src);
	            var optimizerResult = optimizer.minify(dest, chars);

	            if (optimizerResult.code !== 0) {

	            	if (optimizerResult.code === Optimizer.COMMAND_NOT_FOUND) {
		            	error = {
		            		code: 3,
		            		message: 'Please install perl. See: http://www.perl.org'
		            	};
	            	} else {
		            	error = {
		            		code: 4,
		            		message: 'Optimizer error.\n' + src,
		            		result: optimizerResult.output
		            	};
	            	}

	            	that.onerror(error);

	            	return;
	            }

	            var info = {
	            	fontName: item.name,
	            	includeChars: chars,
	            	originalSize: stat.size,
	            	output: [{
	            		file: path.relative('./', dest),
	            		size: fs.statSync(dest).size
	            	}]
	            };

	            var convertor = new Convertor(dest);

	            item.files.forEach(function (file) {

	                var extname = path.extname(file).toLocaleLowerCase();
	                var type = extname.replace('.', '');

	                if (type === 'ttf') {
	                    return;
	                }

	                if (typeof convertor[type] === 'function') {
	                    convertor[type](file);

	                    info.output.push({
	                    	file: path.relative('./', file),
	                    	size: fs.statSync(file).size
	                    });

	                } else {
		            	console.warn('File ' + path.relative('./', file) + ' not created')
	                }

	            });

	            result.push(info);
	            that.onoutput(info);

			});

			that.onend(result);

		});

	}
};

module.exports = FontSpider;
<|endoftext|>


<commit_before>/**
 * Backend tools needed by the frontend
 */
const router = require('express').Router;
const version = require('../../package.json').version;

router.get('/version', function (req, res, next) {
    res.json(version);
});
<commit_msg>minor fix<commit_after>/**
 * Backend tools needed by the frontend
 */
const router = require('express').Router();
const version = require('../../package.json').version;

router.get('/version', function (req, res, next) {
    res.json(version);
});

module.exports = router;
<|endoftext|>


<commit_before>/*eslint dot-notation:0*/
import {Origin} from 'aurelia-metadata';
import {TemplateRegistryEntry, Loader} from 'aurelia-loader';
import {TextTemplateLoader} from './text-template-loader';

let polyfilled = false;

if (!window.System || !window.System.import) {
  let sys = window.System = window.System || {};

  sys.polyfilled = polyfilled = true;
  sys.isFake = false;
  sys.map = {};

  sys['import'] = function(moduleId) {
    return new Promise((resolve, reject) => {
      require([moduleId], resolve, reject);
    });
  };

  sys.normalize = function(url) {
    return Promise.resolve(url);
  };

  sys.normalizeSync = function(url) {
    return url;
  };

  if (window.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
    let defined = requirejs.s.contexts._.defined;
    sys.forEachModule = function(callback) {
      for (let key in defined) {
        if (callback(key, defined[key])) return;
      }
    };
  } else {
    sys.forEachModule = function(callback) {};
  }
} else {
  let modules = System._loader.modules;

  System.isFake = false;

  System.forEachModule = function(callback) {
    for (let key in modules) {
      if (callback(key, modules[key].module)) return;
    }
  };

  System.set('text', System.newModule({
    'translate': function(load) {
      return 'module.exports = "' + load.source
        .replace(/(["\\])/g, '\\$1')
        .replace(/[\f]/g, '\\f')
        .replace(/[\b]/g, '\\b')
        .replace(/[\n]/g, '\\n')
        .replace(/[\t]/g, '\\t')
        .replace(/[\r]/g, '\\r')
        .replace(/[\u2028]/g, '\\u2028')
        .replace(/[\u2029]/g, '\\u2029')
      + '";';
    }
  }));
}

function ensureOriginOnExports(executed, name) {
  let target = executed;
  let key;
  let exportedValue;

  if (target.__useDefault) {
    target = target['default'];
  }

  Origin.set(target, new Origin(name, 'default'));

  for (key in target) {
    exportedValue = target[key];

    if (typeof exportedValue === 'function') {
      Origin.set(exportedValue, new Origin(name, key));
    }
  }

  return executed;
}

interface TemplateLoader {
  loadTemplate(loader: Loader, entry: TemplateRegistryEntry): Promise<any>;
}

export class DefaultLoader extends Loader {
  textPluginName: string = 'text';

  constructor() {
    super();

    this.moduleRegistry = {};
    this.useTemplateLoader(new TextTemplateLoader());

    let that = this;

    this.addPlugin('template-registry-entry', {
      'fetch': function(address) {
        let entry = that.getOrCreateTemplateRegistryEntry(address);
        return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(x => entry);
      }
    });
  }

  useTemplateLoader(templateLoader: TemplateLoader): void {
    this.templateLoader = templateLoader;
  }

  loadModule(id: string): Promise<any> {
    return System.normalize(id).then(newId => {
      let existing = this.moduleRegistry[newId];
      if (existing) {
        return existing;
      }

      return System.import(newId).then(m => {
        this.moduleRegistry[newId] = m;
        return ensureOriginOnExports(m, newId);
      });
    });
  }

  loadAllModules(ids: string[]): Promise<any[]> {
    let loads = [];

    for (let i = 0, ii = ids.length; i < ii; ++i) {
      loads.push(this.loadModule(ids[i]));
    }

    return Promise.all(loads);
  }

  loadTemplate(url: string): Promise<TemplateRegistryEntry> {
    return System.import(this.applyPluginToUrl(url, 'template-registry-entry'));
  }

  loadText(url: string): Promise<string> {
    return System.import(this.applyPluginToUrl(url, this.textPluginName));
  }

  applyPluginToUrl(url: string, pluginName: string): string {
    return polyfilled ? `${pluginName}!${url}` : `${url}!${pluginName}`;
  }

  addPlugin(pluginName, implementation) {
    if (polyfilled) {
      define(pluginName, [], {
        'load': function(name, req, onload) {
          let address = req.toUrl(name);
          let result = implementation.fetch(address);
          Promise.resolve(result).then(onload);
        }
      });
    } else {
      System.set(pluginName, System.newModule({
        'fetch': function(load, _fetch) {
          let result = implementation.fetch(load.address);
          return Promise.resolve(result).then(x => {
            load.metadata.result = x;
            return '';
          });
        },
        'instantiate': function(load) {
          return load.metadata.result;
        }
      }));
    }
  }
}

window.AureliaLoader = DefaultLoader;
<commit_msg>feat(index): add new loader methods and encapsulate loader better<commit_after>/*eslint dot-notation:0*/
import {Origin} from 'aurelia-metadata';
import {TemplateRegistryEntry, Loader} from 'aurelia-loader';
import {TextTemplateLoader} from './text-template-loader';

function ensureOriginOnExports(executed, name) {
  let target = executed;
  let key;
  let exportedValue;

  if (target.__useDefault) {
    target = target['default'];
  }

  Origin.set(target, new Origin(name, 'default'));

  for (key in target) {
    exportedValue = target[key];

    if (typeof exportedValue === 'function') {
      Origin.set(exportedValue, new Origin(name, key));
    }
  }

  return executed;
}

interface TemplateLoader {
  loadTemplate(loader: Loader, entry: TemplateRegistryEntry): Promise<any>;
}

export class DefaultLoader extends Loader {
  textPluginName: string = 'text';

  constructor() {
    super();

    this.moduleRegistry = {};
    this.useTemplateLoader(new TextTemplateLoader());

    let that = this;

    this.addPlugin('template-registry-entry', {
      'fetch': function(address) {
        let entry = that.getOrCreateTemplateRegistryEntry(address);
        return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(x => entry);
      }
    });
  }

  useTemplateLoader(templateLoader: TemplateLoader): void {
    this.templateLoader = templateLoader;
  }

  loadAllModules(ids: string[]): Promise<any[]> {
    let loads = [];

    for (let i = 0, ii = ids.length; i < ii; ++i) {
      loads.push(this.loadModule(ids[i]));
    }

    return Promise.all(loads);
  }

  loadTemplate(url: string): Promise<TemplateRegistryEntry> {
    return this._import(this.applyPluginToUrl(url, 'template-registry-entry'));
  }

  loadText(url: string): Promise<string> {
    return this._import(this.applyPluginToUrl(url, this.textPluginName));
  }
}

if (!window.System || !window.System.import) {
  if (window.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
    let defined = requirejs.s.contexts._.defined;
    window.eachModule = function(callback) {
      for (let key in defined) {
        if (callback(key, defined[key])) return;
      }
    };
  } else {
    window.eachModule = function(callback) {};
  }

  DefaultLoader.prototype._import = function(moduleId) {
    return new Promise((resolve, reject) => {
      require([moduleId], resolve, reject);
    });
  };

  DefaultLoader.prototype.loadModule = function(id) {
    let existing = this.moduleRegistry[id];
    if (existing) {
      return Promise.resolve(existing);
    }

    return new Promise((resolve, reject) => {
      require([id], m => {
        this.moduleRegistry[newId] = m;
        resolve(ensureOriginOnExports(m, newId));
      }, reject);
    });
  };

  DefaultLoader.prototype.map = function(id, source) {};

  DefaultLoader.prototype.normalizeSync = function(moduleId, relativeTo) {
    return moduleId;
  };

  DefaultLoader.prototype.applyPluginToUrl = function(url, pluginName) {
    return `${pluginName}!${url}`;
  };

  DefaultLoader.prototype.addPlugin = function(pluginName, implementation) {
    define(pluginName, [], {
      'load': function(name, req, onload) {
        let address = req.toUrl(name);
        let result = implementation.fetch(address);
        Promise.resolve(result).then(onload);
      }
    });
  };
} else {
  let modules = System._loader.modules;

  window.eachModule = function(callback) {
    for (let key in modules) {
      if (callback(key, modules[key].module)) return;
    }
  };

  System.set('text', System.newModule({
    'translate': function(load) {
      return 'module.exports = "' + load.source
        .replace(/(["\\])/g, '\\$1')
        .replace(/[\f]/g, '\\f')
        .replace(/[\b]/g, '\\b')
        .replace(/[\n]/g, '\\n')
        .replace(/[\t]/g, '\\t')
        .replace(/[\r]/g, '\\r')
        .replace(/[\u2028]/g, '\\u2028')
        .replace(/[\u2029]/g, '\\u2029')
      + '";';
    }
  }));

  DefaultLoader.prototype._import = function(moduleId) {
    return System.import(moduleId);
  };

  DefaultLoader.prototype.loadModule = function(id) {
    let newId = System.normalizeSync(id);
    let existing = this.moduleRegistry[newId];

    if (existing) {
      return Promise.resolve(existing);
    }

    return System.import(newId).then(m => {
      this.moduleRegistry[newId] = m;
      return ensureOriginOnExports(m, newId);
    });
  };

  DefaultLoader.prototype.map = function(id, source) {
    System.map[id] = source;
  };

  DefaultLoader.prototype.normalizeSync = function(moduleId, relativeTo) {
    return System.normalizeSync(moduleId, relativeTo);
  };

  DefaultLoader.prototype.applyPluginToUrl = function(url, pluginName) {
    return `${url}!${pluginName}`;
  };

  DefaultLoader.prototype.addPlugin = function(pluginName, implementation) {
    System.set(pluginName, System.newModule({
      'fetch': function(load, _fetch) {
        let result = implementation.fetch(load.address);
        return Promise.resolve(result).then(x => {
          load.metadata.result = x;
          return '';
        });
      },
      'instantiate': function(load) {
        return load.metadata.result;
      }
    }));
  };
}
<|endoftext|>


<commit_before>/* eslint-disable no-param-reassign */

const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const Raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, captureUncaught = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = Raven.config(...args);
    if (captureUncaught) {
      this._client.install();
    }
  }
  _write(data, encoding, cb) {
    const additionalData = {
      level: ((tags = []) => {
        tags = (typeof tags === 'string') ? [tags] : tags;
        if (hoek.contain(tags, ['fatal'], { part: true })) {
          return 'fatal';
        } else if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(data.tags),
      tags: ((tags = []) => tags.filter(
        (tag) => [
          'fatal',
          'error',
          'warning',
          'info',
          'debug',
        ].includes(tag) === false,
      ).reduce((acc, curr) => {
        acc[curr] = true;
        return acc;
      }, {}))(data.tags),
      extra: {
        event: data.event,
      },
    };

    this._client.captureMessage(data.data, additionalData, () => cb());
  }
}

module.exports = GoodSentry;
<commit_msg>fix: normalize event tags<commit_after>/* eslint-disable no-param-reassign, no-shadow */

const hostname = require('os').hostname;
const hoek = require('hoek');
const Stream = require('stream');
const Raven = require('raven');

const internals = {
  defaults: {
    name: hostname(),
    logger: '',
    release: '',
    environment: '',
  },
};

class GoodSentry extends Stream.Writable {
  constructor({ dsn = null, config = {}, captureUncaught = false } = {}) {
    super({ objectMode: true, decodeStrings: false });

    const settings = hoek.applyToDefaults(internals.defaults, config);
    const args = (dsn === null) ? [settings] : [dsn, settings];

    this._client = Raven.config(...args);
    if (captureUncaught) {
      this._client.install();
    }
  }
  _write(data, encoding, cb) {
    // Normalize event tags - if its a string then wrap in an array, default to an empty array
    let { tags = [] } = data;
    tags = (typeof tags === 'string') ? [tags] : tags;

    const additionalData = {
      level: ((tags = []) => {
        if (hoek.contain(tags, ['fatal'], { part: true })) {
          return 'fatal';
        } else if (hoek.contain(tags, ['err', 'error'], { part: true })) {
          return 'error';
        } else if (hoek.contain(tags, ['warn', 'warning'], { part: true })) {
          return 'warning';
        } else if (hoek.contain(tags, ['info'], { part: true })) {
          return 'info';
        }

        return 'debug';
      })(tags),
      tags: tags.filter(
        (tag) => ['fatal', 'error', 'warning', 'info', 'debug'].includes(tag) === false,
      ).reduce((acc, curr) => {
        acc[curr] = true;
        return acc;
      }, {}),
      extra: {
        event: data.event,
      },
    };

    this._client.captureMessage(data.data, additionalData, () => cb());
  }
}

module.exports = GoodSentry;
<|endoftext|>


<commit_before>const db = require("./db");
const Keygrip = require('keygrip');
const pgpatcher = require("pg-patcher");
const path = require("path");

const MAX_DB_LEVEL = 6;

/** Create all the tables */
exports.createTables = function () {
  console.info("Setting up tables on", db.constr);
  return db.getConnection().then(([conn, done]) => {
    // This is assuming we are running from dist/server/dbschema.js, and need to
    // find the path of server/db-patches/ (not dist):
    let dirname = path.join(__dirname, "..", "..", "server", "db-patches");
    return new Promise((resolve, reject) => {
      pgpatcher(conn, MAX_DB_LEVEL, {dir: dirname}, function(err) {
        if (err) {
          console.error(`Error patching database to level ${MAX_DB_LEVEL}!`, err);
          done();
          reject(err);
        } else {
          console.info(`Database is now at level ${MAX_DB_LEVEL}`);
          resolve();
        }
      });
    });
  }).then(() => {
    let newId = "tmp" + Date.now();
    return db.insert(
      `INSERT INTO data (id, deviceid, value, url)
       VALUES ($1, NULL, $2, $3)`,
      [newId, "test value", ""]
    ).then((inserted) => {
      if (! inserted) {
        throw new Error("Could not insert");
      }
      return db.del(
        `DELETE FROM data
         WHERE id = $1`,
        [newId]
      ).then((count) => {
        if (count != 1) {
          throw new Error("Should have deleted one row");
        }
      });
    });
  }).catch((err) => {
    if (err.code === "ECONNREFUSED") {
      console.warn(`Could not connect to database on ${db.constr}`);
    }
    console.warn("Got error creating and testing tables:", err);
  });
};

let keys;
let textKeys;

exports.getKeygrip = function () {
  return keys;
};

exports.getTextKeys = function () {
  return textKeys;
};

/** Loads the random signing key from the database, or generates a new key
    if none are found */
function loadKeys() {
  return db.select(
    `SELECT key FROM signing_keys ORDER BY CREATED`,
    []
  ).then((rows) => {
    if (rows.length) {
      let textKeys = [];
      for (let i=0; i<rows.length; i++) {
        textKeys.push(rows[i].key);
      }
      return textKeys;
    } else {
      return makeKey().then((key) => {
        return db.insert(
          `INSERT INTO signing_keys (created, key)
           VALUES (NOW(), $1)`,
          [key]
        ).then((ok) => {
          if (! ok) {
            throw new Error("Could not insert key");
          }
          return [key];
        });
      });
    }
  });
}

exports.createKeygrip = function () {
  loadKeys().then((fetchedTextKeys) => {
    textKeys = fetchedTextKeys;
    keys = new Keygrip(textKeys);
  }).catch((err) => {
    console.warn("Could not create signing keys:", err);
  });
};

/** Returns a promise that generates a new largish ASCII random key */
function makeKey() {
  return new Promise(function (resolve, reject) {
    require('crypto').randomBytes(48, function(err, buf) {
      if (err) {
        reject(err);
        return;
      }
      resolve(buf.toString('base64'));
    });
  });
}
<commit_msg>Log the environment for debugging<commit_after>const db = require("./db");
const Keygrip = require('keygrip');
const pgpatcher = require("pg-patcher");
const path = require("path");

const MAX_DB_LEVEL = 6;

/** Create all the tables */
exports.createTables = function () {
  console.info("Setting up tables on", db.constr);
  console.info("Environment: ", process.env);
  return db.getConnection().then(([conn, done]) => {
    // This is assuming we are running from dist/server/dbschema.js, and need to
    // find the path of server/db-patches/ (not dist):
    let dirname = path.join(__dirname, "..", "..", "server", "db-patches");
    return new Promise((resolve, reject) => {
      pgpatcher(conn, MAX_DB_LEVEL, {dir: dirname}, function(err) {
        if (err) {
          console.error(`Error patching database to level ${MAX_DB_LEVEL}!`, err);
          done();
          reject(err);
        } else {
          console.info(`Database is now at level ${MAX_DB_LEVEL}`);
          resolve();
        }
      });
    });
  }).then(() => {
    let newId = "tmp" + Date.now();
    return db.insert(
      `INSERT INTO data (id, deviceid, value, url)
       VALUES ($1, NULL, $2, $3)`,
      [newId, "test value", ""]
    ).then((inserted) => {
      if (! inserted) {
        throw new Error("Could not insert");
      }
      return db.del(
        `DELETE FROM data
         WHERE id = $1`,
        [newId]
      ).then((count) => {
        if (count != 1) {
          throw new Error("Should have deleted one row");
        }
      });
    });
  }).catch((err) => {
    if (err.code === "ECONNREFUSED") {
      console.warn(`Could not connect to database on ${db.constr}`);
    }
    console.warn("Got error creating and testing tables:", err);
  });
};

let keys;
let textKeys;

exports.getKeygrip = function () {
  return keys;
};

exports.getTextKeys = function () {
  return textKeys;
};

/** Loads the random signing key from the database, or generates a new key
    if none are found */
function loadKeys() {
  return db.select(
    `SELECT key FROM signing_keys ORDER BY CREATED`,
    []
  ).then((rows) => {
    if (rows.length) {
      let textKeys = [];
      for (let i=0; i<rows.length; i++) {
        textKeys.push(rows[i].key);
      }
      return textKeys;
    } else {
      return makeKey().then((key) => {
        return db.insert(
          `INSERT INTO signing_keys (created, key)
           VALUES (NOW(), $1)`,
          [key]
        ).then((ok) => {
          if (! ok) {
            throw new Error("Could not insert key");
          }
          return [key];
        });
      });
    }
  });
}

exports.createKeygrip = function () {
  loadKeys().then((fetchedTextKeys) => {
    textKeys = fetchedTextKeys;
    keys = new Keygrip(textKeys);
  }).catch((err) => {
    console.warn("Could not create signing keys:", err);
  });
};

/** Returns a promise that generates a new largish ASCII random key */
function makeKey() {
  return new Promise(function (resolve, reject) {
    require('crypto').randomBytes(48, function(err, buf) {
      if (err) {
        reject(err);
        return;
      }
      resolve(buf.toString('base64'));
    });
  });
}
<|endoftext|>


<commit_before>import uri from 'url';
import crypto from 'crypto';
import { OAuth2Strategy, InternalOAuthError } from 'passport-oauth';

/**
 * `FacebookTokenStrategy` constructor.
 *
 * The Facebook authentication strategy authenticates requests by delegating to
 * Facebook using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occurred, `error` should be set.
 *
 * @param {Object} options
 * @param {Function} verify
 * @example
 * passport.use(new FacebookTokenStrategy({
 *   clientID: '123456789',
 *   clientSecret: 'shhh-its-a-secret'
 * }), (accessToken, refreshToken, profile, done) => {
 *   User.findOrCreate({facebookId: profile.id}, done);
 * });
 */
export default class FacebookTokenStrategy extends OAuth2Strategy {
    constructor(_options, _verify) {
        let options = _options || {};
        let verify = _verify;

        options.authorizationURL = options.authorizationURL || 'https://www.facebook.com/v2.4/dialog/oauth';
        options.tokenURL = options.tokenURL || 'https://graph.facebook.com/oauth/access_token';

        super(options, verify);

        this.name = 'facebook-token';
        this._accessTokenField = options.accessTokenField || 'access_token';
        this._refreshTokenField = options.refreshTokenField || 'refresh_token';
        this._profileURL = options.profileURL || 'https://graph.facebook.com/v2.4/me';
        this._profileFields = options.profileFields || ['id', 'displayName', 'name', 'emails'];
        this._clientSecret = options.clientSecret;
        this._enableProof = typeof options.enableProof === 'boolean' ? options.enableProof : true;
        this._passReqToCallback = options.passReqToCallback;
        this._oauth2.useAuthorizationHeaderforGET(false);
    }

    /**
     * Authenticate request by delegating to a service provider using OAuth 2.0.
     * @param {Object} req
     * @param {Object} options
     */
    authenticate(req, options) {
        let accessToken = this.lookup(req, this._accessTokenField);
        let refreshToken = this.lookup(req, this._refreshTokenField);

        if (!accessToken) return this.fail({ message: `You should provide ${this._accessTokenField}` });

        this._loadUserProfile(accessToken, (error, profile) => {
            if (error) return this.error(error);

            const verified = (error, user, info) => {
                if (error) return this.error(error);
                if (!user) return this.fail(info);

                return this.success(user, info);
            };

            if (this._passReqToCallback) {
                this._verify(req, accessToken, refreshToken, profile, verified);
            } else {
                this._verify(accessToken, refreshToken, profile, verified);
            }
        });
    }

    /**
     * Retrieve user profile from Facebook.
     *
     * This function constructs a normalized profile, with the following properties:
     *
     *   - `provider`         always set to `facebook`
     *   - `id`               the user's Facebook ID
     *   - `username`         the user's Facebook username
     *   - `displayName`      the user's full name
     *   - `name.familyName`  the user's last name
     *   - `name.givenName`   the user's first name
     *   - `name.middleName`  the user's middle name
     *   - `gender`           the user's gender: `male` or `female`
     *   - `profileUrl`       the URL of the profile for the user on Facebook
     *   - `emails`           the proxied or contact email address granted by the user
     *
     * @param {String} accessToken
     * @param {Function} done
     */
    userProfile(accessToken, done) {
        let url = uri.parse(this._profileURL);

        if (this._enableProof) {
            // For further details, refer to https://developers.facebook.com/docs/reference/api/securing-graph-api/
            let proof = crypto.createHmac('sha256', this._clientSecret).update(accessToken).digest('hex');
            url.search = `${url.search ? url.search + '&' : ''}appsecret_proof=${encodeURIComponent(proof) }`;
        }

        if (this._profileFields) {
            let fields = FacebookTokenStrategy.convertProfileFields(this._profileFields);
            url.search = `${url.search ? url.search + '&' : ''}fields=${fields}`;
        }

        url = uri.format(url);

        this._oauth2.get(url, accessToken, (error, body, res) => {
            if (error) return done(new InternalOAuthError('Failed to fetch user profile', error));

            try {
                let json = JSON.parse(body);
                let profile = {
                    provider: 'facebook',
                    id: json.id,
                    displayName: json.name || '',
                    name: {
                        familyName: json.last_name || '',
                        givenName: json.first_name || '',
                        middleName: json.middle_name || ''
                    },
                    gender: json.gender || '',
                    emails: [{
                        value: json.email || ''
                    }],
                    photos: [{
                        value: `https://graph.facebook.com/${json.id}/picture?type=large`
                    }],
                    _raw: body,
                    _json: json
                };

                done(null, profile);
            } catch (e) {
                done(e);
            }
        });
    }

    /**
     * Converts array of profile fields to string
     * @param {Array} _profileFields Profile fields i.e. ['id', 'email']
     * @returns {String}
     */
    static convertProfileFields(_profileFields) {
        let profileFields = _profileFields || [];
        let map = {
            'id': 'id',
            'displayName': 'name',
            'name': ['last_name', 'first_name', 'middle_name'],
            'gender': 'gender',
            'profileUrl': 'link',
            'emails': 'email',
            'photos': 'picture'
        };

        return profileFields.reduce((acc, field) => acc.concat(map[field] || field), []).join(',');
    }

    /**
    * Parses an OAuth2 RFC6750 bearer authorization token, this method additionally is RFC 2616 compliant and respects
    * case insensitive headers.
    *
    * @param {Object} req http request object
    * @returns {String} value for field within body, query, or headers
    */
    parseOAuth2Token(req) {
        const OAuth2AuthorizationField = 'Authorization';
        let headerValue = (req.headers && (req.headers[OAuth2AuthorizationField] || req.headers[OAuth2AuthorizationField.toLowerCase()]));
        return (
            headerValue && (()=>{
                const bearerRE = /Bearer\ (.*)/;
                let match = bearerRE.exec(headerValue);
                return (match && match[1]);
            })()
        );
    }

    /**
    * Performs a lookup of the param field within the request, this method handles searhing the body, query, and header.
    * Additionally this method is RFC 2616 compliant and allows for case insensitive headers. This method additionally will
    * delegate outwards to the OAuth2Token parser to validate whether a OAuth2 bearer token has been provided.
    *
    * @param {Object} req http request object
    * @param {String} field
    * @returns {String} value for field within body, query, or headers
    */
    lookup(req, field) {
        return (
            req.body && req.body[field] ||
            req.query && req.query[field] ||
            req.headers && (req.headers[field] || req.headers[field.toLowerCase()]) ||
            this.parseOAuth2Token(req)
            );
    }

}
<commit_msg>update to fix line indentation issue, articially introduced via vscode editorconfig extension not working properly<commit_after>import uri from 'url';
import crypto from 'crypto';
import { OAuth2Strategy, InternalOAuthError } from 'passport-oauth';

/**
 * `FacebookTokenStrategy` constructor.
 *
 * The Facebook authentication strategy authenticates requests by delegating to
 * Facebook using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occurred, `error` should be set.
 *
 * @param {Object} options
 * @param {Function} verify
 * @example
 * passport.use(new FacebookTokenStrategy({
 *   clientID: '123456789',
 *   clientSecret: 'shhh-its-a-secret'
 * }), (accessToken, refreshToken, profile, done) => {
 *   User.findOrCreate({facebookId: profile.id}, done);
 * });
 */
export default class FacebookTokenStrategy extends OAuth2Strategy {
  constructor(_options, _verify) {
    let options = _options || {};
    let verify = _verify;

    options.authorizationURL = options.authorizationURL || 'https://www.facebook.com/v2.4/dialog/oauth';
    options.tokenURL = options.tokenURL || 'https://graph.facebook.com/oauth/access_token';

    super(options, verify);

    this.name = 'facebook-token';
    this._accessTokenField = options.accessTokenField || 'access_token';
    this._refreshTokenField = options.refreshTokenField || 'refresh_token';
    this._profileURL = options.profileURL || 'https://graph.facebook.com/v2.4/me';
    this._profileFields = options.profileFields || ['id', 'displayName', 'name', 'emails'];
    this._clientSecret = options.clientSecret;
    this._enableProof = typeof options.enableProof === 'boolean' ? options.enableProof : true;
    this._passReqToCallback = options.passReqToCallback;
    this._oauth2.useAuthorizationHeaderforGET(false);
  }

  /**
   * Authenticate request by delegating to a service provider using OAuth 2.0.
   * @param {Object} req
   * @param {Object} options
   */
  authenticate(req, options) {
    let accessToken = this.lookup(req, this._accessTokenField);
    let refreshToken = this.lookup(req, this._refreshTokenField);

    if (!accessToken) return this.fail({ message: `You should provide ${this._accessTokenField}` });

    this._loadUserProfile(accessToken, (error, profile) => {
      if (error) return this.error(error);

      const verified = (error, user, info) => {
        if (error) return this.error(error);
        if (!user) return this.fail(info);

        return this.success(user, info);
      };

      if (this._passReqToCallback) {
        this._verify(req, accessToken, refreshToken, profile, verified);
      } else {
        this._verify(accessToken, refreshToken, profile, verified);
      }
    });
  }

  /**
   * Retrieve user profile from Facebook.
   *
   * This function constructs a normalized profile, with the following properties:
   *
   *   - `provider`         always set to `facebook`
   *   - `id`               the user's Facebook ID
   *   - `username`         the user's Facebook username
   *   - `displayName`      the user's full name
   *   - `name.familyName`  the user's last name
   *   - `name.givenName`   the user's first name
   *   - `name.middleName`  the user's middle name
   *   - `gender`           the user's gender: `male` or `female`
   *   - `profileUrl`       the URL of the profile for the user on Facebook
   *   - `emails`           the proxied or contact email address granted by the user
   *
   * @param {String} accessToken
   * @param {Function} done
   */
  userProfile(accessToken, done) {
    let url = uri.parse(this._profileURL);

    if (this._enableProof) {
      // For further details, refer to https://developers.facebook.com/docs/reference/api/securing-graph-api/
      let proof = crypto.createHmac('sha256', this._clientSecret).update(accessToken).digest('hex');
      url.search = `${url.search ? url.search + '&' : ''}appsecret_proof=${encodeURIComponent(proof) }`;
    }

    if (this._profileFields) {
      let fields = FacebookTokenStrategy.convertProfileFields(this._profileFields);
      url.search = `${url.search ? url.search + '&' : ''}fields=${fields}`;
    }

    url = uri.format(url);

    this._oauth2.get(url, accessToken, (error, body, res) => {
      if (error) return done(new InternalOAuthError('Failed to fetch user profile', error));

      try {
        let json = JSON.parse(body);
        let profile = {
          provider: 'facebook',
          id: json.id,
          displayName: json.name || '',
          name: {
            familyName: json.last_name || '',
            givenName: json.first_name || '',
            middleName: json.middle_name || ''
          },
          gender: json.gender || '',
          emails: [{
            value: json.email || ''
          }],
          photos: [{
            value: `https://graph.facebook.com/${json.id}/picture?type=large`
          }],
          _raw: body,
          _json: json
        };

        done(null, profile);
      } catch (e) {
        done(e);
      }
    });
  }

  /**
   * Converts array of profile fields to string
   * @param {Array} _profileFields Profile fields i.e. ['id', 'email']
   * @returns {String}
   */
  static convertProfileFields(_profileFields) {
    let profileFields = _profileFields || [];
    let map = {
      'id': 'id',
      'displayName': 'name',
      'name': ['last_name', 'first_name', 'middle_name'],
      'gender': 'gender',
      'profileUrl': 'link',
      'emails': 'email',
      'photos': 'picture'
    };

    return profileFields.reduce((acc, field) => acc.concat(map[field] || field), []).join(',');
  }

  /**
  * Parses an OAuth2 RFC6750 bearer authorization token, this method additionally is RFC 2616 compliant and respects
  * case insensitive headers.
  *
  * @param {Object} req http request object
  * @returns {String} value for field within body, query, or headers
  */
  parseOAuth2Token(req) {
    const OAuth2AuthorizationField = 'Authorization';
    let headerValue = (req.headers && (req.headers[OAuth2AuthorizationField] || req.headers[OAuth2AuthorizationField.toLowerCase()]));
    return (
      headerValue && (() => {
        const bearerRE = /Bearer\ (.*)/;
        let match = bearerRE.exec(headerValue);
        return (match && match[1]);
      })()
      );
  }

  /**
  * Performs a lookup of the param field within the request, this method handles searhing the body, query, and header.
  * Additionally this method is RFC 2616 compliant and allows for case insensitive headers. This method additionally will
  * delegate outwards to the OAuth2Token parser to validate whether a OAuth2 bearer token has been provided.
  *
  * @param {Object} req http request object
  * @param {String} field
  * @returns {String} value for field within body, query, or headers
  */
  lookup(req, field) {
    return (
      req.body && req.body[field] ||
      req.query && req.query[field] ||
      req.headers && (req.headers[field] || req.headers[field.toLowerCase()]) ||
      this.parseOAuth2Token(req)
      );
  }

}
<|endoftext|>


<commit_before>
import urlToBase64 from 'imageurl-base64-revolunet';
import { defer } from 'Q';

class ImagesCache {
  constructor() {
    this.cache = {};
  }
  /**
   * use imageurl-base64 to convert an url to its base64 and return promise.
   * @method _addUrlToCache
   * @param  {String}       url url to the ressource
   * @return {Promise}          return a promise that resolve on success and rejects on error
   */
  _addUrlToCache(url) {
    let deferred = defer();
    urlToBase64({
      url: url,
      withCredentials: false
    }, function(err, data) {
      if (err) {
        //console.error('unable to load ' + url, err);
        deferred.reject(err);
        return;
      }
      deferred.resolve(data);
    });
    return deferred.promise;
  }
  /**
   * load in cache a bunch of urls
   * @method loa
   * @param  {Array|String} urls list of urls, or single url to cache
   * @return {Promise}  return a promise with progress({loaded: x, total: y}) and resolved when all images loaded
   */
  load(urls) {
    if (typeof urls === 'string') {
      urls = [urls];
    }
    const nbImages = urls.length;
    let nbImagesLoaded = 0;
    let deferred = defer();

    function urlLoaded() {
      nbImagesLoaded++;
      deferred.notify({
        loaded: nbImagesLoaded,
        total: nbImages
      });
      if (nbImagesLoaded === nbImages) {
        deferred.resolve();
      }
    }

    urls.forEach(url => {
      if (!this.cache[url]) {
        // add resource to cache
        // always increment counter, even when image load failed
        this._addUrlToCache(url).then(result => {
          this.cache[url] = result.dataUri;
          urlLoaded();
        }).catch(e => {
          urlLoaded();
        })
      } else {
        // also notify when image already in cache
        urlLoaded();
      }
    });
    return deferred.promise;
    // optionaly cache on FS or whatever
    // handle http:// urls
    // handle bundle:// urls for cordova bundled files
  }
  get(url, addToCache=true) {
    let cached;
    if (cached = this.cache[url]) {
      return cached;
    } else {
      if (addToCache) {
        // todo : add to cache
      }
      return url;
    }
  }
  clear() {
    this.cache = {};
  }
}

const imagesCache = new ImagesCache();

export default imagesCache;
<commit_msg>fix: use DOM and Image+canvas for b64 conversion<commit_after>
import { defer } from 'q';
import request from 'request';

import image2base64 from 'image2base64';

require('request').debug = true

// most little pixel to prevent safari leak, see http://www.fngtps.com/2010/mobile-safari-image-resource-limit-workaround/
const PICO_PIXEL = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';

/**
 * convert an url to its base64 value and return promise
 * we use canvas here due to strange browserify+buffer issue, see https://gist.github.com/revolunet/4417e4168ae2879a3604
 * @method getUrlAsBase64
 * @param  {String}       url url if the ressource
 * @return {Promise}          return a promise that resolve on success with b64 data and rejects on error
 */
function getUrlAsBase64(url) {
  let deferred = defer();
  var img = new Image();
  img.onload = function() {
    deferred.resolve(image2base64(img));
    img.onload = img.onerror = null;
    img.src = PICO_PIXEL;
    img = null;
  }
  img.onerror = function() {
    deferred.reject();
    img.onload = img.onerror = null;
    img.src = PICO_PIXEL;
    img = null;
  };
  img.src = url;
  return deferred.promise;
}

class ImagesCache {
  constructor() {
    this.cache = {};
  }

  /**
   * load in cache a bunch of urls
   * @method loa
   * @param  {Array|String} urls list of urls, or single url to cache
   * @return {Promise}  return a promise with progress({loaded: x, total: y}) and resolved when all images loaded
   */
  load(urls) {
    if (typeof urls === 'string') {
      urls = [urls];
    }
    const nbImages = urls.length;
    let nbImagesLoaded = 0;
    let deferred = defer();

    function urlLoaded() {
      nbImagesLoaded++;
      deferred.notify({
        loaded: nbImagesLoaded,
        total: nbImages
      });
      if (nbImagesLoaded === nbImages) {
        deferred.resolve();
      }
    }

    urls.forEach(url => {
      if (!this.cache[url]) {
        // add resource to cache
        // always increment counter, even when image load failed
        getUrlAsBase64(url).then(b64 => {
          this.cache[url] = b64;
          urlLoaded();
        }).catch(e => {
          urlLoaded();
        })
      } else {
        // also notify when image already in cache
        urlLoaded();
      }
    });
    return deferred.promise;
    // optionaly cache on FS or whatever
    // handle http:// urls
    // handle bundle:// urls for cordova bundled files
  }
  get(url, addToCache=true) {
    let cached;
    if (cached = this.cache[url]) {
      return cached;
    } else {
      if (addToCache) {
        // todo : add to cache
      }
      return url;
    }
  }
  clear() {
    this.cache = {};
  }
}

const imagesCache = new ImagesCache();

export default imagesCache;
<|endoftext|>


<commit_before>const Promise = require('bluebird');
const redis = Promise.promisifyAll(require('redis'));
const client = redis.createClient();

const addToQueue = (task, UPC) => client.lpushAsync(task, UPC);

const checkQueue = (task) => client.llenAsync(task);

const removeQueue = (task) => client.rpopAsync(task);

const storeProductInfo = (UPC, info) =>
  client.hmsetAsync(`product:${UPC}`, 'productInfo', JSON.stringify(info));

const getProductInfo = (UPC) => client.hgetAsync(`product:${UPC}`, 'productInfo');

const removeProductInfo = (UPC) => client.delAsync(`product:${UPC}`);

const adjustNumber = (num) => {
  const digits = Math.ceil(Number(num)).toString();
  let adjustedNumber;
  if (digits.length < 4) {
    if (digits.length === 3) {
      adjustedNumber = `0${digits}`;
    } else if (digits.length === 2) {
      adjustedNumber = `00${digits}`;
    } else if (digits.length === 1) {
      adjustedNumber = `000${digits}`;
    }
  }
  return adjustedNumber;
};

const sortProductByCategory = (key, category, nutrientLevel, UPC) =>
  client.zaddAsync(`sortByCategory:${key}`, 0, `${category}:${nutrientLevel}:${UPC}`);

const getProductWithBetterNutrients = (quality, categoryField, category, nutrientLevel) => {
  let command;
  if (quality === 'Good') {
    command = client.zrangebylexAsync(
      `sortByCategory:${categoryField}`,
      `[${category}:${nutrientLevel}`, `[${category}:9999`
    );
  } else {
    command = client.zrangebylexAsync(
      `sortByCategory:${categoryField}`,
      `[${category}:0000`, `[${category}:${nutrientLevel}`
    );
  }
  return command;
};

const sortProductByNutrientLevel = (key, nutrientLevel, category, UPC) =>
  client.zaddAsync(`sortByLevel:${key}`, nutrientLevel, `${category}:${UPC}`);

const setAverageCategoryNutrientLevel = (category, key, nutrientLevel, numberOfProducts) =>
  client.hmsetAsync(
    `category:${category}`, key, nutrientLevel, `${key}Products`, numberOfProducts
  );

const getAverageCategoryNutrientLevel = (category, key) =>
  client.hmgetAsync(`category:${category}`, key, `${key}Products`);

const getAllCategoryNutrientLevel = (category) =>
  client.hgetallAsync(`category:${category}`);

const storeRecommendation = (UPC, JSONObject) =>
  client.hsetAsync('recommendation', UPC, JSONObject);

const getRecommendation = (UPC) =>
  client.hgetAsync('recommendation', UPC);

const removeRecommendations = () => {
  console.log("removing recommendations")
  client.delAsync('recommendation');
}

const checkIfBadOrGoodNutrient = (categoryField) => {
  let result = false;
  if (
    categoryField === 'fiber' ||
    categoryField === 'protein' ||
    categoryField.substring(0, 7) === 'vitamin' ||
    categoryField === 'calcium' ||
    categoryField === 'iron' ||
    categoryField === 'potassium' ||
    categoryField === 'biotin' ||
    categoryField === 'pantothenicacid' ||
    categoryField === 'magnesium'
  ) {
    result = 'Good';
  } else if (
    categoryField === 'cholesterol' ||
    categoryField === 'sodium' ||
    categoryField === 'energy' ||
    categoryField === 'fat' ||
    categoryField === 'saturatedfat' ||
    categoryField === 'carbohydrates' ||
    categoryField === 'salt' ||
    categoryField === 'caffeine'
  ) {
    result = 'Bad';
  }
  return result;
};

const checkDV = (nutrient) => {
  let DV;
  if (nutrient === 'energy') {
    DV = 2000;
  } else if (nutrient === 'fat') {
    DV = 65;
  } else if (nutrient === 'sodium') {
    DV = 2400;
  } else if (nutrient === 'saturatedfat') {
    DV = 20;
  } else if (nutrient === 'cholesterol') {
    DV = 300;
  } else if (nutrient === 'carbohydrates') {
    DV = 300;
  } else if (nutrient === 'fiber') {
    DV = 25;
  } else if (nutrient === 'protein') {
    DV = 50;
  } else if (nutrient === 'vitamina') {
    DV = 5000;
  } else if (nutrient === 'vitaminc') {
    DV = 60;
  } else if (nutrient === 'vitamind') {
    DV = 400;
  } else if (nutrient === 'vitamine') {
    DV = 30;
  } else if (nutrient === 'vitamink') {
    DV = 80;
  } else if (nutrient === 'vitaminb6') {
    DV = 2;
  } else if (nutrient === 'vitaminb12') {
    DV = 6;
  } else if (nutrient === 'biotin') {
    DV = 300;
  } else if (nutrient === 'pantothenicacid') {
    DV = 10;
  } else if (nutrient === 'potassium') {
    DV = 3500;
  } else if (nutrient === 'calcium') {
    DV = 1000;
  } else if (nutrient === 'phosphorus') {
    DV = 1000;
  } else if (nutrient === 'iron') {
    DV = 18;
  } else if (nutrient === 'magnesium') {
    DV = 400;
  } else if (nutrient === 'zinc') {
    DV = 15;
  } else if (nutrient === 'manganese') {
    DV = 2;
  } else if (nutrient === 'selenium') {
    DV = 70;
  } else if (nutrient === 'chromium') {
    DV = 120;
  } else if (nutrient === 'molybdenum') {
    DV = 75;
  } else if (nutrient === 'iodine') {
    DV = 150;
  } else {
    DV = null;
  }
  return DV;
};

module.exports = {
  addToQueue,
  checkQueue,
  removeQueue,
  storeProductInfo,
  getProductInfo,
  removeProductInfo,
  adjustNumber,
  sortProductByCategory,
  getProductWithBetterNutrients,
  sortProductByNutrientLevel,
  setAverageCategoryNutrientLevel,
  getAverageCategoryNutrientLevel,
  getAllCategoryNutrientLevel,
  storeRecommendation,
  getRecommendation,
  removeRecommendations,
  checkIfBadOrGoodNutrient,
  checkDV,
};
<commit_msg>clean up lint<commit_after>const Promise = require('bluebird');
const redis = Promise.promisifyAll(require('redis'));
const client = redis.createClient();

const addToQueue = (task, UPC) => client.lpushAsync(task, UPC);

const checkQueue = (task) => client.llenAsync(task);

const removeQueue = (task) => client.rpopAsync(task);

const storeProductInfo = (UPC, info) =>
  client.hmsetAsync(`product:${UPC}`, 'productInfo', JSON.stringify(info));

const getProductInfo = (UPC) => client.hgetAsync(`product:${UPC}`, 'productInfo');

const removeProductInfo = (UPC) => client.delAsync(`product:${UPC}`);

const adjustNumber = (num) => {
  const digits = Math.ceil(Number(num)).toString();
  let adjustedNumber;
  if (digits.length < 4) {
    if (digits.length === 3) {
      adjustedNumber = `0${digits}`;
    } else if (digits.length === 2) {
      adjustedNumber = `00${digits}`;
    } else if (digits.length === 1) {
      adjustedNumber = `000${digits}`;
    }
  }
  return adjustedNumber;
};

const sortProductByCategory = (key, category, nutrientLevel, UPC) =>
  client.zaddAsync(`sortByCategory:${key}`, 0, `${category}:${nutrientLevel}:${UPC}`);

const getProductWithBetterNutrients = (quality, categoryField, category, nutrientLevel) => {
  let command;
  if (quality === 'Good') {
    command = client.zrangebylexAsync(
      `sortByCategory:${categoryField}`,
      `[${category}:${nutrientLevel}`, `[${category}:9999`
    );
  } else {
    command = client.zrangebylexAsync(
      `sortByCategory:${categoryField}`,
      `[${category}:0000`, `[${category}:${nutrientLevel}`
    );
  }
  return command;
};

const sortProductByNutrientLevel = (key, nutrientLevel, category, UPC) =>
  client.zaddAsync(`sortByLevel:${key}`, nutrientLevel, `${category}:${UPC}`);

const setAverageCategoryNutrientLevel = (category, key, nutrientLevel, numberOfProducts) =>
  client.hmsetAsync(
    `category:${category}`, key, nutrientLevel, `${key}Products`, numberOfProducts
  );

const getAverageCategoryNutrientLevel = (category, key) =>
  client.hmgetAsync(`category:${category}`, key, `${key}Products`);

const getAllCategoryNutrientLevel = (category) =>
  client.hgetallAsync(`category:${category}`);

const storeRecommendation = (UPC, JSONObject) =>
  client.hsetAsync('recommendation', UPC, JSONObject);

const getRecommendation = (UPC) =>
  client.hgetAsync('recommendation', UPC);

const removeRecommendations = () => {
  console.log('removing recommendations');
  client.delAsync('recommendation');
};

const checkIfBadOrGoodNutrient = (categoryField) => {
  let result = false;
  if (
    categoryField === 'fiber' ||
    categoryField === 'protein' ||
    categoryField.substring(0, 7) === 'vitamin' ||
    categoryField === 'calcium' ||
    categoryField === 'iron' ||
    categoryField === 'potassium' ||
    categoryField === 'biotin' ||
    categoryField === 'pantothenicacid' ||
    categoryField === 'magnesium'
  ) {
    result = 'Good';
  } else if (
    categoryField === 'cholesterol' ||
    categoryField === 'sodium' ||
    categoryField === 'energy' ||
    categoryField === 'fat' ||
    categoryField === 'saturatedfat' ||
    categoryField === 'carbohydrates' ||
    categoryField === 'salt' ||
    categoryField === 'caffeine'
  ) {
    result = 'Bad';
  }
  return result;
};

const checkDV = (nutrient) => {
  let DV;
  if (nutrient === 'energy') {
    DV = 2000;
  } else if (nutrient === 'fat') {
    DV = 65;
  } else if (nutrient === 'sodium') {
    DV = 2400;
  } else if (nutrient === 'saturatedfat') {
    DV = 20;
  } else if (nutrient === 'cholesterol') {
    DV = 300;
  } else if (nutrient === 'carbohydrates') {
    DV = 300;
  } else if (nutrient === 'fiber') {
    DV = 25;
  } else if (nutrient === 'protein') {
    DV = 50;
  } else if (nutrient === 'vitamina') {
    DV = 5000;
  } else if (nutrient === 'vitaminc') {
    DV = 60;
  } else if (nutrient === 'vitamind') {
    DV = 400;
  } else if (nutrient === 'vitamine') {
    DV = 30;
  } else if (nutrient === 'vitamink') {
    DV = 80;
  } else if (nutrient === 'vitaminb6') {
    DV = 2;
  } else if (nutrient === 'vitaminb12') {
    DV = 6;
  } else if (nutrient === 'biotin') {
    DV = 300;
  } else if (nutrient === 'pantothenicacid') {
    DV = 10;
  } else if (nutrient === 'potassium') {
    DV = 3500;
  } else if (nutrient === 'calcium') {
    DV = 1000;
  } else if (nutrient === 'phosphorus') {
    DV = 1000;
  } else if (nutrient === 'iron') {
    DV = 18;
  } else if (nutrient === 'magnesium') {
    DV = 400;
  } else if (nutrient === 'zinc') {
    DV = 15;
  } else if (nutrient === 'manganese') {
    DV = 2;
  } else if (nutrient === 'selenium') {
    DV = 70;
  } else if (nutrient === 'chromium') {
    DV = 120;
  } else if (nutrient === 'molybdenum') {
    DV = 75;
  } else if (nutrient === 'iodine') {
    DV = 150;
  } else {
    DV = null;
  }
  return DV;
};

module.exports = {
  addToQueue,
  checkQueue,
  removeQueue,
  storeProductInfo,
  getProductInfo,
  removeProductInfo,
  adjustNumber,
  sortProductByCategory,
  getProductWithBetterNutrients,
  sortProductByNutrientLevel,
  setAverageCategoryNutrientLevel,
  getAverageCategoryNutrientLevel,
  getAllCategoryNutrientLevel,
  storeRecommendation,
  getRecommendation,
  removeRecommendations,
  checkIfBadOrGoodNutrient,
  checkDV,
};
<|endoftext|>


<commit_before>import 'aurelia-polyfills';
import {PLATFORM, isInitialized} from 'aurelia-pal';

let bootstrapQueue = [];
let sharedLoader = null;
let Aurelia = null;
const host = PLATFORM.global;
const isNodeLike = typeof process !== 'undefined' && !process.browser;

function onBootstrap(callback) {
  return new Promise((resolve, reject) => {
    if (sharedLoader) {
      resolve(callback(sharedLoader));
    } else {
      bootstrapQueue.push(() => {
        try {
          resolve(callback(sharedLoader));
        } catch (e) {
          reject(e);
        }
      });
    }
  });
}

function ready() {
  return new Promise((resolve, reject) => {
    if (!host.document || host.document.readyState === 'complete') {
      resolve();
    } else {
      host.document.addEventListener('DOMContentLoaded', completed);
      host.addEventListener('load', completed);
    }

    function completed() {
      host.document.removeEventListener('DOMContentLoaded', completed);
      host.removeEventListener('load', completed);
      resolve();
    }
  });
}

function createLoader() {
  // Custom Loader Support
  if (PLATFORM.Loader) {
    return Promise.resolve(new PLATFORM.Loader());
  }

  // Webpack Loader Support
  if (typeof __webpack_require__ !== 'undefined') {
    // Webpack needs the require to be top level to parse the request.
    // However, we don't want to use require or that will cause the Babel
    // transpiler to detect an incorrect dependency.
    const m = __webpack_require__(require.resolve('aurelia-loader-webpack'));
    return Promise.resolve(new m.WebpackLoader());
  }

  // SystemJS Loader Support
  if (host.System && typeof host.System.config === 'function') {
    return host.System.normalize('aurelia-bootstrapper').then(bsn => {
      return host.System.normalize('aurelia-loader-default', bsn);
    }).then(loaderName => {
      return host.System.import(loaderName).then(m => new m.DefaultLoader());
    });
  }

  // AMD Module Loader Support
  if (typeof host.require === 'function' && typeof host.require.version === 'string') {
    return new Promise((resolve, reject) => host.require(['aurelia-loader-default'], m => resolve(new m.DefaultLoader()), reject));
  }

  // Node.js and Electron Support
  if (isNodeLike && typeof module !== 'undefined' && typeof module.require !== 'undefined') {
    // note: we use a scoped module.require() instead of simply require()
    // so that Webpack's parser does not automatically include this loader as a dependency,
    // similarly to the non-global call to System.import() above
    const m = module.require('aurelia-loader-nodejs');
    return Promise.resolve(new m.NodeJsLoader());
  }

  return Promise.reject('No PLATFORM.Loader is defined and there is neither a System API (ES6) or a Require API (AMD) globally available to load your app.');
}

function initializePal(loader) {
  let type;

  var isRenderer = isNodeLike && (process.type === 'renderer' || process.versions['node-webkit']);

  if (isNodeLike && !isRenderer) {
    type = 'nodejs';
  } else if (typeof window !== 'undefined') {
    type = 'browser';
  } else if (typeof self !== 'undefined') {
    type = 'worker';
  } else {
    throw new Error('Could not determine platform implementation to load.');
  }

  return loader.loadModule('aurelia-pal-' + type)
    .then(palModule => type === 'nodejs' && !isInitialized && palModule.globalize() || palModule.initialize());
}

function preparePlatform(loader) {
  return initializePal(loader)
    .then(() => loader.normalize('aurelia-bootstrapper'))
    .then(bootstrapperName => {
      return loader.normalize('aurelia-framework', bootstrapperName)
        .then(frameworkName => {
          loader.map('aurelia-framework', frameworkName);

          return Promise.all([
            loader.normalize('aurelia-dependency-injection', frameworkName)
              .then(diName => loader.map('aurelia-dependency-injection', diName)),
            loader.normalize('aurelia-router', bootstrapperName)
              .then(routerName => loader.map('aurelia-router', routerName)),
            loader.normalize('aurelia-logging-console', bootstrapperName)
              .then(loggingConsoleName => loader.map('aurelia-logging-console', loggingConsoleName))
          ]).then(() => {
            return loader.loadModule(frameworkName).then(m => Aurelia = m.Aurelia);
          });
        });
    });
}

function handleApp(loader, appHost) {
  const moduleId = appHost.getAttribute('aurelia-app') || appHost.getAttribute('data-aurelia-app');
  return config(loader, appHost, moduleId);
}

function config(loader, appHost, configModuleId) {
  const aurelia = new Aurelia(loader);
  aurelia.host = appHost;
  aurelia.configModuleId = configModuleId || null;

  if (configModuleId) {
    return loader.loadModule(configModuleId).then(customConfig => {
      if (!customConfig.configure) {
        throw new Error("Cannot initialize module '" + configModuleId + "' without a configure function.");
      }

      customConfig.configure(aurelia);
    });
  }

  aurelia.use
    .standardConfiguration()
    .developmentLogging();

  return aurelia.start().then(() => aurelia.setRoot());
}

function run() {
  return ready()
    .then(() => createLoader())
    .then(loader => {
      return preparePlatform(loader).then(() => {
        const appHost = host.document.querySelectorAll('[aurelia-app],[data-aurelia-app]');
        const toConsole = console.error.bind(console);

        for (let i = 0, ii = appHost.length; i < ii; ++i) {
          handleApp(loader, appHost[i]).catch(toConsole);
        }

        sharedLoader = loader;
        for (let i = 0, ii = bootstrapQueue.length; i < ii; ++i) {
          bootstrapQueue[i]();
        }
        bootstrapQueue = null;
      });
    });
}

/**
 * Manually bootstraps an application.
 * @param configure A callback which passes an Aurelia instance to the developer to manually configure and start up the app.
 * @return A Promise that completes when configuration is done.
 */
export function bootstrap(configure: Function): Promise<void> {
  return onBootstrap(loader => {
    const aurelia = new Aurelia(loader);
    return configure(aurelia);
  });
}

/**
 * A promise that represents the bootstrapper's startup process.
 * It resolves when the process has finished starting.
 */
export const starting = run();
<commit_msg>silly mistake<commit_after>import 'aurelia-polyfills';
import {PLATFORM, isInitialized} from 'aurelia-pal';

let bootstrapQueue = [];
let sharedLoader = null;
let Aurelia = null;
const host = PLATFORM.global;
const isNodeLike = typeof process !== 'undefined' && !process.browser;

function onBootstrap(callback) {
  return new Promise((resolve, reject) => {
    if (sharedLoader) {
      resolve(callback(sharedLoader));
    } else {
      bootstrapQueue.push(() => {
        try {
          resolve(callback(sharedLoader));
        } catch (e) {
          reject(e);
        }
      });
    }
  });
}

function ready() {
  return new Promise((resolve, reject) => {
    if (!host.document || host.document.readyState === 'complete') {
      resolve();
    } else {
      host.document.addEventListener('DOMContentLoaded', completed);
      host.addEventListener('load', completed);
    }

    function completed() {
      host.document.removeEventListener('DOMContentLoaded', completed);
      host.removeEventListener('load', completed);
      resolve();
    }
  });
}

function createLoader() {
  // Custom Loader Support
  if (PLATFORM.Loader) {
    return Promise.resolve(new PLATFORM.Loader());
  }

  // Webpack Loader Support
  if (typeof __webpack_require__ !== 'undefined') {
    // Webpack needs the require to be top level to parse the request.
    // However, we don't want to use require or that will cause the Babel
    // transpiler to detect an incorrect dependency.
    const m = __webpack_require__(require.resolve('aurelia-loader-webpack'));
    return Promise.resolve(new m.WebpackLoader());
  }

  // SystemJS Loader Support
  if (host.System && typeof host.System.config === 'function') {
    return host.System.normalize('aurelia-bootstrapper').then(bsn => {
      return host.System.normalize('aurelia-loader-default', bsn);
    }).then(loaderName => {
      return host.System.import(loaderName).then(m => new m.DefaultLoader());
    });
  }

  // AMD Module Loader Support
  if (typeof host.require === 'function' && typeof host.require.version === 'string') {
    return new Promise((resolve, reject) => host.require(['aurelia-loader-default'], m => resolve(new m.DefaultLoader()), reject));
  }

  // Node.js and Electron Support
  if (isNodeLike && typeof module !== 'undefined' && typeof module.require !== 'undefined') {
    // note: we use a scoped module.require() instead of simply require()
    // so that Webpack's parser does not automatically include this loader as a dependency,
    // similarly to the non-global call to System.import() above
    const m = module.require('aurelia-loader-nodejs');
    return Promise.resolve(new m.NodeJsLoader());
  }

  return Promise.reject('No PLATFORM.Loader is defined and there is neither a System API (ES6) or a Require API (AMD) globally available to load your app.');
}

function initializePal(loader) {
  let type;

  const isRenderer = isNodeLike && (process.type === 'renderer' || process.versions['node-webkit']);

  if (isNodeLike && !isRenderer) {
    type = 'nodejs';
  } else if (typeof window !== 'undefined') {
    type = 'browser';
  } else if (typeof self !== 'undefined') {
    type = 'worker';
  } else {
    throw new Error('Could not determine platform implementation to load.');
  }

  return loader.loadModule('aurelia-pal-' + type)
    .then(palModule => type === 'nodejs' && !isInitialized && palModule.globalize() || palModule.initialize());
}

function preparePlatform(loader) {
  return initializePal(loader)
    .then(() => loader.normalize('aurelia-bootstrapper'))
    .then(bootstrapperName => {
      return loader.normalize('aurelia-framework', bootstrapperName)
        .then(frameworkName => {
          loader.map('aurelia-framework', frameworkName);

          return Promise.all([
            loader.normalize('aurelia-dependency-injection', frameworkName)
              .then(diName => loader.map('aurelia-dependency-injection', diName)),
            loader.normalize('aurelia-router', bootstrapperName)
              .then(routerName => loader.map('aurelia-router', routerName)),
            loader.normalize('aurelia-logging-console', bootstrapperName)
              .then(loggingConsoleName => loader.map('aurelia-logging-console', loggingConsoleName))
          ]).then(() => {
            return loader.loadModule(frameworkName).then(m => Aurelia = m.Aurelia);
          });
        });
    });
}

function handleApp(loader, appHost) {
  const moduleId = appHost.getAttribute('aurelia-app') || appHost.getAttribute('data-aurelia-app');
  return config(loader, appHost, moduleId);
}

function config(loader, appHost, configModuleId) {
  const aurelia = new Aurelia(loader);
  aurelia.host = appHost;
  aurelia.configModuleId = configModuleId || null;

  if (configModuleId) {
    return loader.loadModule(configModuleId).then(customConfig => {
      if (!customConfig.configure) {
        throw new Error("Cannot initialize module '" + configModuleId + "' without a configure function.");
      }

      customConfig.configure(aurelia);
    });
  }

  aurelia.use
    .standardConfiguration()
    .developmentLogging();

  return aurelia.start().then(() => aurelia.setRoot());
}

function run() {
  return ready()
    .then(() => createLoader())
    .then(loader => {
      return preparePlatform(loader).then(() => {
        const appHost = host.document.querySelectorAll('[aurelia-app],[data-aurelia-app]');
        const toConsole = console.error.bind(console);

        for (let i = 0, ii = appHost.length; i < ii; ++i) {
          handleApp(loader, appHost[i]).catch(toConsole);
        }

        sharedLoader = loader;
        for (let i = 0, ii = bootstrapQueue.length; i < ii; ++i) {
          bootstrapQueue[i]();
        }
        bootstrapQueue = null;
      });
    });
}

/**
 * Manually bootstraps an application.
 * @param configure A callback which passes an Aurelia instance to the developer to manually configure and start up the app.
 * @return A Promise that completes when configuration is done.
 */
export function bootstrap(configure: Function): Promise<void> {
  return onBootstrap(loader => {
    const aurelia = new Aurelia(loader);
    return configure(aurelia);
  });
}

/**
 * A promise that represents the bootstrapper's startup process.
 * It resolves when the process has finished starting.
 */
export const starting = run();
<|endoftext|>


<commit_before>'use strict';

const Joi = require('joi');
const ServiceTester = require('./runner/service-tester');
const { isVPlusDottedVersionAtLeastOne } = require('./helpers/validators');

const isBowerPrereleaseVersion = Joi.string().regex(/^v\d+(\.\d+)?(\.\d+)?(-?[.\w\d])+?$/);

const t = new ServiceTester({ id: 'bower', title: 'Bower' });
module.exports = t;

t.create('licence')
  .get('/l/bootstrap.json')
  .expectJSON({ name: 'bower', value: 'MIT' });

t.create('custom label for licence')
  .get('/l/bootstrap.json?label="my licence"')
  .expectJSON({ name: 'my licence', value: 'MIT' });

t.create('version')
  .get('/v/bootstrap.json')
  .expectJSONTypes(Joi.object().keys({
    name: 'bower',
    value: isVPlusDottedVersionAtLeastOne
  }));

t.create('custom label for version')
  .get('/v/bootstrap.json?label="my version"')
  .expectJSONTypes(Joi.object().keys({
    name: 'my version',
    value: isVPlusDottedVersionAtLeastOne
  }));

t.create('pre version') // e.g. bower|v0.2.5-alpha-rc-pre
  .get('/vpre/bootstrap.json')
  .expectJSONTypes(Joi.object().keys({
    name: 'bower',
    value: isBowerPrereleaseVersion
  }));

t.create('custom label for pre version') // e.g. pre version|v0.2.5-alpha-rc-pre
  .get('/vpre/bootstrap.json?label="pre version"')
  .expectJSONTypes(Joi.object().keys({
    name: 'pre version',
    value: isBowerPrereleaseVersion
  }));

t.create('Version for Invaild Package')
  .get('/v/it-is-a-invalid-package-should-error.json')
  .expectJSON({ name: 'bower', value: 'invalid' });

t.create('Pre Version for Invaild Package')
  .get('/vpre/it-is-a-invalid-package-should-error.json')
  .expectJSON({ name: 'bower', value: 'invalid' });

t.create('licence for Invaild Package')
  .get('/l/it-is-a-invalid-package-should-error.json')
  .expectJSON({ name: 'bower', value: 'invalid' });

t.create('Version label should be `no releases` if no offical version')
  .get('/v/bootstrap.json')
  .intercept(nock => nock('https://libraries.io')
    .get('/api/bower/bootstrap')
    .reply(200, { latest_stable_release: { name: null } })) // or just `{}`
  .expectJSON({ name: 'bower', value: 'no releases' });
<commit_msg>[FIX] Bower service tests (#1383)<commit_after>'use strict';

const Joi = require('joi');
const ServiceTester = require('./runner/service-tester');
const { isVPlusDottedVersionAtLeastOne } = require('./helpers/validators');

const isBowerPrereleaseVersion = Joi.string().regex(/^v\d+(\.\d+)?(\.\d+)?(-?[.\w\d])+?$/);

const t = new ServiceTester({ id: 'bower', title: 'Bower' });
module.exports = t;

t.create('licence')
  .get('/l/bootstrap.json')
  .expectJSON({ name: 'bower', value: 'MIT' });

t.create('custom label for licence')
  .get('/l/bootstrap.json?label=my licence')
  .expectJSON({ name: 'my licence', value: 'MIT' });

t.create('version')
  .get('/v/bootstrap.json')
  .expectJSONTypes(Joi.object().keys({
    name: 'bower',
    value: isVPlusDottedVersionAtLeastOne
  }));

t.create('custom label for version')
  .get('/v/bootstrap.json?label=my version')
  .expectJSONTypes(Joi.object().keys({
    name: 'my version',
    value: isVPlusDottedVersionAtLeastOne
  }));

t.create('pre version') // e.g. bower|v0.2.5-alpha-rc-pre
  .get('/vpre/bootstrap.json')
  .expectJSONTypes(Joi.object().keys({
    name: 'bower',
    value: isBowerPrereleaseVersion
  }));

t.create('custom label for pre version') // e.g. pre version|v0.2.5-alpha-rc-pre
  .get('/vpre/bootstrap.json?label=pre version')
  .expectJSONTypes(Joi.object().keys({
    name: 'pre version',
    value: isBowerPrereleaseVersion
  }));

t.create('Version for Invaild Package')
  .get('/v/it-is-a-invalid-package-should-error.json')
  .expectJSON({ name: 'bower', value: 'invalid' });

t.create('Pre Version for Invaild Package')
  .get('/vpre/it-is-a-invalid-package-should-error.json')
  .expectJSON({ name: 'bower', value: 'invalid' });

t.create('licence for Invaild Package')
  .get('/l/it-is-a-invalid-package-should-error.json')
  .expectJSON({ name: 'bower', value: 'invalid' });

t.create('Version label should be `no releases` if no offical version')
  .get('/v/bootstrap.json')
  .intercept(nock => nock('https://libraries.io')
    .get('/api/bower/bootstrap')
    .reply(200, { latest_stable_release: { name: null } })) // or just `{}`
  .expectJSON({ name: 'bower', value: 'no releases' });
<|endoftext|>


<commit_before>import PropTypes from 'proptypes';
import { render, h, Component } from 'preact';

let createElement = h;

/** @TODO subclass preact's Component to do basic proptype checking. */

export { PropTypes, render, createElement, h, Component };
export default { PropTypes, render, createElement, h, Component };
<commit_msg>Add more react-friendly support for className attributes<commit_after>import PropTypes from 'proptypes';
import { render, h, Component, hooks } from 'preact';

let createElement = h;

// make className work like React's
let oldHook = hooks.vnode;

hooks.vnode = vnode => {
	if (oldHook) vnode = oldHook(vnode) || vnode;
	let { attributes } = vnode;
	if (attributes) {
		let cl = attributes.className || attributes.class;
		if (cl) {
			attributes.className = cl;
		}
	}
};

/** @TODO subclass preact's Component to do basic proptype checking. */

export { PropTypes, render, createElement, h, Component };
export default { PropTypes, render, createElement, h, Component };
<|endoftext|>


<commit_before>'use strict'

import {cyan} from 'chalk'

export function createLogger (name, logger) {
  const prefix = `[${cyan(name)}]`
  function bind (logger) {
    return logger.bind(console, prefix)
  }
  return Object.assign(bind(logger || console.log), {
    error: bind(console.error)
  })
}
<commit_msg>Use es6 default for assiging to console.log<commit_after>'use strict'

import {cyan} from 'chalk'

export function createLogger (name, logger = console.log) {
  const prefix = `[${cyan(name)}]`
  function bind (logger) {
    return logger.bind(console, prefix)
  }
  return Object.assign(bind(logger), {
    error: bind(console.error)
  })
}
<|endoftext|>


<commit_before>var Clarifai = require('clarifai');
var fetch = require('node-fetch');

const BASE = 'https://api.clarifai.com/v1/tag/?model=general-v1.3';

class App {

  constructor(id, secret) {
    this._app = new Clarifai.App(id,secret);
  }

  predictVideo(videoURL) {

    return new Promise((resolve, reject) => {

      this._app.getToken()
        .then(res => {

          const token = res.access_token;
          const url = `${BASE}&url=${videoURL}`;
          const headers = {Authorization: `Bearer ${token}`};

          fetch(url, {method: 'GET', headers: headers})
            .then((res) => {

              if (!res.ok) {
                throw new Error(res.statusText);
              }

              return res.json();

            }).then((json) => {
              const tag = json.results[0].result.tag;
              resolve(tag);
            }).catch(err => {
              reject(err); // Network connection type error
            });

        });
    });
  }

}

module.exports = App;
<commit_msg>Fix Error: UNAUTHORIZED<commit_after>var Clarifai = require('clarifai');
var fetch = require('node-fetch');

const BASE = 'https://api.clarifai.com/v1/tag/?model=general-v1.3';

class App {

  constructor(id, secret) {
    this._app = new Clarifai.App(id,secret);
  }

  predictVideo(videoURL) {

    return new Promise((resolve, reject) => {

      this._app.getToken()
        .then(res => {

          const token = res.accessToken;
          const url = `${BASE}&url=${videoURL}`;
          const headers = {Authorization: `Bearer ${token}`};

          fetch(url, {method: 'GET', headers: headers})
            .then((res) => {

              if (!res.ok) {
                throw new Error(res.statusText);
              }

              return res.json();

            }).then((json) => {
              const tag = json.results[0].result.tag;
              resolve(tag);
            }).catch(err => {
              reject(err); // Network connection type error
            });

        });
    });
  }

}

module.exports = App;
<|endoftext|>


<commit_before>let detectEnv = require('composite-detect')

import assign from 'fast.js/object/assign'
import Rx from 'rx'
import assemble from './assemble'

// TODO: we need to modify the way Jam handles the data , as we do not only return a single geometry/mesh but
// a full hierarchy etc
export default function parse (data, parameters = {}) {
  const defaults = {
    useWorker: (detectEnv.isBrowser === true)
  }
  parameters = assign({}, defaults, parameters)
  const {useWorker} = parameters

  const obs = new Rx.ReplaySubject(1)

  if (useWorker) {
    let worker = new Worker('./worker.js') // browserify

    worker.onmessage = function (event) {
      obs.onNext(event.data.data)
      obs.onNext({progress: 1, total: Math.NaN})
      obs.onCompleted()
    }
    worker.onerror = function (event) {
      obs.onError(`error: ${event.message}`)
    }

    worker.postMessage({ 'data': data })

    obs.catch(e => worker.terminate())
  } else {
    assemble(data)
      /* .last(function (data, idx, obs) {
        return data._finished === true
      })*/ // WHY U NO WORK ??
      .subscribe(function (data) {
        if (data._finished === true) {
          obs.onNext({progress: 1, total: Math.NaN})
          obs.onNext(data)
          obs.onCompleted()
        }
      })
  }

  return obs
}
<commit_msg>refactor(): started refactor/upgdrade based on existing streaming stl parser work<commit_after>import detectEnv from 'composite-detect'
import workerSpawner from './workerSpawner'
import makeStreamParser from './parseStream'
import through2 from 'through2'

/**
 * @author kaosat-dev / https://github.com/kaosat-dev
 *
 * Description: A streaming (node.js streams) parser for 3MF files
 * Optimised both for speed and low memory consumption
 *
 *
 * Limitations:
 *
**/

export default function makeParsedStream (parameters = {}) {
  const defaults = {
    useWorker: (detectEnv.isBrowser === true)
  }
  parameters = Object.assign({}, defaults, parameters)
  const {useWorker} = parameters

  return useWorker ? workerSpawner() : through2(makeStreamParser())
}

/*let detectEnv = require('composite-detect')

import assign from 'fast.js/object/assign'
import Rx from 'rx'
import assemble from './assemble'

// TODO: we need to modify the way Jam handles the data , as we do not only return a single geometry/mesh but
// a full hierarchy etc
export default function parse (data, parameters = {}) {
  const defaults = {
    useWorker: (detectEnv.isBrowser === true)
  }
  parameters = assign({}, defaults, parameters)
  const {useWorker} = parameters

  const obs = new Rx.ReplaySubject(1)

  if (useWorker) {
    let worker = new Worker('./worker.js') // browserify

    worker.onmessage = function (event) {
      obs.onNext(event.data.data)
      obs.onNext({progress: 1, total: Math.NaN})
      obs.onCompleted()
    }
    worker.onerror = function (event) {
      obs.onError(`error: ${event.message}`)
    }

    worker.postMessage({ 'data': data })

    obs.catch(e => worker.terminate())
  } else {
    assemble(data)
      .subscribe(function (data) {
        if (data._finished === true) {
          obs.onNext({progress: 1, total: Math.NaN})
          obs.onNext(data)
          obs.onCompleted()
        }
      })
  }

  return obs
}*/
<|endoftext|>