<commit_before>'use strict';

var path = require('path');
var karma = require('karma');

function normalizeOptions(options) {
	var codeGlobs = ['src/**/*.js', '!src/**/*.soy.js', 'test/**/*.js', 'gulpfile.js'];

	options = options || {};
	options.buildAmdDest = options.buildAmdDest || 'build/amd';
	options.buildGlobalsJqueryDest = options.buildGlobalsJqueryDest || 'build/globals-jquery';
	options.buildAmdJqueryDest = options.buildAmdJqueryDest || 'build/amd-jquery';
	options.buildJqueryDest = options.buildJqueryDest || 'build/jquery';
	options.bundleCssFileName = options.bundleCssFileName || 'all.css';
	options.bundleFileName = options.bundleFileName || 'metal.js';
	options.buildDest = options.buildDest || 'build/globals';
	options.buildSrc = options.buildSrc || 'src/**/*.js';
	options.cleanDir = options.cleanDir || 'build';
	options.cssDest = options.cssDest || 'build';
	options.cssSrc = options.cssSrc || 'src/**/*.css';
	options.formatGlobs = options.formatGlobs || codeGlobs;
	options.globalName = options.globalName || 'metal';
	options.jsDocConfFile = options.jsDocConfFile || path.resolve(__dirname, '../jsdoc.json');
	options.karma = options.karma || karma;
	options.lintGlobs = options.lintGlobs || codeGlobs;
	options.uglifySrc = options.uglifySrc || 'build/**/*.js';
	options.moduleName = options.moduleName || 'metal';
	options.noSoy = options.noSoy || false;
	options.scssIncludePaths = options.scssIncludePaths || ['node_modules'];
	options.scssSrc = options.scssSrc || 'src/**/*.scss';
	options.soyDest = options.soyDest || 'src';
	options.soyDeps = options.soyDest;
	options.soyLocales = options.soyLocales;
	options.soyMessageFilePathFormat = options.soyMessageFilePathFormat;
	options.soySrc = options.soySrc || 'src/**/*.soy';
	options.taskPrefix = options.taskPrefix || '';
	options.mainBuildJsTasks = options.mainBuildJsTasks || [options.taskPrefix + 'build:globals:js'];
	options.testBrowsers = options.testBrowsers || ['Chrome', 'Firefox', 'Safari', 'IE9 - Win7', 'IE10 - Win7', 'IE11 - Win7'];
	options.testNodeSrc = options.testNodeSrc || 'test/**/*.js';
	options.testSaucelabsBrowsers = options.testSaucelabsBrowsers || {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_safari: {
			base: 'SauceLabs',
			browserName: 'safari'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_ie_9: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '9'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_edge_20: {
			base: 'SauceLabs',
			browserName: 'microsoftedge',
			platform: 'Windows 10',
			version: '20'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'iphone',
			platform: 'OS X 10.10',
			version: '7.1'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	};

	return options;
}

module.exports = normalizeOptions;
<commit_msg>Fixes typo<commit_after>'use strict';

var path = require('path');
var karma = require('karma');

function normalizeOptions(options) {
	var codeGlobs = ['src/**/*.js', '!src/**/*.soy.js', 'test/**/*.js', 'gulpfile.js'];

	options = options || {};
	options.buildAmdDest = options.buildAmdDest || 'build/amd';
	options.buildGlobalsJqueryDest = options.buildGlobalsJqueryDest || 'build/globals-jquery';
	options.buildAmdJqueryDest = options.buildAmdJqueryDest || 'build/amd-jquery';
	options.buildJqueryDest = options.buildJqueryDest || 'build/jquery';
	options.bundleCssFileName = options.bundleCssFileName || 'all.css';
	options.bundleFileName = options.bundleFileName || 'metal.js';
	options.buildDest = options.buildDest || 'build/globals';
	options.buildSrc = options.buildSrc || 'src/**/*.js';
	options.cleanDir = options.cleanDir || 'build';
	options.cssDest = options.cssDest || 'build';
	options.cssSrc = options.cssSrc || 'src/**/*.css';
	options.formatGlobs = options.formatGlobs || codeGlobs;
	options.globalName = options.globalName || 'metal';
	options.jsDocConfFile = options.jsDocConfFile || path.resolve(__dirname, '../jsdoc.json');
	options.karma = options.karma || karma;
	options.lintGlobs = options.lintGlobs || codeGlobs;
	options.uglifySrc = options.uglifySrc || 'build/**/*.js';
	options.moduleName = options.moduleName || 'metal';
	options.noSoy = options.noSoy || false;
	options.scssIncludePaths = options.scssIncludePaths || ['node_modules'];
	options.scssSrc = options.scssSrc || 'src/**/*.scss';
	options.soyDest = options.soyDest || 'src';
	options.soyDeps = options.soyDeps;
	options.soyLocales = options.soyLocales;
	options.soyMessageFilePathFormat = options.soyMessageFilePathFormat;
	options.soySrc = options.soySrc || 'src/**/*.soy';
	options.taskPrefix = options.taskPrefix || '';
	options.mainBuildJsTasks = options.mainBuildJsTasks || [options.taskPrefix + 'build:globals:js'];
	options.testBrowsers = options.testBrowsers || ['Chrome', 'Firefox', 'Safari', 'IE9 - Win7', 'IE10 - Win7', 'IE11 - Win7'];
	options.testNodeSrc = options.testNodeSrc || 'test/**/*.js';
	options.testSaucelabsBrowsers = options.testSaucelabsBrowsers || {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_safari: {
			base: 'SauceLabs',
			browserName: 'safari'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_ie_9: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '9'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_edge_20: {
			base: 'SauceLabs',
			browserName: 'microsoftedge',
			platform: 'Windows 10',
			version: '20'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'iphone',
			platform: 'OS X 10.10',
			version: '7.1'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	};

	return options;
}

module.exports = normalizeOptions;
<|endoftext|>


<commit_before>// Includes
var request = require('request-promise');
var settings = require('../settings.json');

exports.jar = (settings.session_only ? {session: ''} : request.jar());

exports.errorHandler = function (err) {
  console.error(err.stack);
};

var cacheList = [];
for (var item in settings.cache) {
  if (item.indexOf('_') === -1) {
    var lower = item.toLowerCase();
    var cacheObj = {
      name: item,
      refresh: settings.cache[lower + '_' + 'refresh'],
      expire: settings.cache[item]
    };
    cacheList.push(cacheObj);
  }
}
exports.cache = require('./cache/new.js')(cacheList);
<commit_msg>Add sessionOnly option<commit_after>// Includes
var request = require('request-promise');
var settings = require('../settings.json');

var session_only = settings.session_only;
exports.sessionOnly = session_only;
exports.jar = (session_only ? {session: ''} : request.jar());

exports.errorHandler = function (err) {
  console.error(err.stack);
};

var cacheList = [];
for (var item in settings.cache) {
  if (item.indexOf('_') === -1) {
    var lower = item.toLowerCase();
    var cacheObj = {
      name: item,
      refresh: settings.cache[lower + '_' + 'refresh'],
      expire: settings.cache[item]
    };
    cacheList.push(cacheObj);
  }
}
exports.cache = require('./cache/new.js')(cacheList);
<|endoftext|>


<commit_before>/* jshint node: true  */
'use strict';

var async = require('async');
var util = require('util');
var read = require('read');
var _ = require('underscore');
var Table = require('cli-table');
var defaults = require('./defaults');

var TableFormat = {
  chars: { 'top': '' , 'top-mid': '' , 'top-left': '' , 'top-right': ''
    , 'bottom': '' , 'bottom-mid': '' , 'bottom-left': '' , 'bottom-right': ''
    , 'left': '' , 'left-mid': '' , 'mid': '' , 'mid-mid': ''
    , 'right': '' , 'right-mid': '' , 'middle': ' ' },
  style: { 'padding-left': 0, 'padding-right': 0 }
};
module.exports.TableFormat = TableFormat;

/*
 * Validate the options as if they came from a command line.
 * This will not fill in missing options -- "validate" may be used
 * to do that later.
 */
module.exports.getopts = function(argv, start, descriptor) {
  var opts = {};
  for (var i = start; i < argv.length; i++) {
    var longArg = /^--(.+)/.exec(argv[i]);
    if (longArg) {
      var longArgName = longArg[1];
      var ld = descriptor[longArgName];
      if (ld) {
        if (ld.toggle) {
          opts[longArgName] = true;
        } else if (i < (argv.length - 1)) {
          i++;
          opts[longArgName] = argv[i];

          if (ld.type === 'int') {
            opts[longArgName] = parseInt(opts[longArgName], 10);
          }

          // Set prompt
          if(ld.prompt == false){
            opts.prompt = true;
          }
        } else {
          badArg(argv[i]);
        }
      }

    }
    else {
      var shortArg = /^-([A-Za-z])/.exec(argv[i]);
      if (shortArg) {
        var shortArgName = shortArg[1];
        var longName;
        var des;
        for (var sd in descriptor) {
          des = descriptor[sd];
          if (des.shortOption === shortArgName) {
            longName = sd;
            break;
          }
        }

        if (longName) {
          if  (des.toggle) {
            opts[longName] = true;
          } else if (i < (argv.length - 1)) {
            i++;
            opts[longName] = argv[i];

            if (des.type === 'int') {
              opts[longName] = parseInt(opts[longName], 10);
            }

            // Set prompt
            if(des.prompt == false){
              opts.prompt = true;
            }
          } else {
            badArg(argv[i]);
          }
        }
      } else {
        badArg(argv[i]);
      }
    }
  }
  return opts;
};

function badArg(arg) {
  throw new Error(util.format('Unknown argument %s', arg));
}

/*
 * Given an "options" object, validate it against "descriptor."
 * Each property in "descriptor" is the name of an option, and has
 * the following possible fields:
 *   required (boolean) error if the option is not present
 *   secure (boolean) error if we must prompt in a secure way
 */
module.exports.validate = function(opts, descriptor, cb) {
  defaults.defaultOptions(opts);
  async.eachSeries(Object.getOwnPropertyNames(descriptor), function(item, done) {
    checkProperty(opts, descriptor, item, done);
  }, function(err) {
    cb(err, opts);
  });
};

function checkProperty(opts, descriptor, propName, done) {
  var desc = descriptor[propName];
  if (desc === null || desc === undefined) {
    done(new Error(util.format('Invalid property %s', propName)));
    return;
  }
  if (desc.required && !opts[propName] && (!opts.prompt && desc.prompt)) {
    if (opts.interactive) {
      var pn = (desc.name ? desc.name : propName);
      prompt(pn, desc.secure, function(err, val) {
        if (err) {
          done(err);
        } else {
          if (desc.secure === true) {
            opts[propName] = new SecureValue(val);
          } else {
            opts[propName] = val;
          }
          done();
        }
      });
    } else {
      done(new Error(util.format('Missing required option "%s"', propName)));
    }
  } else {
    if (opts[propName] && (desc.secure === true)) {
      makeSecure(opts, propName);
    }
    done();
  }
}

function prompt(name, secure, cb) {
  var opts = {
    prompt: name + ':'
  };
  if (secure) {
    opts.silent = true;
    opts.replace = '*';
  }

  read(opts, cb);
}

/*
 * Do the same thing as "validate" but without a callback, so it can be used
 * anywhere.
 */
module.exports.validateSync = function(opts, descriptor) {
  _.each(Object.getOwnPropertyNames(descriptor), function(item) {
    checkPropertySync(opts, descriptor, item);
  });
};

function checkPropertySync(opts, descriptor, propName) {
  var desc = descriptor[propName];
  if (desc === null || desc === undefined) {
    console.error(new Error(util.format('Invalid property %s', propName)));
  }
  if (desc.required && !opts[propName] && (!opts.prompt && desc.prompt)) {
    console.error(new Error(util.format('Missing required option "%s"', propName)));
  } else {
    if (opts[propName] && (desc.secure === true)) {
      makeSecure(opts, propName);
    }
  }
}

function makeSecure(opts, propName) {
  if (opts[propName] && (!(opts[propName] instanceof SecureValue))) {
    opts[propName] = new SecureValue(opts[propName]);
  }
}

/*
 * Produce some "help" text based on the descriptor.
 */
module.exports.getHelp = function(descriptor) {
  var tab = new Table(TableFormat);

  _.each(_.sortBy(_.pairs(descriptor)), function(d) {
    tab.push([d[0],
      (d[1].shortOption ? '-' + d[1].shortOption : ''),
      ((d[1].required && d[1].prompt) ? '(required)': '(optional)')]);
  });

  return tab.toString();
};

/*
 * This is a little wrapper for a secure value.
 */
function SecureValue(val) {
  if (!(this instanceof SecureValue)) {
    return new SecureValue(val);
  }
  Object.defineProperty(this, 'value', {
    configurable: false,
    enumerable: false,
    writable: false,
    value: val
  });
}

module.exports.SecureValue = SecureValue;

SecureValue.prototype.toString = function() {
  return '********';
};

SecureValue.prototype.getValue = function () {
  return this.value;
};
<commit_msg>Error out if unknown option is provided<commit_after>/* jshint node: true  */
'use strict';

var async = require('async');
var util = require('util');
var read = require('read');
var _ = require('underscore');
var Table = require('cli-table');
var defaults = require('./defaults');

var TableFormat = {
  chars: { 'top': '' , 'top-mid': '' , 'top-left': '' , 'top-right': ''
    , 'bottom': '' , 'bottom-mid': '' , 'bottom-left': '' , 'bottom-right': ''
    , 'left': '' , 'left-mid': '' , 'mid': '' , 'mid-mid': ''
    , 'right': '' , 'right-mid': '' , 'middle': ' ' },
  style: { 'padding-left': 0, 'padding-right': 0 }
};
module.exports.TableFormat = TableFormat;

/*
 * Validate the options as if they came from a command line.
 * This will not fill in missing options -- "validate" may be used
 * to do that later.
 */
module.exports.getopts = function(argv, start, descriptor) {
  var opts = {};
  for (var i = start; i < argv.length; i++) {
    var longArg = /^--(.+)/.exec(argv[i]);
    if (longArg) {
      var longArgName = longArg[1];
      var ld = descriptor[longArgName];
      if (ld) {
        if (ld.toggle) {
          opts[longArgName] = true;
        } else if (i < (argv.length - 1)) {
          i++;
          opts[longArgName] = argv[i];

          if (ld.type === 'int') {
            opts[longArgName] = parseInt(opts[longArgName], 10);
          }

          // Set prompt
          if(ld.prompt == false){
            opts.prompt = true;
          }
        } else {
          badArg(argv[i]);
        }
      }

    }
    else {
      var shortArg = /^-([A-Za-z])/.exec(argv[i]);
      if (shortArg) {
        var shortArgName = shortArg[1];
        var longName = undefined;
        var des;
        for (var sd in descriptor) {
          des = descriptor[sd];
          if (des.shortOption === shortArgName) {
            longName = sd;
            break;
          }
        }

        if (longName) {
          if  (des.toggle) {
            opts[longName] = true;
          } else if (i < (argv.length - 1)) {
            i++;
            opts[longName] = argv[i];

            if (des.type === 'int') {
              opts[longName] = parseInt(opts[longName], 10);
            }

            // Set prompt
            if(des.prompt == false){
              opts.prompt = true;
            }
          } else {
            badArg(argv[i]);
          }
        } else {
          badArg(argv[i])
        }

      } else {
        badArg(argv[i]);
      }
    }
  }
  return opts;
};

function badArg(arg) {
  throw new Error(util.format('Unknown argument %s', arg));
}

/*
 * Given an "options" object, validate it against "descriptor."
 * Each property in "descriptor" is the name of an option, and has
 * the following possible fields:
 *   required (boolean) error if the option is not present
 *   secure (boolean) error if we must prompt in a secure way
 */
module.exports.validate = function(opts, descriptor, cb) {
  defaults.defaultOptions(opts);
  async.eachSeries(Object.getOwnPropertyNames(descriptor), function(item, done) {
    checkProperty(opts, descriptor, item, done);
  }, function(err) {
    cb(err, opts);
  });
};

function checkProperty(opts, descriptor, propName, done) {
  var desc = descriptor[propName];
  if (desc === null || desc === undefined) {
    done(new Error(util.format('Invalid property %s', propName)));
    return;
  }
  if (desc.required && !opts[propName] && (!opts.prompt && desc.prompt)) {
    if (opts.interactive) {
      var pn = (desc.name ? desc.name : propName);
      prompt(pn, desc.secure, function(err, val) {
        if (err) {
          done(err);
        } else {
          if (desc.secure === true) {
            opts[propName] = new SecureValue(val);
          } else {
            opts[propName] = val;
          }
          done();
        }
      });
    } else {
      done(new Error(util.format('Missing required option "%s"', propName)));
    }
  } else {
    if (opts[propName] && (desc.secure === true)) {
      makeSecure(opts, propName);
    }
    done();
  }
}

function prompt(name, secure, cb) {
  var opts = {
    prompt: name + ':'
  };
  if (secure) {
    opts.silent = true;
    opts.replace = '*';
  }

  read(opts, cb);
}

/*
 * Do the same thing as "validate" but without a callback, so it can be used
 * anywhere.
 */
module.exports.validateSync = function(opts, descriptor) {
  _.each(Object.getOwnPropertyNames(descriptor), function(item) {
    checkPropertySync(opts, descriptor, item);
  });
};

function checkPropertySync(opts, descriptor, propName) {
  var desc = descriptor[propName];
  if (desc === null || desc === undefined) {
    console.error(new Error(util.format('Invalid property %s', propName)));
  }
  if (desc.required && !opts[propName] && (!opts.prompt && desc.prompt)) {
    console.error(new Error(util.format('Missing required option "%s"', propName)));
  } else {
    if (opts[propName] && (desc.secure === true)) {
      makeSecure(opts, propName);
    }
  }
}

function makeSecure(opts, propName) {
  if (opts[propName] && (!(opts[propName] instanceof SecureValue))) {
    opts[propName] = new SecureValue(opts[propName]);
  }
}

/*
 * Produce some "help" text based on the descriptor.
 */
module.exports.getHelp = function(descriptor) {
  var tab = new Table(TableFormat);

  _.each(_.sortBy(_.pairs(descriptor)), function(d) {
    tab.push([d[0],
      (d[1].shortOption ? '-' + d[1].shortOption : ''),
      ((d[1].required && d[1].prompt) ? '(required)': '(optional)')]);
  });

  return tab.toString();
};

/*
 * This is a little wrapper for a secure value.
 */
function SecureValue(val) {
  if (!(this instanceof SecureValue)) {
    return new SecureValue(val);
  }
  Object.defineProperty(this, 'value', {
    configurable: false,
    enumerable: false,
    writable: false,
    value: val
  });
}

module.exports.SecureValue = SecureValue;

SecureValue.prototype.toString = function() {
  return '********';
};

SecureValue.prototype.getValue = function () {
  return this.value;
};
<|endoftext|>


<commit_before>/*
 * Package Configuration Extension
 *
 * Example:
 *
 * System.packages = {
 *   jquery: {
 *     basePath: 'lib', // optionally only use a subdirectory within the package
 *     main: 'index.js', // when not set, package name is requested directly
 *     format: 'amd',
 *     defaultExtension: 'ts', // defaults to 'js', can be set to false
 *     meta: {
 *       '*.ts': {
 *         loader: 'typescript'
 *       },
 *       'vendor/sizzle.js': {
 *         format: 'global'
 *       }
 *     },
 *     map: {
 *        // map internal require('sizzle') to local require('./vendor/sizzle')
 *        sizzle: './vendor/sizzle.js',
 *        // map any internal or external require of 'jquery/vendor/another' to 'another/index.js'
 *        './vendor/another.js': './another/index.js',
 *        // test.js / test -> lib/test.js
 *        './test.js': './lib/test.js',
 *
 *        // environment-specific map configurations
 *        './index.js': {
 *          '~browser': './index-node.js'
 *        }
 *     }
 *   }
 * };
 *
 * Then:
 *   import 'jquery'                       -> jquery/index.js
 *   import 'jquery/submodule'             -> jquery/submodule.js
 *   import 'jquery/submodule.ts'          -> jquery/submodule.ts loaded as typescript
 *   import 'jquery/vendor/another'        -> another/index.js
 *
 * Detailed Behaviours
 * - main is the only property where a leading "./" can be added optionally
 * - map and defaultExtension are applied to the main
 * - defaultExtension adds the extension only if no other extension is present
 * - defaultJSExtensions applies after map when defaultExtension is not set
 * - if a meta value is available for a module, map and defaultExtension are skipped
 * - like global map, package map also applies to subpaths (sizzle/x, ./vendor/another/sub)
 * - condition module map is '@env' module in package or '@system-env' globally
 *
 * In addition, the following meta properties will be allowed to be package
 * -relative as well in the package meta config:
 *
 *   - loader
 *   - alias
 *
 *
 * Package Configuration Loading
 *
 * Not all packages may already have their configuration present in the System config
 * For these cases, a list of packageConfigPaths can be provided, which when matched against
 * a request, will first request a ".json" file by the package name to derive the package
 * configuration from. This allows dynamic loading of non-predetermined code, a key use
 * case in SystemJS.
 *
 * Example:
 *
 *   System.packageConfigPaths = ['packages/test/package.json', 'packages/*.json'];
 *
 *   // will first request 'packages/new-package/package.json' for the package config
 *   // before completing the package request to 'packages/new-package/path'
 *   System.import('packages/new-package/path');
 *
 *   // will first request 'packages/test/package.json' before the main
 *   System.import('packages/test');
 *
 * When a package matches packageConfigPaths, it will always send a config request for
 * the package configuration.
 * The package name itself is taken to be the match up to and including the last wildcard
 * or trailing slash.
 * Package config paths are ordered - matching is done based on the first match found.
 * Any existing package configurations for the package will deeply merge with the
 * package config, with the existing package configurations taking preference.
 * To opt-out of the package configuration request for a package that matches
 * packageConfigPaths, use the { loadConfig: false } package config option.
 *
 */
(function() {

  hookConstructor(function(constructor) {
    return function() {
      constructor.call(this);
      this.packages = {};
      this.packageConfigPaths = {};
    };
  });

  function getPackage(name) {
    // use most specific package
    var curPkg, curPkgLen = 0, pkgLen;
    for (var p in this.packages) {
      if (name.substr(0, p.length) === p && (name.length === p.length || name[p.length] === '/')) {
        pkgLen = p.split('/').length;
        if (pkgLen > curPkgLen) {
          curPkg = p;
          curPkgLen = pkgLen;
        }
      }
    }
    return curPkg;
  }

  function applyMap(map, name) {
    var bestMatch, bestMatchLength = 0;

    for (var p in map) {
      if (name.substr(0, p.length) == p && (name.length == p.length || name[p.length] == '/')) {
        var curMatchLength = p.split('/').length;
        if (curMatchLength <= bestMatchLength)
          continue;
        bestMatch = p;
        bestMatchLength = curMatchLength;
      }
    }

    return bestMatch;
  }

  function envMap(loader, pkgName, pkgMap, name) {
    var map = applyMap(pkgMap, name);
    var mapped = pkgMap[map];

    // conditional package map
    if (mapped) {
      if (typeof mapped == 'object') {
        return loader['import'](pkgMap['@env'] || '@system-env', pkgName)
        .then(function(env) {
          // first map condition to match is used
          for (var e in mapped) {
            var negate = e[0] == '~';

            var value = readMemberExpression(negate ? e.substr(1) : e, env);

            if (!negate && value || negate && !value)
              return mapped[e] + name.substr(map.length);
          }
        });
      }
      // normal map
      else {
        return mapped + name.substr(map.length);
      }
    }
  }

  function getBasePath(pkg) {
    // sanitize basePath
    var basePath = pkg.basePath && pkg.basePath != '.' ? pkg.basePath : '';
    if (basePath) {
      if (basePath.substr(0, 2) == './')
        basePath = basePath.substr(2);
      if (basePath[basePath.length - 1] != '/')
        basePath += '/';
    }
    return basePath;
  }

  // given the package subpath, return the resultant combined path
  // defaultExtension is only added if the path does not have
  // loader package meta or exact package meta
  function toPackagePath(pkgName, pkg, basePath, subPath, isPlugin) {
    var normalized = pkgName + '/' + basePath + subPath;

    var hasExtensionMeta = isPlugin;
    if (pkg.meta)
      getMetaMatches(pkg.meta, basePath, pkgName, normalized, function(metaPattern, matchMeta, matchDepth) {
        // exact meta or meta with any content after the last wildcard skips extension
        if (matchDepth == 0 || metaPattern.lastIndexOf('*') != metaPattern.length - 1)
          hasExtensionMeta = true;
      });

    return normalized + (hasExtensionMeta ? '' : getDefaultExtension(pkg, subPath));
  }

  function getDefaultExtension(pkg, subPath) {
    // don't apply extensions to folders or if defaultExtension = false
    if (subPath[subPath.length - 1] != '/' && pkg.defaultExtension !== false) {
      // work out what the defaultExtension is and add if not there already
      var defaultExtension = '.' + (pkg.defaultExtension || 'js');
      if (subPath.substr(subPath.length - defaultExtension.length) != defaultExtension)
        return defaultExtension;
    }
    return '';
  }

  function applyPackageConfig(normalized, pkgName, sync, isPlugin) {
    var loader = this;
    var pkg = loader.packages[pkgName];

    var basePath = getBasePath(pkg);

    // main
    if (pkgName === normalized && pkg.main)
      normalized += '/' + (pkg.main.substr(0, 2) == './' ? pkg.main.substr(2) : pkg.main);

    // allow for direct package name normalization with trailling "/" (no main)
    if (normalized.length == pkgName.length + 1 && normalized[pkgName.length] == '/')
      return normalized;

    // no submap if name is package itself
    if (normalized.length == pkgName.length)
      return normalized + (loader.defaultJSExtensions && normalized.substr(normalized.length - 3, 3) != '.js' ? '.js' : '');

    // sync normalize does not apply package map
    if (sync || !pkg.map)
      return toPackagePath(pkgName, pkg, basePath, normalized.substr(pkgName.length + 1));

    var subPath = '.' + normalized.substr(pkgName.length);

    // apply submap checking without then with defaultExtension
    return Promise.resolve(envMap(loader, pkgName, pkg.map, subPath))
    .then(function(mapped) {
      if (mapped)
        return mapped;

      var defaultExtension = isPlugin && getDefaultExtension(pkg, subPath.substr(2));
      if (defaultExtension)
        return envMap(loader, pkgName, pkg.map, subPath + defaultExtension);
    })
    .then(function(mapped) {
      if (mapped) {
        // '.' as a target is the package itself (with package main check)
        if (mapped == '.')
          return loader.normalizeSync(pkgName);
        // internal package map
        else if (mapped.substr(0, 2) == './')
          return toPackagePath(pkgName, pkg, basePath, mapped.substr(2), isPlugin);
        // global package map
        else
          return loader.normalize.call(loader, mapped);
      }
      else {
        return toPackagePath(pkgName, pkg, basePath, normalized.substr(pkgName.length + 1), isPlugin);
      }
    });
  }

  var packageConfigPathsRegExps = {};
  var pkgConfigPromises = {};
  function createPackageNormalize(normalize, sync) {
    return function(name, parentName, isPlugin) {
      isPlugin = isPlugin === true;

      // apply contextual package map first
      if (parentName) {
        var parentPackage = getPackage.call(this, parentName) ||
            this.defaultJSExtensions && parentName.substr(parentName.length - 3, 3) == '.js' &&
            getPackage.call(this, parentName.substr(0, parentName.length - 3));
      }

      if (parentPackage && name[0] !== '.') {
        var parentMap = this.packages[parentPackage].map;
        if (parentMap) {
          var map = applyMap(parentMap, name);

          if (map) {
            name = parentMap[map] + name.substr(map.length);

            // relative maps are package-relative
            if (name[0] === '.')
              parentName = parentPackage + '/';
          }
        }
      }

      var defaultJSExtension = this.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js';

      // apply global map, relative normalization
      var normalized = normalize.call(this, name, parentName);

      // undo defaultJSExtension
      if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) != '.js')
        defaultJSExtension = false;
      if (defaultJSExtension)
        normalized = normalized.substr(0, normalized.length - 3);

      // check if we are inside a package
      var pkgName = getPackage.call(this, normalized);

      var loader = this;

      // check if we match a packageConfigPaths
      if (!sync) {
        var pkgPath, pkgConfigPath;
        for (var i = 0; i < this.packageConfigPaths.length; i++) {
          var p = this.packageConfigPaths[i];
          var pPkgLen = Math.max(p.lastIndexOf('*') + 1, p.lastIndexOf('/'));
          var match = normalized.match(packageConfigPathsRegExps[p] ||
              (packageConfigPathsRegExps[p] = new RegExp('^(' + p.substr(0, pPkgLen).replace(/\*/g, '[^\\/]+') + ')(\/|$)')));
          if (match) {
            pkgPath = match[1];
            pkgConfigPath = pkgPath + p.substr(pPkgLen);
            break;
          }
        }

        if (pkgPath && (!pkgName || pkgName != pkgPath || loader.packages[pkgName].loadConfig !== false)) {
          return (pkgConfigPromises[pkgPath] ||
            (pkgConfigPromises[pkgPath] =
              loader['fetch']({ name: pkgConfigPath, address: pkgConfigPath, metadata: {} })
              .then(function(source) {
                try {
                  return JSON.parse(source);
                }
                catch(e) {
                  throw new Error('Invalid JSON in package configuration file ' + pkgPath);
                }
              })
              .then(function(cfg) {
                // support "systemjs" prefixing
                if (cfg.systemjs)
                  cfg = cfg.systemjs;

                // remove any non-system properties if generic config file (eg package.json)
                for (var p in cfg) {
                  if (indexOf.call(packageProperties, p) == -1)
                    delete cfg[p];
                }

                // support main array
                if (cfg.main instanceof Array)
                  cfg.main = cfg.main[0];

                // deeply-merge (to first level) config with any existing package config
                if (pkgName && pkgName == pkgPath)
                  extendMeta(cfg, loader.packages[pkgPath]);

                loader.packages[pkgPath] = cfg;
              })
            )
          )
          .then(function() {
            // finally apply the package config we just created to the current request
            return applyPackageConfig.call(loader, normalized, pkgPath, sync, isPlugin);
          });
        }
      }

      if (pkgName)
        return applyPackageConfig.call(loader, normalized, pkgName, sync, isPlugin);

      // add back defaultJSExtension if not a package
      if (defaultJSExtension)
        normalized += '.js';

      return normalized;
    };
  }

  SystemJSLoader.prototype.normalizeSync = SystemJSLoader.prototype.normalize;

  hook('normalizeSync', function(normalize) {
    return createPackageNormalize(normalize, true);
  });

  hook('normalize', function(normalize) {
    return createPackageNormalize(normalize, false);
  });

  function getMetaMatches(pkgMeta, basePath, pkgName, normalized, matchFn) {
    // wildcard meta
    var meta = {};
    var wildcardIndex;
    for (var module in pkgMeta) {
      // allow meta to start with ./ for flexibility
      var dotRel = module.substr(0, 2) == './' ? './' : '';
      if (dotRel)
        module = module.substr(2);

      wildcardIndex = module.indexOf('*');
      if (wildcardIndex === -1)
        continue;

      if (basePath + module.substr(0, wildcardIndex) === normalized.substr(pkgName.length + 1, wildcardIndex + basePath.length)
          && module.substr(wildcardIndex + 1) === normalized.substr(normalized.length - module.length + wildcardIndex + 1)) {
        matchFn(module, pkgMeta[dotRel + module], module.split('/').length);
      }
    }
    // exact meta
    var metaName = normalized.substr(pkgName.length + basePath.length + 1);
    var exactMeta = pkgMeta[metaName] || pkgMeta['./' + metaName];
    if (exactMeta && normalized.substr(pkgName.length + 1, basePath.length) == basePath)
      matchFn(exactMeta, exactMeta, 0);
  }

  hook('locate', function(locate) {
    return function(load) {
      var loader = this;
      return Promise.resolve(locate.call(this, load))
      .then(function(address) {
        var pkgName = getPackage.call(loader, load.name);
        if (pkgName) {
          var pkg = loader.packages[pkgName];

          var basePath = getBasePath(pkg);

          // format
          if (pkg.format)
            load.metadata.format = load.metadata.format || pkg.format;

          var meta = {};
          if (pkg.meta) {
            var bestDepth = 0;
            getMetaMatches(pkg.meta, basePath, pkgName, load.name, function(metaPattern, matchMeta, matchDepth) {
              if (matchDepth > bestDepth)
                bestDepth = matchDepth;
              extendMeta(meta, matchMeta, matchDepth && bestDepth > matchDepth);
            });

            // allow alias and loader to be package-relative
            if (meta.alias && meta.alias.substr(0, 2) == './')
              meta.alias = pkgName + meta.alias.substr(1);
            if (meta.loader && meta.loader.substr(0, 2) == './')
              meta.loader = pkgName + meta.loader.substr(1);
            extendMeta(load.metadata, meta);
          }
        }

        return address;
      });
    };
  });

})();<commit_msg>package environment map to use pluginLoader when suitable<commit_after>/*
 * Package Configuration Extension
 *
 * Example:
 *
 * System.packages = {
 *   jquery: {
 *     basePath: 'lib', // optionally only use a subdirectory within the package
 *     main: 'index.js', // when not set, package name is requested directly
 *     format: 'amd',
 *     defaultExtension: 'ts', // defaults to 'js', can be set to false
 *     meta: {
 *       '*.ts': {
 *         loader: 'typescript'
 *       },
 *       'vendor/sizzle.js': {
 *         format: 'global'
 *       }
 *     },
 *     map: {
 *        // map internal require('sizzle') to local require('./vendor/sizzle')
 *        sizzle: './vendor/sizzle.js',
 *        // map any internal or external require of 'jquery/vendor/another' to 'another/index.js'
 *        './vendor/another.js': './another/index.js',
 *        // test.js / test -> lib/test.js
 *        './test.js': './lib/test.js',
 *
 *        // environment-specific map configurations
 *        './index.js': {
 *          '~browser': './index-node.js'
 *        }
 *     }
 *   }
 * };
 *
 * Then:
 *   import 'jquery'                       -> jquery/index.js
 *   import 'jquery/submodule'             -> jquery/submodule.js
 *   import 'jquery/submodule.ts'          -> jquery/submodule.ts loaded as typescript
 *   import 'jquery/vendor/another'        -> another/index.js
 *
 * Detailed Behaviours
 * - main is the only property where a leading "./" can be added optionally
 * - map and defaultExtension are applied to the main
 * - defaultExtension adds the extension only if no other extension is present
 * - defaultJSExtensions applies after map when defaultExtension is not set
 * - if a meta value is available for a module, map and defaultExtension are skipped
 * - like global map, package map also applies to subpaths (sizzle/x, ./vendor/another/sub)
 * - condition module map is '@env' module in package or '@system-env' globally
 *
 * In addition, the following meta properties will be allowed to be package
 * -relative as well in the package meta config:
 *
 *   - loader
 *   - alias
 *
 *
 * Package Configuration Loading
 *
 * Not all packages may already have their configuration present in the System config
 * For these cases, a list of packageConfigPaths can be provided, which when matched against
 * a request, will first request a ".json" file by the package name to derive the package
 * configuration from. This allows dynamic loading of non-predetermined code, a key use
 * case in SystemJS.
 *
 * Example:
 *
 *   System.packageConfigPaths = ['packages/test/package.json', 'packages/*.json'];
 *
 *   // will first request 'packages/new-package/package.json' for the package config
 *   // before completing the package request to 'packages/new-package/path'
 *   System.import('packages/new-package/path');
 *
 *   // will first request 'packages/test/package.json' before the main
 *   System.import('packages/test');
 *
 * When a package matches packageConfigPaths, it will always send a config request for
 * the package configuration.
 * The package name itself is taken to be the match up to and including the last wildcard
 * or trailing slash.
 * Package config paths are ordered - matching is done based on the first match found.
 * Any existing package configurations for the package will deeply merge with the
 * package config, with the existing package configurations taking preference.
 * To opt-out of the package configuration request for a package that matches
 * packageConfigPaths, use the { loadConfig: false } package config option.
 *
 */
(function() {

  hookConstructor(function(constructor) {
    return function() {
      constructor.call(this);
      this.packages = {};
      this.packageConfigPaths = {};
    };
  });

  function getPackage(name) {
    // use most specific package
    var curPkg, curPkgLen = 0, pkgLen;
    for (var p in this.packages) {
      if (name.substr(0, p.length) === p && (name.length === p.length || name[p.length] === '/')) {
        pkgLen = p.split('/').length;
        if (pkgLen > curPkgLen) {
          curPkg = p;
          curPkgLen = pkgLen;
        }
      }
    }
    return curPkg;
  }

  function applyMap(map, name) {
    var bestMatch, bestMatchLength = 0;

    for (var p in map) {
      if (name.substr(0, p.length) == p && (name.length == p.length || name[p.length] == '/')) {
        var curMatchLength = p.split('/').length;
        if (curMatchLength <= bestMatchLength)
          continue;
        bestMatch = p;
        bestMatchLength = curMatchLength;
      }
    }

    return bestMatch;
  }

  function envMap(loader, pkgName, pkgMap, name) {
    var map = applyMap(pkgMap, name);
    var mapped = pkgMap[map];

    // conditional package map
    if (mapped) {
      if (typeof mapped == 'object') {
        var pluginLoader = loader.pluginLoader || loader;
        return pluginLoader['import'](pkgMap['@env'] || '@system-env', pkgName)
        .then(function(env) {
          // first map condition to match is used
          for (var e in mapped) {
            var negate = e[0] == '~';

            var value = readMemberExpression(negate ? e.substr(1) : e, env);

            if (!negate && value || negate && !value)
              return mapped[e] + name.substr(map.length);
          }
        });
      }
      // normal map
      else {
        return mapped + name.substr(map.length);
      }
    }
  }

  function getBasePath(pkg) {
    // sanitize basePath
    var basePath = pkg.basePath && pkg.basePath != '.' ? pkg.basePath : '';
    if (basePath) {
      if (basePath.substr(0, 2) == './')
        basePath = basePath.substr(2);
      if (basePath[basePath.length - 1] != '/')
        basePath += '/';
    }
    return basePath;
  }

  // given the package subpath, return the resultant combined path
  // defaultExtension is only added if the path does not have
  // loader package meta or exact package meta
  function toPackagePath(pkgName, pkg, basePath, subPath, isPlugin) {
    var normalized = pkgName + '/' + basePath + subPath;

    var hasExtensionMeta = isPlugin;
    if (pkg.meta)
      getMetaMatches(pkg.meta, basePath, pkgName, normalized, function(metaPattern, matchMeta, matchDepth) {
        // exact meta or meta with any content after the last wildcard skips extension
        if (matchDepth == 0 || metaPattern.lastIndexOf('*') != metaPattern.length - 1)
          hasExtensionMeta = true;
      });

    return normalized + (hasExtensionMeta ? '' : getDefaultExtension(pkg, subPath));
  }

  function getDefaultExtension(pkg, subPath) {
    // don't apply extensions to folders or if defaultExtension = false
    if (subPath[subPath.length - 1] != '/' && pkg.defaultExtension !== false) {
      // work out what the defaultExtension is and add if not there already
      var defaultExtension = '.' + (pkg.defaultExtension || 'js');
      if (subPath.substr(subPath.length - defaultExtension.length) != defaultExtension)
        return defaultExtension;
    }
    return '';
  }

  function applyPackageConfig(normalized, pkgName, sync, isPlugin) {
    var loader = this;
    var pkg = loader.packages[pkgName];

    var basePath = getBasePath(pkg);

    // main
    if (pkgName === normalized && pkg.main)
      normalized += '/' + (pkg.main.substr(0, 2) == './' ? pkg.main.substr(2) : pkg.main);

    // allow for direct package name normalization with trailling "/" (no main)
    if (normalized.length == pkgName.length + 1 && normalized[pkgName.length] == '/')
      return normalized;

    // no submap if name is package itself
    if (normalized.length == pkgName.length)
      return normalized + (loader.defaultJSExtensions && normalized.substr(normalized.length - 3, 3) != '.js' ? '.js' : '');

    // sync normalize does not apply package map
    if (sync || !pkg.map)
      return toPackagePath(pkgName, pkg, basePath, normalized.substr(pkgName.length + 1));

    var subPath = '.' + normalized.substr(pkgName.length);

    // apply submap checking without then with defaultExtension
    return Promise.resolve(envMap(loader, pkgName, pkg.map, subPath))
    .then(function(mapped) {
      if (mapped)
        return mapped;

      var defaultExtension = isPlugin && getDefaultExtension(pkg, subPath.substr(2));
      if (defaultExtension)
        return envMap(loader, pkgName, pkg.map, subPath + defaultExtension);
    })
    .then(function(mapped) {
      if (mapped) {
        // '.' as a target is the package itself (with package main check)
        if (mapped == '.')
          return loader.normalizeSync(pkgName);
        // internal package map
        else if (mapped.substr(0, 2) == './')
          return toPackagePath(pkgName, pkg, basePath, mapped.substr(2), isPlugin);
        // global package map
        else
          return loader.normalize.call(loader, mapped);
      }
      else {
        return toPackagePath(pkgName, pkg, basePath, normalized.substr(pkgName.length + 1), isPlugin);
      }
    });
  }

  var packageConfigPathsRegExps = {};
  var pkgConfigPromises = {};
  function createPackageNormalize(normalize, sync) {
    return function(name, parentName, isPlugin) {
      isPlugin = isPlugin === true;

      // apply contextual package map first
      if (parentName) {
        var parentPackage = getPackage.call(this, parentName) ||
            this.defaultJSExtensions && parentName.substr(parentName.length - 3, 3) == '.js' &&
            getPackage.call(this, parentName.substr(0, parentName.length - 3));
      }

      if (parentPackage && name[0] !== '.') {
        var parentMap = this.packages[parentPackage].map;
        if (parentMap) {
          var map = applyMap(parentMap, name);

          if (map) {
            name = parentMap[map] + name.substr(map.length);

            // relative maps are package-relative
            if (name[0] === '.')
              parentName = parentPackage + '/';
          }
        }
      }

      var defaultJSExtension = this.defaultJSExtensions && name.substr(name.length - 3, 3) != '.js';

      // apply global map, relative normalization
      var normalized = normalize.call(this, name, parentName);

      // undo defaultJSExtension
      if (defaultJSExtension && normalized.substr(normalized.length - 3, 3) != '.js')
        defaultJSExtension = false;
      if (defaultJSExtension)
        normalized = normalized.substr(0, normalized.length - 3);

      // check if we are inside a package
      var pkgName = getPackage.call(this, normalized);

      var loader = this;

      // check if we match a packageConfigPaths
      if (!sync) {
        var pkgPath, pkgConfigPath;
        for (var i = 0; i < this.packageConfigPaths.length; i++) {
          var p = this.packageConfigPaths[i];
          var pPkgLen = Math.max(p.lastIndexOf('*') + 1, p.lastIndexOf('/'));
          var match = normalized.match(packageConfigPathsRegExps[p] ||
              (packageConfigPathsRegExps[p] = new RegExp('^(' + p.substr(0, pPkgLen).replace(/\*/g, '[^\\/]+') + ')(\/|$)')));
          if (match) {
            pkgPath = match[1];
            pkgConfigPath = pkgPath + p.substr(pPkgLen);
            break;
          }
        }

        if (pkgPath && (!pkgName || pkgName != pkgPath || loader.packages[pkgName].loadConfig !== false)) {
          return (pkgConfigPromises[pkgPath] ||
            (pkgConfigPromises[pkgPath] =
              loader['fetch']({ name: pkgConfigPath, address: pkgConfigPath, metadata: {} })
              .then(function(source) {
                try {
                  return JSON.parse(source);
                }
                catch(e) {
                  throw new Error('Invalid JSON in package configuration file ' + pkgPath);
                }
              })
              .then(function(cfg) {
                // support "systemjs" prefixing
                if (cfg.systemjs)
                  cfg = cfg.systemjs;

                // remove any non-system properties if generic config file (eg package.json)
                for (var p in cfg) {
                  if (indexOf.call(packageProperties, p) == -1)
                    delete cfg[p];
                }

                // support main array
                if (cfg.main instanceof Array)
                  cfg.main = cfg.main[0];

                // deeply-merge (to first level) config with any existing package config
                if (pkgName && pkgName == pkgPath)
                  extendMeta(cfg, loader.packages[pkgPath]);

                loader.packages[pkgPath] = cfg;
              })
            )
          )
          .then(function() {
            // finally apply the package config we just created to the current request
            return applyPackageConfig.call(loader, normalized, pkgPath, sync, isPlugin);
          });
        }
      }

      if (pkgName)
        return applyPackageConfig.call(loader, normalized, pkgName, sync, isPlugin);

      // add back defaultJSExtension if not a package
      if (defaultJSExtension)
        normalized += '.js';

      return normalized;
    };
  }

  SystemJSLoader.prototype.normalizeSync = SystemJSLoader.prototype.normalize;

  hook('normalizeSync', function(normalize) {
    return createPackageNormalize(normalize, true);
  });

  hook('normalize', function(normalize) {
    return createPackageNormalize(normalize, false);
  });

  function getMetaMatches(pkgMeta, basePath, pkgName, normalized, matchFn) {
    // wildcard meta
    var meta = {};
    var wildcardIndex;
    for (var module in pkgMeta) {
      // allow meta to start with ./ for flexibility
      var dotRel = module.substr(0, 2) == './' ? './' : '';
      if (dotRel)
        module = module.substr(2);

      wildcardIndex = module.indexOf('*');
      if (wildcardIndex === -1)
        continue;

      if (basePath + module.substr(0, wildcardIndex) === normalized.substr(pkgName.length + 1, wildcardIndex + basePath.length)
          && module.substr(wildcardIndex + 1) === normalized.substr(normalized.length - module.length + wildcardIndex + 1)) {
        matchFn(module, pkgMeta[dotRel + module], module.split('/').length);
      }
    }
    // exact meta
    var metaName = normalized.substr(pkgName.length + basePath.length + 1);
    var exactMeta = pkgMeta[metaName] || pkgMeta['./' + metaName];
    if (exactMeta && normalized.substr(pkgName.length + 1, basePath.length) == basePath)
      matchFn(exactMeta, exactMeta, 0);
  }

  hook('locate', function(locate) {
    return function(load) {
      var loader = this;
      return Promise.resolve(locate.call(this, load))
      .then(function(address) {
        var pkgName = getPackage.call(loader, load.name);
        if (pkgName) {
          var pkg = loader.packages[pkgName];

          var basePath = getBasePath(pkg);

          // format
          if (pkg.format)
            load.metadata.format = load.metadata.format || pkg.format;

          var meta = {};
          if (pkg.meta) {
            var bestDepth = 0;
            getMetaMatches(pkg.meta, basePath, pkgName, load.name, function(metaPattern, matchMeta, matchDepth) {
              if (matchDepth > bestDepth)
                bestDepth = matchDepth;
              extendMeta(meta, matchMeta, matchDepth && bestDepth > matchDepth);
            });

            // allow alias and loader to be package-relative
            if (meta.alias && meta.alias.substr(0, 2) == './')
              meta.alias = pkgName + meta.alias.substr(1);
            if (meta.loader && meta.loader.substr(0, 2) == './')
              meta.loader = pkgName + meta.loader.substr(1);
            extendMeta(load.metadata, meta);
          }
        }

        return address;
      });
    };
  });

})();<|endoftext|>


<commit_before>'use strict';

const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const normalizePkg = require('normalize-package-data');
const parseGitHubRepoURL = require('parse-github-repo-url');

let get = (directory) => {
  const _path = path.join(directory, 'package.json');
  let pkg = JSON.parse(fs.readFileSync(_path));
  // normalizePkg(pkg);
  pkg._path = _path;

  const g = parseGitHubRepoURL(pkg.repository.url);
  pkg.github_owner = g[0];
  pkg.github_repo = g[1];
  return pkg;
};

module.exports = get(process.cwd());
module.exports.get = get;
<commit_msg>:green_heart: :shirt:<commit_after>'use strict';
/* eslint no-sync: 0 */
// const _ = require('lodash');
const fs = require('fs');
const path = require('path');
// const normalizePkg = require('normalize-package-data');
const parseGitHubRepoURL = require('parse-github-repo-url');

let get = (directory) => {
  const _path = path.join(directory, 'package.json');
  let pkg = JSON.parse(fs.readFileSync(_path));
  // normalizePkg(pkg);
  pkg._path = _path;

  const g = parseGitHubRepoURL(pkg.repository.url);
  pkg.github_owner = g[0];
  pkg.github_repo = g[1];
  return pkg;
};

module.exports = get(process.cwd());
module.exports.get = get;
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------------------------------------------------
// PathLib
//
// @module
//----------------------------------------------------------------------------------------------------------------------

const path = require('path');

//----------------------------------------------------------------------------------------------------------------------

/**
 * Gets the absolute path to the root folder of the currently running node process, or the folder it was run from.
 *
 * @returns {String} The path to the root folder of the current node process
 */
function getRoot()
{
    return require.main ? path.dirname(require.main.filename) : process.cwd();
} // end getRoot

//----------------------------------------------------------------------------------------------------------------------

module.exports = {
    getRoot,
    join: path.join
};

//----------------------------------------------------------------------------------------------------------------------
<commit_msg>added browser support.<commit_after>//----------------------------------------------------------------------------------------------------------------------
// PathLib
//
// @module
//----------------------------------------------------------------------------------------------------------------------

const path = require('path');

//----------------------------------------------------------------------------------------------------------------------

/**
 * Gets the absolute path to the root folder of the currently running node process, or the folder it was run from. If
 * running in a browser, we simple return `'/'`, as that is always the root of a website.
 *
 * @returns {String} The path to the root folder of the current node process.
 */
function getRoot()
{
    if(process.browser)
    {
        return '/';
    }
    else
    {
        return require.main ? path.dirname(require.main.filename) : process.cwd();
    } // end if
} // end getRoot

//----------------------------------------------------------------------------------------------------------------------

module.exports = {
    getRoot,
    join: path.join
};

//----------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>"use strict";

var fs = require('fs');
var gm = require('gm');
var path = require('path');
var async = require('async');

class Pdf2Img {

    options = {
        type: 'jpg',
        size: 1024,
        density: 600,
        outputdir: null,
        outputname: null,
        page: null,
        quality: 100
    };

    constructor(options) {
        this.options = options
    }

    convert(input, callbackreturn) {
        // Make sure it has correct extension
        if (path.extname(path.basename(input)) != '.pdf') {
            return callbackreturn({
                result: 'error',
                message: 'Unsupported file type.'
            });
        }

        // Check if input file exists
        if (!this.isFileExists(input)) {
            return callbackreturn({
                result: 'error',
                message: 'Input file not found.'
            });
        }

        const options = this.options

        var stdout = [];
        var output = path.basename(input, path.extname(path.basename(input)));

        // Set output dir
        if (this.options.outputdir) {
            this.options.outputdir = this.options.outputdir + path.sep;
        } else {
            this.options.outputdir = output + path.sep;
        }
        const isDirExists = this.isDirExists
        // Create output dir if it doesn't exists
        if (!this.isDirExists(this.options.outputdir)) {
            let dirs = this.options.outputdir.split(path.sep);
            let completePath = ''
            dirs.forEach(function (dir) {
                completePath += dir
                if (!isDirExists(completePath)) {
                    fs.mkdirSync(completePath);
                }
            })
        }

        // Set output name
        if (!this.options.outputname) {
            this.options.outputname = output;
        }

        const convertPdf2Img = function (input, output, page, callback) {
        if (input.path) {
            var filepath = input.path;
        } else {
            return callback({
                result: 'error',
                message: 'Invalid input file path.'
            }, null);
        }

        var filename = filepath + '[' + (page - 1) + ']';
        console.log(`file name ${filename}`)
        gm(input, filename)
            .density(options.density, options.density)
            .resize(options.size)
            .quality(options.quality)
            .write(output, function (err) {
                if (err) {
                    return callback({
                        result: 'error',
                        message: 'Can not write output file.'
                    }, null);
                }

                if (!(fs.statSync(output)['size'] / 1000)) {
                    return callback({
                        result: 'error',
                        message: 'Zero sized output image detected.'
                    }, null);
                }

                var results = {
                    page: page,
                    name: path.basename(output),
                    size: fs.statSync(output)['size'] / 1000.0,
                    path: output
                };

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

        async.waterfall([
            // Get pages count
            function (callback) {
                gm(input).identify("%p ", function (err, value) {
                    var pageCount = String(value).split(' ');
                    console.log(`value = ${value}`)
                    console.log(`pageCount = ${pageCount}`)
                    if (!pageCount.length) {
                        callback({
                            result: 'error',
                            message: 'Invalid page number #1.'
                        }, null);
                    } else {
                        // Convert selected page
                        if (options.page) {
                            if (options.page <= pageCount.length) {
                                callback(null, [options.page]);
                            } else {
                                callback({
                                    result: 'error',
                                    message: 'Invalid page number #2.'
                                }, null);
                            }
                        } else {
                            callback(null, pageCount);
                        }
                    }

                })

            },

            // Convert pdf file
            function (pages, callback) {
                // Use eachSeries to make sure that conversion has done page by page
                async.eachSeries(pages, function (page, callbackmap) {
                    var inputStream = fs.createReadStream(input);
                    var outputFile = options.outputdir + options.outputname + '_' + page + '.' + options.type;

                    convertPdf2Img(inputStream, outputFile, parseInt(page), function (error, result) {
                        if (error) {
                            return callbackmap(error);
                        }

                        stdout.push(result);
                        return callbackmap(error, result);
                    });
                }, function (e) {
                    if (e) callback(e);

                    return callback(null, {
                        result: 'success',
                        message: stdout
                    });
                });
            }
        ], callbackreturn);
    };

// Check if directory is exists

    isDirExists(path) {
        try {
            return fs.statSync(path).isDirectory();
        } catch (e) {
            return false;
        }
    }

// Check if file is exists

    isFileExists(path) {
        try {
            return fs.statSync(path).isFile();
        } catch (e) {
            return false;
        }
    }

}

module.exports = Pdf2Img;

/*
Usage Example
new Pdf2Img({
    type: "png",
    size: 1024,
    density: 600,
    outputdir: "output",
    // outputname: "output_name",
    // page: null,
    quality: 100,
}).convert("/Users/elgamala/Downloads/moodleandoffice365withadfs.pdf", function (data){
    console.log(data)
})
*/
<commit_msg>fix invalid page number error<commit_after>"use strict";

var fs = require('fs');
var gm = require('gm');
var path = require('path');
var async = require('async');

class Pdf2Img {

    options = {
        type: 'jpg',
        size: 1024,
        density: 600,
        outputdir: null,
        outputname: null,
        page: null,
        quality: 100
    };

    constructor(options) {
        this.options = options
    }

    convert(input, callbackreturn) {
        // Make sure it has correct extension
        if (path.extname(path.basename(input)) != '.pdf') {
            return callbackreturn({
                result: 'error',
                message: 'Unsupported file type.'
            });
        }

        // Check if input file exists
        if (!this.isFileExists(input)) {
            return callbackreturn({
                result: 'error',
                message: 'Input file not found.'
            });
        }

        const options = this.options

        var stdout = [];
        var output = path.basename(input, path.extname(path.basename(input)));

        // Set output dir
        if (this.options.outputdir) {
            this.options.outputdir = this.options.outputdir + path.sep;
        } else {
            this.options.outputdir = output + path.sep;
        }
        const isDirExists = this.isDirExists
        // Create output dir if it doesn't exists
        if (!this.isDirExists(this.options.outputdir)) {
            fs.mkdirSync(this.options.outputdir);
        }

        // Set output name
        if (!this.options.outputname) {
            this.options.outputname = output;
        }

        const convertPdf2Img = function (input, output, page, callback) {
        if (input.path) {
            var filepath = input.path;
        } else {
            return callback({
                result: 'error',
                message: 'Invalid input file path.'
            }, null);
        }

        var filename = filepath + '[' + (page - 1) + ']';
        console.log(`file name ${filename}`)
        gm(input, filename)
            .density(options.density, options.density)
            .resize(options.size)
            .quality(options.quality)
            .write(output, function (err) {
                if (err) {
                    return callback({
                        result: 'error',
                        message: 'Can not write output file.'
                    }, null);
                }

                if (!(fs.statSync(output)['size'] / 1000)) {
                    return callback({
                        result: 'error',
                        message: 'Zero sized output image detected.'
                    }, null);
                }

                var results = {
                    page: page,
                    name: path.basename(output),
                    size: fs.statSync(output)['size'] / 1000.0,
                    path: output
                };

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

        async.waterfall([
            // Get pages count
            function (callback) {
                gm(input).identify("%p ", function (err, value) {
                    var pageCount = String(value).split(' ');
                    console.log(`value = ${value}`)
                    console.log(`pageCount = ${pageCount}`)
                    if (!pageCount.length) {
                        callback({
                            result: 'error',
                            message: 'Invalid page number #1.'
                        }, null);
                    } else {
                        // Convert selected page
                        if (options.page) {
                            if (options.page <= pageCount.length) {
                                callback(null, [options.page]);
                            } else {
                                callback({
                                    result: 'error',
                                    message: 'Invalid page number #2.'
                                }, null);
                            }
                        } else {
                            callback(null, pageCount);
                        }
                    }

                })

            },

            // Convert pdf file
            function (pages, callback) {
                // Use eachSeries to make sure that conversion has done page by page
                async.eachSeries(pages, function (page, callbackmap) {
                    var inputStream = fs.createReadStream(input);
                    var outputFile = options.outputdir + options.outputname + '_' + page + '.' + options.type;

                    convertPdf2Img(inputStream, outputFile, parseInt(page), function (error, result) {
                        if (error) {
                            return callbackmap(error);
                        }

                        stdout.push(result);
                        return callbackmap(error, result);
                    });
                }, function (e) {
                    if (e) callback(e);

                    return callback(null, {
                        result: 'success',
                        message: stdout
                    });
                });
            }
        ], callbackreturn);
    };

// Check if directory is exists

    isDirExists(path) {
        try {
            return fs.statSync(path).isDirectory();
        } catch (e) {
            return false;
        }
    }

// Check if file is exists

    isFileExists(path) {
        try {
            return fs.statSync(path).isFile();
        } catch (e) {
            return false;
        }
    }

}

module.exports = Pdf2Img;

/*
Usage Example
new Pdf2Img({
    type: "png",
    size: 1024,
    density: 600,
    outputdir: "output",
    // outputname: "output_name",
    // page: null,
    quality: 100,
}).convert("/Users/elgamala/Downloads/moodleandoffice365withadfs.pdf", function (data){
    console.log(data)
})
*/
<|endoftext|>


<commit_before>/*
* caching
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var events = require('events');
var utils = require('./utilities');
var fmKey = function(key) { return utils.trim(key).toLowerCase(); };

var storage = {

    _data: {}, events: new events.EventEmitter(),

    get: function(region, key) {
        region = fmKey(region);
        key = fmKey(key);
        //
        if (arguments.length === 0) {
            return this._data;
        } else {
            var r = this._data[region];
            if (arguments.length === 1) {
                return r;
            } else {
                return r ? r[key] : r;
            }
        }
    },

    set: function(region, key, val) {
        region = fmKey(region);
        key = fmKey(key);
        //
        if (arguments.length === 2) {
            return this._data[region] = key;
        }
        if (arguments.length === 3) {
            var r = this._data[region];
            if (!r) { r = this._data[region] = {}; }
            r[key] = val;
        }
    },

    remove: function(region, key) {
        region = fmKey(region);
        key = fmKey(key);
        //
        this.events.emit('remove', { region: region, key: key });
        //
        if (arguments.length === 1) {
            return delete this._data[region];
        } else {
            var r = this._data[region];
            if (r) { return delete r[key]; }
            return false;
        }
    },

    exists: function(region, key) {
        region = fmKey(region);
        key = fmKey(key);
        //
        if (arguments.length === 1) {
            return (region in this._data);
        } else {
            var r = this._data[region];
            return (r && key in r);
        }
    },

    clear: function(region) {
        region = fmKey(region);
        //
        this.events.emit('clear', { region: region });
        //
        if (arguments.length === 0) {
            this._data = {};
            return true;
        } else {
            return delete this._data[region];
        }
    }
};

var instances = {

    _data: {},

    get: function(key) {
        return this._data[fmKey(key)];
    },

    set: function(key, ins) {
        this._data[fmKey(key)] = ins;
    }
};

var caching = function(set) {
    set = set || {};
    var region = set.region || ('guid:' + utils.unique(32));
    //
    var instance = instances.get(region);
    if (instance) { return instance; }
    instances.set(region, this);
    //
    this._region = region;
};

caching.storage = storage;

caching.instances = instances;

caching.region = function(region) {
    return new caching({ region: region });
};

caching.isRandomRegionName = function (region) {
    return /^guid:[a-z0-9]{32}$/i.test(region);
};

caching.prototype = {

    _region: null,

    constructor: caching, className: 'caching',

    all: function() {
        var ret = {}, self = this;
        utils.each(storage.get(this._region), function(key) {
            var val = self.get(key);
            if (val) { ret[key] = val; }
        });
        return ret;
    },

    get: function(key) {
        var o = storage.get(this._region, key);
        if (o) {
            if (utils.isDate(o.expire) && new Date() >= o.expire) {
                this.remove(key);
                return null;
            } else {
                return o.val;
            }
        }
        return undefined;
    },

    set: function(key, val, expire, notify) {
        var o = { val: val, expire: expire, notify: notify };
        storage.set(this._region, key, o);
    },

    remove: function(key) {
        var o = storage.get(this._region, key);
        if (o && utils.isFunction(o.notify)) {
            o.notify({
                value: o.val,
                action: 'remove'
            });
        }
        return storage.remove(this._region, key);
    },

    count: function() {
        return utils.propCount(this.all());
    },

    exists: function(key) {
        return storage.exists(this._region, key);
    },

    clear: function() {
        return storage.remove(this._region);
    }
};

module.exports = caching;
<commit_msg>add _cachedAll<commit_after>/*
* caching
* author: ronglin
* create date: 2014.6.24
*/

'use strict';

var events = require('events');
var utils = require('./utilities');
var fmKey = function(key) { return utils.trim(key).toLowerCase(); };

var storage = {

    _data: {}, events: new events.EventEmitter(),

    get: function(region, key) {
        region = fmKey(region);
        key = fmKey(key);
        //
        if (arguments.length === 0) {
            return this._data;
        } else {
            var r = this._data[region];
            if (arguments.length === 1) {
                return r;
            } else {
                return r ? r[key] : r;
            }
        }
    },

    set: function(region, key, val) {
        region = fmKey(region);
        key = fmKey(key);
        //
        if (arguments.length === 2) {
            return this._data[region] = key;
        }
        if (arguments.length === 3) {
            var r = this._data[region];
            if (!r) { r = this._data[region] = {}; }
            r[key] = val;
        }
    },

    remove: function(region, key) {
        region = fmKey(region);
        key = fmKey(key);
        //
        this.events.emit('remove', { region: region, key: key });
        //
        if (arguments.length === 1) {
            return delete this._data[region];
        } else {
            var r = this._data[region];
            if (r) { return delete r[key]; }
            return false;
        }
    },

    exists: function(region, key) {
        region = fmKey(region);
        key = fmKey(key);
        //
        if (arguments.length === 1) {
            return (region in this._data);
        } else {
            var r = this._data[region];
            return (r && key in r);
        }
    },

    clear: function(region) {
        region = fmKey(region);
        //
        this.events.emit('clear', { region: region });
        //
        if (arguments.length === 0) {
            this._data = {};
            return true;
        } else {
            return delete this._data[region];
        }
    }
};

var instances = {

    _data: {},

    get: function(key) {
        return this._data[fmKey(key)];
    },

    set: function(key, ins) {
        this._data[fmKey(key)] = ins;
    }
};

var caching = function(set) {
    set = set || {};
    var region = set.region || ('guid:' + utils.unique(32));
    //
    var instance = instances.get(region);
    if (instance) { return instance; }
    instances.set(region, this);
    //
    this._region = region;
};

caching.storage = storage;

caching.instances = instances;

caching.region = function(region) {
    return new caching({ region: region });
};

caching.isRandomRegionName = function (region) {
    return /^guid:[a-z0-9]{32}$/i.test(region);
};

caching.prototype = {

    _region: null, _cachedAll: null,

    constructor: caching, className: 'caching',

    all: function(cache) {
        if (cache === true) {
            if (this._cachedAll) {
                return (this._cachedAll);
            } else {
                return (this._cachedAll = this.all());
            }
        }
        var ret = {}, self = this;
        utils.each(storage.get(this._region), function(key) {
            var val = self.get(key);
            if (val) { ret[key] = val; }
        });
        return ret;
    },

    get: function(key) {
        var o = storage.get(this._region, key);
        if (o) {
            if (utils.isDate(o.expire) && new Date() >= o.expire) {
                this.remove(key);
                return null;
            } else {
                return o.val;
            }
        }
        return undefined;
    },

    set: function(key, val, expire, notify) {
        var o = { val: val, expire: expire, notify: notify };
        storage.set(this._region, key, o);
        this._cachedAll = null;
    },

    remove: function(key) {
        var o = storage.get(this._region, key);
        if (o && utils.isFunction(o.notify)) {
            o.notify({
                value: o.val,
                action: 'remove'
            });
        }
        this._cachedAll = null;
        return storage.remove(this._region, key);
    },

    count: function() {
        return utils.propCount(this.all());
    },

    exists: function(key) {
        return storage.exists(this._region, key);
    },

    clear: function() {
        this._cachedAll = null;
        return storage.remove(this._region);
    }
};

module.exports = caching;
<|endoftext|>


<commit_before>(function () {
    'use strict';
    var getModule = function (moduleName, excludeCommonDeps) {
        var module = {
            name: moduleName
        };

        if (excludeCommonDeps) {
            module.exclude = ['js/factories/common_deps'];
        }

        return module;
    };

    var getModulesList = function (modules) {
        var result = [getModule('js/factories/common_deps')];
        return result.concat(modules.map(function (moduleName) {
            return getModule(moduleName, true);
        }));
    };

    return {
        /**
         * List the modules that will be optimized. All their immediate and deep
         * dependencies will be included in the module's file when the build is
         * done.
         */
        modules: getModulesList([
            'js/factories/asset_index',
            'js/factories/base',
            'js/factories/checklists',
            'js/factories/container',
            'js/factories/course',
            'js/factories/course_create_rerun',
            'js/factories/course_info',
            'js/factories/edit_tabs',
            'js/factories/export',
            'js/factories/group_configurations',
            'js/certificates/factories/certificates_page_factory',
            'js/factories/import',
            'js/factories/index',
            'js/factories/login',
            'js/factories/manage_users',
            'js/factories/outline',
            'js/factories/register',
            'js/factories/settings',
            'js/factories/settings_advanced',
            'js/factories/settings_graders',
            'js/factories/textbooks',
            'js/factories/videos_index',
            'js/factories/xblock_validation'
        ]),
        /**
         * By default all the configuration for optimization happens from the command
         * line or by properties in the config file, and configuration that was
         * passed to requirejs as part of the app's runtime "main" JS file is *not*
         * considered. However, if you prefer the "main" JS file configuration
         * to be read for the build so that you do not have to duplicate the values
         * in a separate configuration, set this property to the location of that
         * main JS file. The first requirejs({}), require({}), requirejs.config({}),
         * or require.config({}) call found in that file will be used.
         * As of 2.1.10, mainConfigFile can be an array of values, with the last
         * value's config take precedence over previous values in the array.
         */
        mainConfigFile: 'require-config.js',
        /**
         * Set paths for modules. If relative paths, set relative to baseUrl above.
         * If a special value of "empty:" is used for the path value, then that
         * acts like mapping the path to an empty file. It allows the optimizer to
         * resolve the dependency to path, but then does not include it in the output.
         * Useful to map module names that are to resources on a CDN or other
         * http: URL when running in the browser and during an optimization that
         * file should be skipped because it has no dependencies.
         */
        paths: {
            'gettext': 'empty:',
            'xmodule': 'empty:',
            'mathjax': 'empty:',
            'tender': 'empty:',
            'youtube': 'empty:'
        },
        /**
         * If shim config is used in the app during runtime, duplicate the config
         * here. Necessary if shim config is used, so that the shim's dependencies
         * are included in the build. Using "mainConfigFile" is a better way to
         * pass this information though, so that it is only listed in one place.
         * However, if mainConfigFile is not an option, the shim config can be
         * inlined in the build config.
         */
        shim: {
            'xmodule': {
                deps: [
                    'jquery', 'underscore', 'codemirror', 'tinymce',
                    'jquery.tinymce', 'jquery.qtip', 'jquery.scrollTo', 'jquery.flot',
                    'jquery.cookie', 'utility'
                ]
            }
        },
        /**
         * Introduced in 2.1.2: If using "dir" for an output directory, normally the
         * optimize setting is used to optimize the build bundles (the "modules"
         * section of the config) and any other JS file in the directory. However, if
         * the non-build bundle JS files will not be loaded after a build, you can
         * skip the optimization of those files, to speed up builds. Set this value
         * to true if you want to skip optimizing those other non-build bundle JS
         * files.
         */
        skipDirOptimize: true,
        /**
         * When the optimizer copies files from the source location to the
         * destination directory, it will skip directories and files that start
         * with a ".". If you want to copy .directories or certain .files, for
         * instance if you keep some packages in a .packages directory, or copy
         * over .htaccess files, you can set this to null. If you want to change
         * the exclusion rules, change it to a different regexp. If the regexp
         * matches, it means the directory will be excluded. This used to be
         * called dirExclusionRegExp before the 1.0.2 release.
         * As of 1.0.3, this value can also be a string that is converted to a
         * RegExp via new RegExp().
         */
        fileExclusionRegExp: /^\.|spec|spec_helpers/,
        /**
         * Allow CSS optimizations. Allowed values:
         * - "standard": @import inlining and removal of comments, unnecessary
         * whitespace and line returns.
         * Removing line returns may have problems in IE, depending on the type
         * of CSS.
         * - "standard.keepLines": like "standard" but keeps line returns.
         * - "none": skip CSS optimizations.
         * - "standard.keepComments": keeps the file comments, but removes line
         * returns.  (r.js 1.0.8+)
         * - "standard.keepComments.keepLines": keeps the file comments and line
         * returns. (r.js 1.0.8+)
         * - "standard.keepWhitespace": like "standard" but keeps unnecessary whitespace.
         */
        optimizeCss: 'none',
        /**
         * How to optimize all the JS files in the build output directory.
         * Right now only the following values are supported:
         * - "uglify": Uses UglifyJS to minify the code.
         * - "uglify2": Uses UglifyJS2.
         * - "closure": Uses Google's Closure Compiler in simple optimization
         * mode to minify the code. Only available if REQUIRE_ENVIRONMENT is "rhino" (the default).
         * - "none": No minification will be done.
         */
        optimize: 'uglify2',
        /**
         * Sets the logging level. It is a number:
         * TRACE: 0,
         * INFO: 1,
         * WARN: 2,
         * ERROR: 3,
         * SILENT: 4
         * Default is 0.
         */
        logLevel: 1
    };
} ())
<commit_msg>Use RequireJS Optimizer for content libraries<commit_after>(function () {
    'use strict';
    var getModule = function (moduleName, excludeCommonDeps) {
        var module = {
            name: moduleName
        };

        if (excludeCommonDeps) {
            module.exclude = ['js/factories/common_deps'];
        }

        return module;
    };

    var getModulesList = function (modules) {
        var result = [getModule('js/factories/common_deps')];
        return result.concat(modules.map(function (moduleName) {
            return getModule(moduleName, true);
        }));
    };

    return {
        /**
         * List the modules that will be optimized. All their immediate and deep
         * dependencies will be included in the module's file when the build is
         * done.
         */
        modules: getModulesList([
            'js/factories/asset_index',
            'js/factories/base',
            'js/factories/checklists',
            'js/factories/container',
            'js/factories/course',
            'js/factories/course_create_rerun',
            'js/factories/course_info',
            'js/factories/edit_tabs',
            'js/factories/export',
            'js/factories/group_configurations',
            'js/certificates/factories/certificates_page_factory',
            'js/factories/import',
            'js/factories/index',
            'js/factories/library',
            'js/factories/login',
            'js/factories/manage_users',
            'js/factories/outline',
            'js/factories/register',
            'js/factories/settings',
            'js/factories/settings_advanced',
            'js/factories/settings_graders',
            'js/factories/textbooks',
            'js/factories/videos_index',
            'js/factories/xblock_validation'
        ]),
        /**
         * By default all the configuration for optimization happens from the command
         * line or by properties in the config file, and configuration that was
         * passed to requirejs as part of the app's runtime "main" JS file is *not*
         * considered. However, if you prefer the "main" JS file configuration
         * to be read for the build so that you do not have to duplicate the values
         * in a separate configuration, set this property to the location of that
         * main JS file. The first requirejs({}), require({}), requirejs.config({}),
         * or require.config({}) call found in that file will be used.
         * As of 2.1.10, mainConfigFile can be an array of values, with the last
         * value's config take precedence over previous values in the array.
         */
        mainConfigFile: 'require-config.js',
        /**
         * Set paths for modules. If relative paths, set relative to baseUrl above.
         * If a special value of "empty:" is used for the path value, then that
         * acts like mapping the path to an empty file. It allows the optimizer to
         * resolve the dependency to path, but then does not include it in the output.
         * Useful to map module names that are to resources on a CDN or other
         * http: URL when running in the browser and during an optimization that
         * file should be skipped because it has no dependencies.
         */
        paths: {
            'gettext': 'empty:',
            'xmodule': 'empty:',
            'mathjax': 'empty:',
            'tender': 'empty:',
            'youtube': 'empty:'
        },
        /**
         * If shim config is used in the app during runtime, duplicate the config
         * here. Necessary if shim config is used, so that the shim's dependencies
         * are included in the build. Using "mainConfigFile" is a better way to
         * pass this information though, so that it is only listed in one place.
         * However, if mainConfigFile is not an option, the shim config can be
         * inlined in the build config.
         */
        shim: {
            'xmodule': {
                deps: [
                    'jquery', 'underscore', 'codemirror', 'tinymce',
                    'jquery.tinymce', 'jquery.qtip', 'jquery.scrollTo', 'jquery.flot',
                    'jquery.cookie', 'utility'
                ]
            }
        },
        /**
         * Introduced in 2.1.2: If using "dir" for an output directory, normally the
         * optimize setting is used to optimize the build bundles (the "modules"
         * section of the config) and any other JS file in the directory. However, if
         * the non-build bundle JS files will not be loaded after a build, you can
         * skip the optimization of those files, to speed up builds. Set this value
         * to true if you want to skip optimizing those other non-build bundle JS
         * files.
         */
        skipDirOptimize: true,
        /**
         * When the optimizer copies files from the source location to the
         * destination directory, it will skip directories and files that start
         * with a ".". If you want to copy .directories or certain .files, for
         * instance if you keep some packages in a .packages directory, or copy
         * over .htaccess files, you can set this to null. If you want to change
         * the exclusion rules, change it to a different regexp. If the regexp
         * matches, it means the directory will be excluded. This used to be
         * called dirExclusionRegExp before the 1.0.2 release.
         * As of 1.0.3, this value can also be a string that is converted to a
         * RegExp via new RegExp().
         */
        fileExclusionRegExp: /^\.|spec|spec_helpers/,
        /**
         * Allow CSS optimizations. Allowed values:
         * - "standard": @import inlining and removal of comments, unnecessary
         * whitespace and line returns.
         * Removing line returns may have problems in IE, depending on the type
         * of CSS.
         * - "standard.keepLines": like "standard" but keeps line returns.
         * - "none": skip CSS optimizations.
         * - "standard.keepComments": keeps the file comments, but removes line
         * returns.  (r.js 1.0.8+)
         * - "standard.keepComments.keepLines": keeps the file comments and line
         * returns. (r.js 1.0.8+)
         * - "standard.keepWhitespace": like "standard" but keeps unnecessary whitespace.
         */
        optimizeCss: 'none',
        /**
         * How to optimize all the JS files in the build output directory.
         * Right now only the following values are supported:
         * - "uglify": Uses UglifyJS to minify the code.
         * - "uglify2": Uses UglifyJS2.
         * - "closure": Uses Google's Closure Compiler in simple optimization
         * mode to minify the code. Only available if REQUIRE_ENVIRONMENT is "rhino" (the default).
         * - "none": No minification will be done.
         */
        optimize: 'uglify2',
        /**
         * Sets the logging level. It is a number:
         * TRACE: 0,
         * INFO: 1,
         * WARN: 2,
         * ERROR: 3,
         * SILENT: 4
         * Default is 0.
         */
        logLevel: 1
    };
} ())
<|endoftext|>