diff --git a/bin/yarn-0.27.5.js b/bin/yarn-1.0.1.js similarity index 93% rename from bin/yarn-0.27.5.js rename to bin/yarn-1.0.1.js index 602df5d25d3aedcf2ea766398b13d42128a3f00e..302b0235ce2b5ffcbec66f55549d42188e77d185 100644 --- a/bin/yarn-0.27.5.js +++ b/bin/yarn-1.0.1.js @@ -1,4 +1,5 @@ #!/usr/bin/env node +module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; @@ -64,11 +65,17 @@ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 638); +/******/ return __webpack_require__(__webpack_require__.s = 409); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ +/***/ (function(module, exports) { + +module.exports = require("path"); + +/***/ }), +/* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76,7 +83,7 @@ exports.__esModule = true; -var _promise = __webpack_require__(398); +var _promise = __webpack_require__(171); var _promise2 = _interopRequireDefault(_promise); @@ -111,12 +118,6 @@ exports.default = function (fn) { }; }; -/***/ }), -/* 1 */ -/***/ (function(module, exports) { - -module.exports = require("path"); - /***/ }), /* 2 */ /***/ (function(module, exports) { @@ -142,11 +143,29 @@ class MessageError extends Error { } exports.MessageError = MessageError; +class ProcessSpawnError extends MessageError { + constructor(msg, code, process) { + super(msg, code); + this.process = process; + } + +} + +exports.ProcessSpawnError = ProcessSpawnError; class SecurityError extends MessageError {} exports.SecurityError = SecurityError; -class SpawnError extends MessageError {} -exports.SpawnError = SpawnError; +class ProcessTermError extends MessageError {} + +exports.ProcessTermError = ProcessTermError; +class ResponseError extends Error { + constructor(msg, responseCode) { + super(msg); + this.responseCode = responseCode; + } + +} +exports.ResponseError = ResponseError; /***/ }), /* 4 */ @@ -158,12 +177,12 @@ exports.SpawnError = SpawnError; Object.defineProperty(exports, "__esModule", { value: true }); -exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.fileDatesEqual = exports.glob = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.unlink = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.readFileBuffer = exports.lockQueue = undefined; +exports.getFirstSuitableFolder = exports.readFirstAvailableStream = exports.makeTempDir = exports.hardlinksWork = exports.writeFilePreservingEol = exports.getFileSizeOnDisk = exports.walk = exports.symlink = exports.find = exports.readJsonAndFile = exports.readJson = exports.readFileAny = exports.hardlinkBulk = exports.copyBulk = exports.fileDatesEqual = exports.glob = exports.link = exports.chmod = exports.lstat = exports.exists = exports.mkdirp = exports.unlink = exports.stat = exports.access = exports.rename = exports.readdir = exports.realpath = exports.readlink = exports.writeFile = exports.readFileBuffer = exports.lockQueue = exports.constants = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } let buildActionsForCopy = (() => { @@ -178,10 +197,17 @@ let buildActionsForCopy = (() => { const onFresh = data.onFresh || noop; const onDone = data.onDone || noop; - files.add(dest); + + // TODO https://github.com/yarnpkg/yarn/issues/3751 + // related to bundled dependencies handling + if (files.has(dest.toLowerCase())) { + reporter.warn(`The case-insensitive file ${dest} shouldn't be copied twice in one bulk copy`); + } else { + files.add(dest.toLowerCase()); + } if (type === 'symlink') { - yield mkdirp(path.dirname(dest)); + yield mkdirp((_path || _load_path()).default.dirname(dest)); onFresh(); actions.push({ type: 'symlink', @@ -192,7 +218,7 @@ let buildActionsForCopy = (() => { return; } - if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) { + if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { // ignored file return; } @@ -254,12 +280,12 @@ let buildActionsForCopy = (() => { for (const file of destFiles) { if (srcFiles.indexOf(file) < 0) { - const loc = path.join(dest, file); + const loc = (_path || _load_path()).default.join(dest, file); possibleExtraneous.add(loc); if ((yield lstat(loc)).isDirectory()) { for (const file of yield readdir(loc)) { - possibleExtraneous.add(path.join(loc, file)); + possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); } } } @@ -267,6 +293,11 @@ let buildActionsForCopy = (() => { } } + if (destStat && destStat.isSymbolicLink()) { + yield unlink(dest); + destStat = null; + } + if (srcStat.isSymbolicLink()) { onFresh(); const linkname = yield readlink(src); @@ -282,9 +313,9 @@ let buildActionsForCopy = (() => { yield mkdirp(dest); } - const destParts = dest.split(path.sep); + const destParts = dest.split((_path || _load_path()).default.sep); while (destParts.length) { - files.add(destParts.join(path.sep)); + files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); destParts.pop(); } @@ -296,14 +327,14 @@ let buildActionsForCopy = (() => { } for (const file of srcFiles) { queue.push({ - dest: path.join(dest, file), + dest: (_path || _load_path()).default.join(dest, file), onFresh, onDone: function () { if (--remaining === 0) { onDone(); } }, - src: path.join(src, file) + src: (_path || _load_path()).default.join(src, file) }); } } else if (srcStat.isFile()) { @@ -361,7 +392,7 @@ let buildActionsForCopy = (() => { } for (const loc of possibleExtraneous) { - if (files.has(loc)) { + if (files.has(loc.toLowerCase())) { possibleExtraneous.delete(loc); } } @@ -385,9 +416,18 @@ let buildActionsForHardlink = (() => { const onFresh = data.onFresh || noop; const onDone = data.onDone || noop; - files.add(dest); + if (files.has(dest.toLowerCase())) { + // Fixes issue https://github.com/yarnpkg/yarn/issues/2734 + // When bulk hardlinking we have A -> B structure that we want to hardlink to A1 -> B1, + // package-linker passes that modules A1 and B1 need to be hardlinked, + // the recursive linking algorithm of A1 ends up scheduling files in B1 to be linked twice which will case + // an exception. + onDone(); + return; + } + files.add(dest.toLowerCase()); - if (events.ignoreBasenames.indexOf(path.basename(src)) >= 0) { + if (events.ignoreBasenames.indexOf((_path || _load_path()).default.basename(src)) >= 0) { // ignored file return; } @@ -441,12 +481,12 @@ let buildActionsForHardlink = (() => { for (const file of destFiles) { if (srcFiles.indexOf(file) < 0) { - const loc = path.join(dest, file); + const loc = (_path || _load_path()).default.join(dest, file); possibleExtraneous.add(loc); if ((yield lstat(loc)).isDirectory()) { for (const file of yield readdir(loc)) { - possibleExtraneous.add(path.join(loc, file)); + possibleExtraneous.add((_path || _load_path()).default.join(loc, file)); } } } @@ -467,9 +507,9 @@ let buildActionsForHardlink = (() => { reporter.verbose(reporter.lang('verboseFileFolder', dest)); yield mkdirp(dest); - const destParts = dest.split(path.sep); + const destParts = dest.split((_path || _load_path()).default.sep); while (destParts.length) { - files.add(destParts.join(path.sep)); + files.add(destParts.join((_path || _load_path()).default.sep).toLowerCase()); destParts.pop(); } @@ -482,8 +522,8 @@ let buildActionsForHardlink = (() => { for (const file of srcFiles) { queue.push({ onFresh, - src: path.join(src, file), - dest: path.join(dest, file), + src: (_path || _load_path()).default.join(src, file), + dest: (_path || _load_path()).default.join(dest, file), onDone: function () { if (--remaining === 0) { onDone(); @@ -544,7 +584,7 @@ let buildActionsForHardlink = (() => { } for (const loc of possibleExtraneous) { - if (files.has(loc)) { + if (files.has(loc.toLowerCase())) { possibleExtraneous.delete(loc); } } @@ -587,11 +627,21 @@ let copyBulk = exports.copyBulk = (() => { return delete currentlyWriting[data.dest]; }; reporter.verbose(reporter.lang('verboseFileCopy', data.src, data.dest)); - return currentlyWriting[data.dest] = readFileBuffer(data.src).then(function (d) { - return writeFile(data.dest, d, { mode: data.mode }); - }).then(function () { + return currentlyWriting[data.dest] = readFileBuffer(data.src).then((() => { + var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (d) { + // we need to do this because of case-insensitive filesystems, which wouldn't properly + // change the file name in case of a file being renamed + yield unlink(data.dest); + + return writeFile(data.dest, d, { mode: data.mode }); + }); + + return function (_x15) { + return _ref7.apply(this, arguments); + }; + })()).then(function () { return new Promise(function (resolve, reject) { - fs.utimes(data.dest, data.atime, data.mtime, function (err) { + (_fs || _load_fs()).default.utimes(data.dest, data.atime, data.mtime, function (err) { if (err) { reject(err); } else { @@ -618,7 +668,7 @@ let copyBulk = exports.copyBulk = (() => { return action.type === 'symlink'; }); yield (_promise || _load_promise()).queue(symlinkActions, function (data) { - const linkname = path.resolve(path.dirname(data.dest), data.linkname); + const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); return symlink(linkname, data.dest); }); @@ -630,7 +680,7 @@ let copyBulk = exports.copyBulk = (() => { })(); let hardlinkBulk = exports.hardlinkBulk = (() => { - var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { + var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (queue, reporter, _events) { const events = { onStart: _events && _events.onStart || noop, onProgress: _events && _events.onProgress || noop, @@ -647,7 +697,7 @@ let hardlinkBulk = exports.hardlinkBulk = (() => { }); yield (_promise || _load_promise()).queue(fileActions, (() => { - var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { + var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (data) { reporter.verbose(reporter.lang('verboseFileLink', data.src, data.dest)); if (data.removeDest) { yield unlink(data.dest); @@ -655,8 +705,8 @@ let hardlinkBulk = exports.hardlinkBulk = (() => { yield link(data.src, data.dest); }); - return function (_x18) { - return _ref8.apply(this, arguments); + return function (_x19) { + return _ref9.apply(this, arguments); }; })(), CONCURRENT_QUEUE_ITEMS); @@ -665,19 +715,19 @@ let hardlinkBulk = exports.hardlinkBulk = (() => { return action.type === 'symlink'; }); yield (_promise || _load_promise()).queue(symlinkActions, function (data) { - const linkname = path.resolve(path.dirname(data.dest), data.linkname); + const linkname = (_path || _load_path()).default.resolve((_path || _load_path()).default.dirname(data.dest), data.linkname); reporter.verbose(reporter.lang('verboseFileSymlink', data.dest, linkname)); return symlink(linkname, data.dest); }); }); - return function hardlinkBulk(_x15, _x16, _x17) { - return _ref7.apply(this, arguments); + return function hardlinkBulk(_x16, _x17, _x18) { + return _ref8.apply(this, arguments); }; })(); let readFileAny = exports.readFileAny = (() => { - var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) { + var _ref10 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (files) { for (const file of files) { if (yield exists(file)) { return readFile(file); @@ -686,23 +736,23 @@ let readFileAny = exports.readFileAny = (() => { return null; }); - return function readFileAny(_x19) { - return _ref9.apply(this, arguments); + return function readFileAny(_x20) { + return _ref10.apply(this, arguments); }; })(); let readJson = exports.readJson = (() => { - var _ref10 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { return (yield readJsonAndFile(loc)).object; }); - return function readJson(_x20) { - return _ref10.apply(this, arguments); + return function readJson(_x21) { + return _ref11.apply(this, arguments); }; })(); let readJsonAndFile = exports.readJsonAndFile = (() => { - var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + var _ref12 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { const file = yield readFile(loc); try { return { @@ -715,17 +765,17 @@ let readJsonAndFile = exports.readJsonAndFile = (() => { } }); - return function readJsonAndFile(_x21) { - return _ref11.apply(this, arguments); + return function readJsonAndFile(_x22) { + return _ref12.apply(this, arguments); }; })(); let find = exports.find = (() => { - var _ref12 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) { - const parts = dir.split(path.sep); + var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (filename, dir) { + const parts = dir.split((_path || _load_path()).default.sep); while (parts.length) { - const loc = parts.concat(filename).join(path.sep); + const loc = parts.concat(filename).join((_path || _load_path()).default.sep); if (yield exists(loc)) { return loc; @@ -737,13 +787,13 @@ let find = exports.find = (() => { return false; }); - return function find(_x22, _x23) { - return _ref12.apply(this, arguments); + return function find(_x23, _x24) { + return _ref13.apply(this, arguments); }; })(); let symlink = exports.symlink = (() => { - var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { + var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { try { const stats = yield lstat(dest); @@ -769,11 +819,13 @@ let symlink = exports.symlink = (() => { // use relative paths otherwise which will be retained if the directory is moved let relative; if (yield exists(src)) { - relative = path.relative(fs.realpathSync(path.dirname(dest)), fs.realpathSync(src)); + relative = (_path || _load_path()).default.relative((_fs || _load_fs()).default.realpathSync((_path || _load_path()).default.dirname(dest)), (_fs || _load_fs()).default.realpathSync(src)); } else { - relative = path.relative(path.dirname(dest), src); + relative = (_path || _load_path()).default.relative((_path || _load_path()).default.dirname(dest), src); } - yield fsSymlink(relative, dest); + // When path.relative returns an empty string for the current directory, we should instead use + // '.', which is a valid fs.symlink target. + yield fsSymlink(relative || '.', dest); } } catch (err) { if (err.code === 'EEXIST') { @@ -785,13 +837,13 @@ let symlink = exports.symlink = (() => { } }); - return function symlink(_x24, _x25) { - return _ref13.apply(this, arguments); + return function symlink(_x25, _x26) { + return _ref14.apply(this, arguments); }; })(); let walk = exports.walk = (() => { - var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir) { + var _ref15 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir, relativeDir) { let ignoreBasenames = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set(); let files = []; @@ -804,8 +856,8 @@ let walk = exports.walk = (() => { } for (const name of filenames) { - const relative = relativeDir ? path.join(relativeDir, name) : name; - const loc = path.join(dir, name); + const relative = relativeDir ? (_path || _load_path()).default.join(relativeDir, name) : name; + const loc = (_path || _load_path()).default.join(dir, name); const stat = yield lstat(loc); files.push({ @@ -823,13 +875,13 @@ let walk = exports.walk = (() => { return files; }); - return function walk(_x26, _x27) { - return _ref14.apply(this, arguments); + return function walk(_x27, _x28) { + return _ref15.apply(this, arguments); }; })(); let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => { - var _ref15 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { + var _ref16 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (loc) { const stat = yield lstat(loc); const size = stat.size, blockSize = stat.blksize; @@ -838,13 +890,13 @@ let getFileSizeOnDisk = exports.getFileSizeOnDisk = (() => { return Math.ceil(size / blockSize) * blockSize; }); - return function getFileSizeOnDisk(_x29) { - return _ref15.apply(this, arguments); + return function getFileSizeOnDisk(_x30) { + return _ref16.apply(this, arguments); }; })(); let getEolFromFile = (() => { - var _ref16 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) { + var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path) { if (!(yield exists(path))) { return undefined; } @@ -862,30 +914,30 @@ let getEolFromFile = (() => { return undefined; }); - return function getEolFromFile(_x30) { - return _ref16.apply(this, arguments); + return function getEolFromFile(_x31) { + return _ref17.apply(this, arguments); }; })(); let writeFilePreservingEol = exports.writeFilePreservingEol = (() => { - var _ref17 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) { - const eol = (yield getEolFromFile(path)) || os.EOL; + var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (path, data) { + const eol = (yield getEolFromFile(path)) || (_os || _load_os()).default.EOL; if (eol !== '\n') { data = data.replace(/\n/g, eol); } - yield (0, (_promise2 || _load_promise2()).promisify)(fs.writeFile)(path, data); + yield (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.writeFile)(path, data); }); - return function writeFilePreservingEol(_x31, _x32) { - return _ref17.apply(this, arguments); + return function writeFilePreservingEol(_x32, _x33) { + return _ref18.apply(this, arguments); }; })(); let hardlinksWork = exports.hardlinksWork = (() => { - var _ref18 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) { + var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) { const filename = 'test-file' + Math.random(); - const file = path.join(dir, filename); - const fileLink = path.join(dir, filename + '-link'); + const file = (_path || _load_path()).default.join(dir, filename); + const fileLink = (_path || _load_path()).default.join(dir, filename + '-link'); try { yield writeFile(file, 'test'); yield link(file, fileLink); @@ -898,8 +950,8 @@ let hardlinksWork = exports.hardlinksWork = (() => { return true; }); - return function hardlinksWork(_x33) { - return _ref18.apply(this, arguments); + return function hardlinksWork(_x34) { + return _ref19.apply(this, arguments); }; })(); @@ -907,15 +959,81 @@ let hardlinksWork = exports.hardlinksWork = (() => { let makeTempDir = exports.makeTempDir = (() => { - var _ref19 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) { - const dir = path.join(os.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`); + var _ref20 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (prefix) { + const dir = (_path || _load_path()).default.join((_os || _load_os()).default.tmpdir(), `yarn-${prefix || ''}-${Date.now()}-${Math.random()}`); yield unlink(dir); yield mkdirp(dir); return dir; }); - return function makeTempDir(_x34) { - return _ref19.apply(this, arguments); + return function makeTempDir(_x35) { + return _ref20.apply(this, arguments); + }; +})(); + +let readFirstAvailableStream = exports.readFirstAvailableStream = (() => { + var _ref21 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths) { + var _this = this; + + let stream; + const triedPaths = []; + for (const tarballPath of paths) { + if (tarballPath) { + try { + // We need the weird `await new Promise()` construct for `createReadStream` because + // it always returns a ReadStream object but immediately triggers an `error` event + // on it if it fails to open the file, instead of throwing an exception. If this event + // is not handled, it crashes node. A saner way to handle this with multiple tries is + // the following construct. + stream = yield new Promise(function (resolve, reject) { + const maybeStream = (_fs || _load_fs()).default.createReadStream(tarballPath); + maybeStream.on('error', reject).on('readable', resolve.bind(_this, maybeStream)); + }); + break; + } catch (err) { + // Try the next one + triedPaths.push(tarballPath); + } + } + } + + return { stream, triedPaths }; + }); + + return function readFirstAvailableStream(_x36) { + return _ref21.apply(this, arguments); + }; +})(); + +let getFirstSuitableFolder = exports.getFirstSuitableFolder = (() => { + var _ref22 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (paths) { + let mode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : constants.W_OK | constants.X_OK; + + const result = { + skipped: [], + folder: null + }; + + for (const folder of paths) { + try { + yield mkdirp(folder); + yield access(folder, mode); + + result.folder = folder; + + return result; + } catch (error) { + result.skipped.push({ + error, + folder + }); + } + } + return result; + }); + + return function getFirstSuitableFolder(_x37) { + return _ref22.apply(this, arguments); }; })(); @@ -924,63 +1042,87 @@ exports.readFile = readFile; exports.readFileRaw = readFileRaw; exports.normalizeOS = normalizeOS; +var _fs; + +function _load_fs() { + return _fs = _interopRequireDefault(__webpack_require__(5)); +} + +var _glob; + +function _load_glob() { + return _glob = _interopRequireDefault(__webpack_require__(71)); +} + +var _os; + +function _load_os() { + return _os = _interopRequireDefault(__webpack_require__(47)); +} + +var _path; + +function _load_path() { + return _path = _interopRequireDefault(__webpack_require__(0)); +} + var _blockingQueue; function _load_blockingQueue() { - return _blockingQueue = _interopRequireDefault(__webpack_require__(84)); + return _blockingQueue = _interopRequireDefault(__webpack_require__(79)); } var _promise; function _load_promise() { - return _promise = _interopRequireWildcard(__webpack_require__(64)); + return _promise = _interopRequireWildcard(__webpack_require__(53)); } var _promise2; function _load_promise2() { - return _promise2 = __webpack_require__(64); + return _promise2 = __webpack_require__(53); } var _map; function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); + return _map = _interopRequireDefault(__webpack_require__(16)); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const fs = __webpack_require__(6); - -const globModule = __webpack_require__(150); -const os = __webpack_require__(113); -const path = __webpack_require__(1); +const constants = exports.constants = typeof (_fs || _load_fs()).default.constants !== 'undefined' ? (_fs || _load_fs()).default.constants : { + R_OK: (_fs || _load_fs()).default.R_OK, + W_OK: (_fs || _load_fs()).default.W_OK, + X_OK: (_fs || _load_fs()).default.X_OK +}; const lockQueue = exports.lockQueue = new (_blockingQueue || _load_blockingQueue()).default('fs lock'); -const readFileBuffer = exports.readFileBuffer = (0, (_promise2 || _load_promise2()).promisify)(fs.readFile); -const writeFile = exports.writeFile = (0, (_promise2 || _load_promise2()).promisify)(fs.writeFile); -const readlink = exports.readlink = (0, (_promise2 || _load_promise2()).promisify)(fs.readlink); -const realpath = exports.realpath = (0, (_promise2 || _load_promise2()).promisify)(fs.realpath); -const readdir = exports.readdir = (0, (_promise2 || _load_promise2()).promisify)(fs.readdir); -const rename = exports.rename = (0, (_promise2 || _load_promise2()).promisify)(fs.rename); -const access = exports.access = (0, (_promise2 || _load_promise2()).promisify)(fs.access); -const stat = exports.stat = (0, (_promise2 || _load_promise2()).promisify)(fs.stat); -const unlink = exports.unlink = (0, (_promise2 || _load_promise2()).promisify)(__webpack_require__(602)); -const mkdirp = exports.mkdirp = (0, (_promise2 || _load_promise2()).promisify)(__webpack_require__(160)); -const exists = exports.exists = (0, (_promise2 || _load_promise2()).promisify)(fs.exists, true); -const lstat = exports.lstat = (0, (_promise2 || _load_promise2()).promisify)(fs.lstat); -const chmod = exports.chmod = (0, (_promise2 || _load_promise2()).promisify)(fs.chmod); -const link = exports.link = (0, (_promise2 || _load_promise2()).promisify)(fs.link); -const glob = exports.glob = (0, (_promise2 || _load_promise2()).promisify)(globModule); +const readFileBuffer = exports.readFileBuffer = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readFile); +const writeFile = exports.writeFile = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.writeFile); +const readlink = exports.readlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readlink); +const realpath = exports.realpath = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.realpath); +const readdir = exports.readdir = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.readdir); +const rename = exports.rename = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.rename); +const access = exports.access = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.access); +const stat = exports.stat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.stat); +const unlink = exports.unlink = (0, (_promise2 || _load_promise2()).promisify)(__webpack_require__(224)); +const mkdirp = exports.mkdirp = (0, (_promise2 || _load_promise2()).promisify)(__webpack_require__(114)); +const exists = exports.exists = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.exists, true); +const lstat = exports.lstat = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.lstat); +const chmod = exports.chmod = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.chmod); +const link = exports.link = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.link); +const glob = exports.glob = (0, (_promise2 || _load_promise2()).promisify)((_glob || _load_glob()).default); const CONCURRENT_QUEUE_ITEMS = 4; -const fsSymlink = (0, (_promise2 || _load_promise2()).promisify)(fs.symlink); -const invariant = __webpack_require__(5); -const stripBOM = __webpack_require__(268); +const fsSymlink = (0, (_promise2 || _load_promise2()).promisify)((_fs || _load_fs()).default.symlink); +const invariant = __webpack_require__(7); +const stripBOM = __webpack_require__(119); const noop = () => {}; @@ -1020,7 +1162,7 @@ function copy(src, dest, reporter) { function _readFile(loc, encoding) { return new Promise((resolve, reject) => { - fs.readFile(loc, encoding, function (err, content) { + (_fs || _load_fs()).default.readFile(loc, encoding, function (err, content) { if (err) { reject(err); } else { @@ -1047,6 +1189,154 @@ const lf = new Buffer('\n', 'utf8')[0]; /***/ }), /* 5 */ +/***/ (function(module, exports) { + +module.exports = require("fs"); + +/***/ }), +/* 6 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isProduction = isProduction; +exports.getPathKey = getPathKey; +const os = __webpack_require__(47); +const path = __webpack_require__(0); +const userHome = __webpack_require__(62).default; +const isWebpackBundle = __webpack_require__(214); + +const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']; + +const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com'; + +const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/'; +const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh'; +const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi'; + +const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version'; +const SELF_UPDATE_TARBALL_URL = exports.SELF_UPDATE_TARBALL_URL = 'https://yarnpkg.com/latest.tar.gz'; +const SELF_UPDATE_DOWNLOAD_FOLDER = exports.SELF_UPDATE_DOWNLOAD_FOLDER = 'updates'; + +// cache version, bump whenever we make backwards incompatible changes +const CACHE_VERSION = exports.CACHE_VERSION = 1; + +// lockfile version, bump whenever we make backwards incompatible changes +const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1; + +// max amount of network requests to perform concurrently +const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8; + +// HTTP timeout used when downloading packages +const NETWORK_TIMEOUT = exports.NETWORK_TIMEOUT = 30 * 1000; // in milliseconds + +// max amount of child processes to execute concurrently +const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5; + +const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid']; + +function getDirectory(category) { + // use %LOCALAPPDATA%/Yarn on Windows + if (process.platform === 'win32' && process.env.LOCALAPPDATA) { + return path.join(process.env.LOCALAPPDATA, 'Yarn', category); + } + + // otherwise use ~/.{category}/yarn + return path.join(userHome, `.${category}`, 'yarn'); +} + +function getPreferredCacheDirectories() { + const preferredCacheDirectories = []; + + if (process.platform === 'darwin') { + preferredCacheDirectories.push(path.join(userHome, 'Library', 'Caches', 'Yarn')); + } else { + preferredCacheDirectories.push(getDirectory('cache')); + } + + preferredCacheDirectories.push(path.join(os.tmpdir(), '.yarn-cache')); + + return preferredCacheDirectories; +} + +const PREFERRED_MODULE_CACHE_DIRECTORIES = exports.PREFERRED_MODULE_CACHE_DIRECTORIES = getPreferredCacheDirectories(); +const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getDirectory('config'); +const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(CONFIG_DIRECTORY, 'link'); +const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(CONFIG_DIRECTORY, 'global'); + +const NODE_BIN_PATH = exports.NODE_BIN_PATH = process.execPath; +const YARN_BIN_PATH = exports.YARN_BIN_PATH = getYarnBinPath(); + +// Webpack needs to be configured with node.__dirname/__filename = false +function getYarnBinPath() { + if (isWebpackBundle) { + return __filename; + } else { + return path.join(__dirname, '..', 'bin', 'yarn.js'); + } +} + +const NODE_MODULES_FOLDER = exports.NODE_MODULES_FOLDER = 'node_modules'; +const NODE_PACKAGE_JSON = exports.NODE_PACKAGE_JSON = 'package.json'; + +const POSIX_GLOBAL_PREFIX = exports.POSIX_GLOBAL_PREFIX = `${process.env.DESTDIR || ''}/usr/local`; +const FALLBACK_GLOBAL_PREFIX = exports.FALLBACK_GLOBAL_PREFIX = path.join(userHome, '.yarn'); + +const META_FOLDER = exports.META_FOLDER = '.yarn-meta'; +const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity'; +const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock'; +const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json'; +const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz'; +const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean'; +const ACCESS_FILENAME = exports.ACCESS_FILENAME = '.yarn-access'; + +const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' '; +const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997; +const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance'; + +const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env); + +function isProduction() { + let env = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.env; + + return env.NODE_ENV === 'production'; +} + +function getPathKey(platform, env) { + let pathKey = 'PATH'; + + // windows calls its path "Path" usually, but this is not guaranteed. + if (platform === 'win32') { + pathKey = 'Path'; + + for (const key in env) { + if (key.toLowerCase() === 'path') { + pathKey = key; + } + } + } + + return pathKey; +} + +const VERSION_COLOR_SCHEME = exports.VERSION_COLOR_SCHEME = { + major: 'red', + premajor: 'red', + minor: 'yellow', + preminor: 'yellow', + patch: 'green', + prepatch: 'green', + prerelease: 'red', + unchanged: 'white', + unknown: 'red' +}; + +/***/ }), +/* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -1106,19 +1396,29 @@ module.exports = invariant; /***/ }), -/* 6 */ +/* 8 */ /***/ (function(module, exports) { -module.exports = require("fs"); +module.exports = require("crypto"); /***/ }), -/* 7 */ -/***/ (function(module, exports) { +/* 9 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = require("crypto"); +var store = __webpack_require__(104)('wks') + , uid = __webpack_require__(107) + , Symbol = __webpack_require__(13).Symbol + , USE_SYMBOL = typeof Symbol == 'function'; + +var $exports = module.exports = function(name){ + return store[name] || (store[name] = + USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); +}; + +$exports.store = store; /***/ }), -/* 8 */ +/* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -1127,101 +1427,124 @@ module.exports = require("crypto"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.getPathKey = getPathKey; -const path = __webpack_require__(1); -const userHome = __webpack_require__(86).default; - -const DEPENDENCY_TYPES = exports.DEPENDENCY_TYPES = ['devDependencies', 'dependencies', 'optionalDependencies', 'peerDependencies']; - -const YARN_REGISTRY = exports.YARN_REGISTRY = 'https://registry.yarnpkg.com'; - -const YARN_DOCS = exports.YARN_DOCS = 'https://yarnpkg.com/en/docs/cli/'; -const YARN_INSTALLER_SH = exports.YARN_INSTALLER_SH = 'https://yarnpkg.com/install.sh'; -const YARN_INSTALLER_MSI = exports.YARN_INSTALLER_MSI = 'https://yarnpkg.com/latest.msi'; - -const SELF_UPDATE_VERSION_URL = exports.SELF_UPDATE_VERSION_URL = 'https://yarnpkg.com/latest-version'; -const SELF_UPDATE_TARBALL_URL = exports.SELF_UPDATE_TARBALL_URL = 'https://yarnpkg.com/latest.tar.gz'; -const SELF_UPDATE_DOWNLOAD_FOLDER = exports.SELF_UPDATE_DOWNLOAD_FOLDER = 'updates'; - -// cache version, bump whenever we make backwards incompatible changes -const CACHE_VERSION = exports.CACHE_VERSION = 1; - -// lockfile version, bump whenever we make backwards incompatible changes -const LOCKFILE_VERSION = exports.LOCKFILE_VERSION = 1; +exports.consumeStream = consumeStream; +exports.sortAlpha = sortAlpha; +exports.entries = entries; +exports.removePrefix = removePrefix; +exports.removeSuffix = removeSuffix; +exports.addSuffix = addSuffix; +exports.hyphenate = hyphenate; +exports.camelCase = camelCase; +exports.compareSortedArrays = compareSortedArrays; +exports.sleep = sleep; +const _camelCase = __webpack_require__(175); -// max amount of network requests to perform concurrently -const NETWORK_CONCURRENCY = exports.NETWORK_CONCURRENCY = 8; +function consumeStream(stream) { + return new Promise((resolve, reject) => { + const buffers = []; -// HTTP timeout used when downloading packages -const NETWORK_TIMEOUT = exports.NETWORK_TIMEOUT = 30 * 1000; // in milliseconds + stream.on(`data`, buffer => { + buffers.push(buffer); + }); -// max amount of child processes to execute concurrently -const CHILD_CONCURRENCY = exports.CHILD_CONCURRENCY = 5; + stream.on(`end`, () => { + resolve(Buffer.concat(buffers)); + }); -const REQUIRED_PACKAGE_KEYS = exports.REQUIRED_PACKAGE_KEYS = ['name', 'version', '_uid']; + stream.on(`error`, error => { + reject(error); + }); + }); +} -function getDirectory(category) { - // use %LOCALAPPDATA%/Yarn on Windows - if (process.platform === 'win32' && process.env.LOCALAPPDATA) { - return path.join(process.env.LOCALAPPDATA, 'Yarn', category); +function sortAlpha(a, b) { + // sort alphabetically in a deterministic way + const shortLen = Math.min(a.length, b.length); + for (let i = 0; i < shortLen; i++) { + const aChar = a.charCodeAt(i); + const bChar = b.charCodeAt(i); + if (aChar !== bChar) { + return aChar - bChar; + } } + return a.length - b.length; +} - // otherwise use ~/.{category}/yarn - return path.join(userHome, `.${category}`, 'yarn'); +function entries(obj) { + const entries = []; + if (obj) { + for (const key in obj) { + entries.push([key, obj[key]]); + } + } + return entries; } -function getCacheDirectory() { - if (process.platform === 'darwin') { - return path.join(userHome, 'Library', 'Caches', 'Yarn'); +function removePrefix(pattern, prefix) { + if (pattern.startsWith(prefix)) { + pattern = pattern.slice(prefix.length); } - return getDirectory('cache'); + return pattern; } -const MODULE_CACHE_DIRECTORY = exports.MODULE_CACHE_DIRECTORY = getCacheDirectory(); -const CONFIG_DIRECTORY = exports.CONFIG_DIRECTORY = getDirectory('config'); -const LINK_REGISTRY_DIRECTORY = exports.LINK_REGISTRY_DIRECTORY = path.join(CONFIG_DIRECTORY, 'link'); -const GLOBAL_MODULE_DIRECTORY = exports.GLOBAL_MODULE_DIRECTORY = path.join(CONFIG_DIRECTORY, 'global'); +function removeSuffix(pattern, suffix) { + if (pattern.endsWith(suffix)) { + return pattern.slice(0, -suffix.length); + } -const META_FOLDER = exports.META_FOLDER = '.yarn-meta'; -const INTEGRITY_FILENAME = exports.INTEGRITY_FILENAME = '.yarn-integrity'; -const LOCKFILE_FILENAME = exports.LOCKFILE_FILENAME = 'yarn.lock'; -const METADATA_FILENAME = exports.METADATA_FILENAME = '.yarn-metadata.json'; -const TARBALL_FILENAME = exports.TARBALL_FILENAME = '.yarn-tarball.tgz'; -const CLEAN_FILENAME = exports.CLEAN_FILENAME = '.yarnclean'; + return pattern; +} -const DEFAULT_INDENT = exports.DEFAULT_INDENT = ' '; -const SINGLE_INSTANCE_PORT = exports.SINGLE_INSTANCE_PORT = 31997; -const SINGLE_INSTANCE_FILENAME = exports.SINGLE_INSTANCE_FILENAME = '.yarn-single-instance'; +function addSuffix(pattern, suffix) { + if (!pattern.endsWith(suffix)) { + return pattern + suffix; + } -const ENV_PATH_KEY = exports.ENV_PATH_KEY = getPathKey(process.platform, process.env); + return pattern; +} -function getPathKey(platform, env) { - let pathKey = 'PATH'; +function hyphenate(str) { + return str.replace(/[A-Z]/g, match => { + return '-' + match.charAt(0).toLowerCase(); + }); +} - // windows calls its path "Path" usually, but this is not guaranteed. - if (platform === 'win32') { - pathKey = 'Path'; +function camelCase(str) { + if (/[A-Z]/.test(str)) { + return null; + } else { + return _camelCase(str); + } +} - for (const key in env) { - if (key.toLowerCase() === 'path') { - pathKey = key; - } +function compareSortedArrays(array1, array2) { + if (array1.length !== array2.length) { + return false; + } + for (let i = 0, len = array1.length; i < len; i++) { + if (array1[i] !== array2[i]) { + return false; } } + return true; +} - return pathKey; +function sleep(ms) { + return new Promise(resolve => { + setTimeout(resolve, ms); + }); } /***/ }), -/* 9 */ +/* 11 */ /***/ (function(module, exports, __webpack_require__) { // Copyright (c) 2012, Mark Cavage. All rights reserved. // Copyright 2015 Joyent, Inc. -var assert = __webpack_require__(22); -var Stream = __webpack_require__(20).Stream; +var assert = __webpack_require__(18); +var Stream = __webpack_require__(26).Stream; var util = __webpack_require__(2); @@ -1431,7 +1754,7 @@ module.exports = _setExports(process.env.NODE_NDEBUG); /***/ }), -/* 10 */ +/* 12 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -1440,102 +1763,261 @@ module.exports = _setExports(process.env.NODE_NDEBUG); Object.defineProperty(exports, "__esModule", { value: true }); -exports.has2xxResponse = has2xxResponse; -exports.sortAlpha = sortAlpha; -exports.entries = entries; -exports.removePrefix = removePrefix; -exports.removeSuffix = removeSuffix; -exports.addSuffix = addSuffix; -exports.hyphenate = hyphenate; -exports.camelCase = camelCase; -exports.compareSortedArrays = compareSortedArrays; -const _camelCase = __webpack_require__(405); +exports.stringify = exports.parse = undefined; + +var _asyncToGenerator2; -function has2xxResponse(res) { - return res.responseCode >= 200 && res.responseCode < 300; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -function sortAlpha(a, b) { - // sort alphabetically in a deterministic way - const shortLen = Math.min(a.length, b.length); - for (let i = 0; i < shortLen; i++) { - const aChar = a.charCodeAt(i); - const bChar = b.charCodeAt(i); - if (aChar !== bChar) { - return aChar - bChar; - } - } - return a.length - b.length; +var _parse; + +function _load_parse() { + return _parse = __webpack_require__(76); } -function entries(obj) { - const entries = []; - if (obj) { - for (const key in obj) { - entries.push([key, obj[key]]); - } +Object.defineProperty(exports, 'parse', { + enumerable: true, + get: function () { + return _interopRequireDefault(_parse || _load_parse()).default; } - return entries; +}); + +var _stringify; + +function _load_stringify() { + return _stringify = __webpack_require__(152); } -function removePrefix(pattern, prefix) { - if (pattern.startsWith(prefix)) { - pattern = pattern.slice(prefix.length); +Object.defineProperty(exports, 'stringify', { + enumerable: true, + get: function () { + return _interopRequireDefault(_stringify || _load_stringify()).default; } +}); +exports.implodeEntry = implodeEntry; +exports.explodeEntry = explodeEntry; - return pattern; +var _misc; + +function _load_misc() { + return _misc = __webpack_require__(10); } -function removeSuffix(pattern, suffix) { - if (pattern.endsWith(suffix)) { - return pattern.slice(0, -suffix.length); - } +var _normalizePattern; - return pattern; +function _load_normalizePattern() { + return _normalizePattern = __webpack_require__(30); } -function addSuffix(pattern, suffix) { - if (!pattern.endsWith(suffix)) { - return pattern + suffix; - } +var _parse2; - return pattern; +function _load_parse2() { + return _parse2 = _interopRequireDefault(__webpack_require__(76)); } -function hyphenate(str) { - return str.replace(/[A-Z]/g, match => { - return '-' + match.charAt(0).toLowerCase(); - }); +var _constants; + +function _load_constants() { + return _constants = __webpack_require__(6); } -function camelCase(str) { - if (/[A-Z]/.test(str)) { - return null; - } else { - return _camelCase(str); - } +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } -function compareSortedArrays(array1, array2) { - if (array1.length !== array2.length) { - return false; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const invariant = __webpack_require__(7); + +const path = __webpack_require__(0); + +function getName(pattern) { + return (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern).name; +} + +function blankObjectUndefined(obj) { + return obj && Object.keys(obj).length ? obj : undefined; +} + +function keyForRemote(remote) { + return remote.resolved || (remote.reference && remote.hash ? `${remote.reference}#${remote.hash}` : null); +} + +function implodeEntry(pattern, obj) { + const inferredName = getName(pattern); + return { + name: inferredName === obj.name ? undefined : obj.name, + version: obj.version, + uid: obj.uid === obj.version ? undefined : obj.uid, + resolved: obj.resolved, + registry: obj.registry === 'npm' ? undefined : obj.registry, + dependencies: blankObjectUndefined(obj.dependencies), + optionalDependencies: blankObjectUndefined(obj.optionalDependencies), + permissions: blankObjectUndefined(obj.permissions) + }; +} + +function explodeEntry(pattern, obj) { + obj.optionalDependencies = obj.optionalDependencies || {}; + obj.dependencies = obj.dependencies || {}; + obj.uid = obj.uid || obj.version; + obj.permissions = obj.permissions || {}; + obj.registry = obj.registry || 'npm'; + obj.name = obj.name || getName(pattern); + return obj; +} + +class Lockfile { + constructor() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + let cache = _ref.cache, + source = _ref.source, + parseResultType = _ref.parseResultType; + + this.source = source || ''; + this.cache = cache; + this.parseResultType = parseResultType; } - for (let i = 0, len = array1.length; i < len; i++) { - if (array1[i] !== array2[i]) { - return false; + + // source string if the `cache` was parsed + + + static fromDirectory(dir, reporter) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // read the manifest in this directory + const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME); + + let lockfile; + let rawLockfile = ''; + let parseResult; + + if (yield (_fs || _load_fs()).exists(lockfileLoc)) { + rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc); + parseResult = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc); + + if (reporter) { + if (parseResult.type === 'merge') { + reporter.info(reporter.lang('lockfileMerged')); + } else if (parseResult.type === 'conflict') { + reporter.warn(reporter.lang('lockfileConflict')); + } + } + + lockfile = parseResult.object; + } else { + if (reporter) { + reporter.info(reporter.lang('noLockfileFound')); + } + } + + return new Lockfile({ cache: lockfile, source: rawLockfile, parseResultType: parseResult && parseResult.type }); + })(); + } + + getLocked(pattern) { + const cache = this.cache; + if (!cache) { + return undefined; + } + + const shrunk = pattern in cache && cache[pattern]; + + if (typeof shrunk === 'string') { + return this.getLocked(shrunk); + } else if (shrunk) { + explodeEntry(pattern, shrunk); + return shrunk; } + + return undefined; + } + + removePattern(pattern) { + const cache = this.cache; + if (!cache) { + return; + } + delete cache[pattern]; + } + + getLockfile(patterns) { + const lockfile = {}; + const seen = new Map(); + + // order by name so that lockfile manifest is assigned to the first dependency with this manifest + // the others that have the same remoteKey will just refer to the first + // ordering allows for consistency in lockfile when it is serialized + const sortedPatternsKeys = Object.keys(patterns).sort((_misc || _load_misc()).sortAlpha); + + for (const pattern of sortedPatternsKeys) { + const pkg = patterns[pattern]; + const remote = pkg._remote, + ref = pkg._reference; + + invariant(ref, 'Package is missing a reference'); + invariant(remote, 'Package is missing a remote'); + + const remoteKey = keyForRemote(remote); + const seenPattern = remoteKey && seen.get(remoteKey); + if (seenPattern) { + // no point in duplicating it + lockfile[pattern] = seenPattern; + + // if we're relying on our name being inferred and two of the patterns have + // different inferred names then we need to set it + if (!seenPattern.name && getName(pattern) !== pkg.name) { + seenPattern.name = pkg.name; + } + continue; + } + + const obj = implodeEntry(pattern, { + name: pkg.name, + version: pkg.version, + uid: pkg._uid, + resolved: remote.resolved, + registry: remote.registry, + dependencies: pkg.dependencies, + peerDependencies: pkg.peerDependencies, + optionalDependencies: pkg.optionalDependencies, + permissions: ref.permissions + }); + lockfile[pattern] = obj; + + if (remoteKey) { + seen.set(remoteKey, obj); + } + } + + return lockfile; } - return true; } +exports.default = Lockfile; /***/ }), -/* 11 */ +/* 13 */ +/***/ (function(module, exports) { + +// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 +var global = module.exports = typeof window != 'undefined' && window.Math == Math + ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); +if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef + +/***/ }), +/* 14 */ /***/ (function(module, exports) { module.exports = require("url"); /***/ }), -/* 12 */ +/* 15 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -1543,11 +2025,11 @@ module.exports = require("url"); exports.__esModule = true; -var _isIterable2 = __webpack_require__(396); +var _isIterable2 = __webpack_require__(448); var _isIterable3 = _interopRequireDefault(_isIterable2); -var _getIterator2 = __webpack_require__(395); +var _getIterator2 = __webpack_require__(447); var _getIterator3 = _interopRequireDefault(_getIterator2); @@ -1592,7 +2074,39 @@ exports.default = function () { }(); /***/ }), -/* 13 */ +/* 16 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = nullify; +function nullify() { + let obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + if (Array.isArray(obj)) { + for (const item of obj) { + nullify(item); + } + } else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') { + Object.setPrototypeOf(obj, null); + + // for..in can only be applied to 'object', not 'function' + if (typeof obj === 'object') { + for (const key in obj) { + nullify(obj[key]); + } + } + } + + return obj; +} + +/***/ }), +/* 17 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2015 Joyent, Inc. @@ -1610,9 +2124,9 @@ module.exports = { opensshCipherInfo: opensshCipherInfo }; -var assert = __webpack_require__(9); -var PrivateKey = __webpack_require__(18); -var crypto = __webpack_require__(7); +var assert = __webpack_require__(11); +var PrivateKey = __webpack_require__(25); +var crypto = __webpack_require__(8); var MAX_CLASS_DEPTH = 3; @@ -1799,7 +2313,7 @@ function calculateDSAPublic(g, p, x) { assert.buffer(p); assert.buffer(x); try { - var bigInt = __webpack_require__(40).BigInteger; + var bigInt = __webpack_require__(56).BigInteger; } catch (e) { throw (new Error('To load a PKCS#8 format DSA private key, ' + 'the node jsbn library is required.')); @@ -1816,7 +2330,7 @@ function addRSAMissing(key) { assert.object(key); assertCompatible(key, PrivateKey, [1, 1]); try { - var bigInt = __webpack_require__(40).BigInteger; + var bigInt = __webpack_require__(56).BigInteger; } catch (e) { throw (new Error('To write a PEM private key from ' + 'this source, the node jsbn lib is required.')); @@ -1886,19227 +2400,19216 @@ function opensshCipherInfo(cipher) { /***/ }), -/* 14 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - +/* 18 */ +/***/ (function(module, exports) { -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.stringify = exports.parse = undefined; +module.exports = require("assert"); -var _asyncToGenerator2; +/***/ }), +/* 19 */ +/***/ (function(module, exports) { -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +module.exports = function(module) { + if(!module.webpackPolyfill) { + module.deprecate = function() {}; + module.paths = []; + // module.parent = undefined by default + if(!module.children) module.children = []; + Object.defineProperty(module, "loaded", { + enumerable: true, + get: function() { + return module.l; + } + }); + Object.defineProperty(module, "id", { + enumerable: true, + get: function() { + return module.i; + } + }); + module.webpackPolyfill = 1; + } + return module; +}; -var _parse; -function _load_parse() { - return _parse = __webpack_require__(80); -} +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { -Object.defineProperty(exports, 'parse', { - enumerable: true, - get: function () { - return _interopRequireDefault(_parse || _load_parse()).default; - } -}); +"use strict"; -var _stringify; +var escapeStringRegexp = __webpack_require__(286); +var ansiStyles = __webpack_require__(371); +var stripAnsi = __webpack_require__(227); +var hasAnsi = __webpack_require__(520); +var supportsColor = __webpack_require__(454); +var defineProps = Object.defineProperties; +var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM); -function _load_stringify() { - return _stringify = __webpack_require__(81); +function Chalk(options) { + // detect mode if not set manually + this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; } -Object.defineProperty(exports, 'stringify', { - enumerable: true, - get: function () { - return _interopRequireDefault(_stringify || _load_stringify()).default; - } -}); -exports.implodeEntry = implodeEntry; -exports.explodeEntry = explodeEntry; +// use bright blue on Windows as the normal blue color is illegible +if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001b[94m'; +} -var _misc; +var styles = (function () { + var ret = {}; -function _load_misc() { - return _misc = __webpack_require__(10); -} + Object.keys(ansiStyles).forEach(function (key) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); -var _packageRequest; + ret[key] = { + get: function () { + return build.call(this, this._styles.concat(key)); + } + }; + }); -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); -} + return ret; +})(); -var _parse2; +var proto = defineProps(function chalk() {}, styles); -function _load_parse2() { - return _parse2 = _interopRequireDefault(__webpack_require__(80)); -} +function build(_styles) { + var builder = function () { + return applyStyle.apply(builder, arguments); + }; -var _constants; + builder._styles = _styles; + builder.enabled = this.enabled; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + /* eslint-disable no-proto */ + builder.__proto__ = proto; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); + return builder; } -var _fs; +function applyStyle() { + // support varags, but simply cast to string in case there's only one arg + var args = arguments; + var argsLen = args.length; + var str = argsLen !== 0 && String(arguments[0]); -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + if (argsLen > 1) { + // don't slice `arguments`, it prevents v8 optimizations + for (var a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (!this.enabled || !str) { + return str; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var nestedStyles = this._styles; + var i = nestedStyles.length; -const invariant = __webpack_require__(5); -const path = __webpack_require__(1); + // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + var originalDim = ansiStyles.dim.open; + if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) { + ansiStyles.dim.open = ''; + } -function getName(pattern) { - return (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern).name; -} + while (i--) { + var code = ansiStyles[nestedStyles[i]]; -function blankObjectUndefined(obj) { - return obj && Object.keys(obj).length ? obj : undefined; -} + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; + } -function implodeEntry(pattern, obj) { - const inferredName = getName(pattern); - return { - name: inferredName === obj.name ? undefined : obj.name, - version: obj.version, - uid: obj.uid === obj.version ? undefined : obj.uid, - resolved: obj.resolved, - registry: obj.registry === 'npm' ? undefined : obj.registry, - dependencies: blankObjectUndefined(obj.dependencies), - optionalDependencies: blankObjectUndefined(obj.optionalDependencies), - permissions: blankObjectUndefined(obj.permissions) - }; -} + // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue. + ansiStyles.dim.open = originalDim; -function explodeEntry(pattern, obj) { - obj.optionalDependencies = obj.optionalDependencies || {}; - obj.dependencies = obj.dependencies || {}; - obj.uid = obj.uid || obj.version; - obj.permissions = obj.permissions || {}; - obj.registry = obj.registry || 'npm'; - obj.name = obj.name || getName(pattern); - return obj; + return str; } -class Lockfile { - constructor(cache, source) { - this.source = source || ''; - this.cache = cache; - } +function init() { + var ret = {}; - // source string if the `cache` was parsed + Object.keys(styles).forEach(function (name) { + ret[name] = { + get: function () { + return build.call(this, [name]); + } + }; + }); + return ret; +} - static fromDirectory(dir, reporter) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // read the manifest in this directory - const lockfileLoc = path.join(dir, (_constants || _load_constants()).LOCKFILE_FILENAME); +defineProps(Chalk.prototype, init()); - let lockfile; - let rawLockfile = ''; +module.exports = new Chalk(); +module.exports.styles = ansiStyles; +module.exports.hasColor = hasAnsi; +module.exports.stripColor = stripAnsi; +module.exports.supportsColor = supportsColor; - if (yield (_fs || _load_fs()).exists(lockfileLoc)) { - rawLockfile = yield (_fs || _load_fs()).readFile(lockfileLoc); - lockfile = (0, (_parse2 || _load_parse2()).default)(rawLockfile, lockfileLoc); - } else { - if (reporter) { - reporter.info(reporter.lang('noLockfileFound')); - } - } - return new Lockfile(lockfile, rawLockfile); - })(); - } +/***/ }), +/* 21 */ +/***/ (function(module, exports) { - getLocked(pattern) { - const cache = this.cache; - if (!cache) { - return undefined; - } +var core = module.exports = {version: '2.4.0'}; +if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef - const shrunk = pattern in cache && cache[pattern]; +/***/ }), +/* 22 */ +/***/ (function(module, exports) { - if (typeof shrunk === 'string') { - return this.getLocked(shrunk); - } else if (shrunk) { - explodeEntry(pattern, shrunk); - return shrunk; - } +exports = module.exports = SemVer; - return undefined; - } +// The debug function is excluded entirely from the minified version. +/* nomin */ var debug; +/* nomin */ if (typeof process === 'object' && + /* nomin */ process.env && + /* nomin */ process.env.NODE_DEBUG && + /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) + /* nomin */ debug = function() { + /* nomin */ var args = Array.prototype.slice.call(arguments, 0); + /* nomin */ args.unshift('SEMVER'); + /* nomin */ console.log.apply(console, args); + /* nomin */ }; +/* nomin */ else + /* nomin */ debug = function() {}; - removePattern(pattern) { - const cache = this.cache; - if (!cache) { - return; - } - delete cache[pattern]; - } +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0'; - getLockfile(patterns) { - const lockfile = {}; - const seen = new Map(); +var MAX_LENGTH = 256; +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; - // order by name so that lockfile manifest is assigned to the first dependency with this manifest - // the others that have the same remote.resolved will just refer to the first - // ordering allows for consistency in lockfile when it is serialized - const sortedPatternsKeys = Object.keys(patterns).sort((_misc || _load_misc()).sortAlpha); +// The actual regexps go on exports.re +var re = exports.re = []; +var src = exports.src = []; +var R = 0; - for (const pattern of sortedPatternsKeys) { - const pkg = patterns[pattern]; - const remote = pkg._remote, - ref = pkg._reference; +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. - invariant(ref, 'Package is missing a reference'); - invariant(remote, 'Package is missing a remote'); +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. - const seenPattern = remote.resolved && seen.get(remote.resolved); - if (seenPattern) { - // no point in duplicating it - lockfile[pattern] = seenPattern; +var NUMERICIDENTIFIER = R++; +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; +var NUMERICIDENTIFIERLOOSE = R++; +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; - // if we're relying on our name being inferred and two of the patterns have - // different inferred names then we need to set it - if (!seenPattern.name && getName(pattern) !== pkg.name) { - seenPattern.name = pkg.name; - } - continue; - } - const obj = implodeEntry(pattern, { - name: pkg.name, - version: pkg.version, - uid: pkg._uid, - resolved: remote.resolved, - registry: remote.registry, - dependencies: pkg.dependencies, - peerDependencies: pkg.peerDependencies, - optionalDependencies: pkg.optionalDependencies, - permissions: ref.permissions - }); - lockfile[pattern] = obj; +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. - if (remote.resolved) { - seen.set(remote.resolved, obj); - } - } +var NONNUMERICIDENTIFIER = R++; +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; - return lockfile; - } -} -exports.default = Lockfile; -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { +// ## Main Version +// Three dot-separated numeric identifiers. -"use strict"; +var MAINVERSION = R++; +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')'; -var escapeStringRegexp = __webpack_require__(231); -var ansiStyles = __webpack_require__(316); -var stripAnsi = __webpack_require__(166); -var hasAnsi = __webpack_require__(504); -var supportsColor = __webpack_require__(406); -var defineProps = Object.defineProperties; -var isSimpleWindowsTerm = process.platform === 'win32' && !/^xterm/i.test(process.env.TERM); +var MAINVERSIONLOOSE = R++; +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; -function Chalk(options) { - // detect mode if not set manually - this.enabled = !options || options.enabled === undefined ? supportsColor : options.enabled; -} +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. -// use bright blue on Windows as the normal blue color is illegible -if (isSimpleWindowsTerm) { - ansiStyles.blue.open = '\u001b[94m'; -} +var PRERELEASEIDENTIFIER = R++; +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; -var styles = (function () { - var ret = {}; +var PRERELEASEIDENTIFIERLOOSE = R++; +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')'; - Object.keys(ansiStyles).forEach(function (key) { - ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - ret[key] = { - get: function () { - return build.call(this, this._styles.concat(key)); - } - }; - }); +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. - return ret; -})(); +var PRERELEASE = R++; +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; -var proto = defineProps(function chalk() {}, styles); +var PRERELEASELOOSE = R++; +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; -function build(_styles) { - var builder = function () { - return applyStyle.apply(builder, arguments); - }; +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. - builder._styles = _styles; - builder.enabled = this.enabled; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - /* eslint-disable no-proto */ - builder.__proto__ = proto; +var BUILDIDENTIFIER = R++; +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; - return builder; -} +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. -function applyStyle() { - // support varags, but simply cast to string in case there's only one arg - var args = arguments; - var argsLen = args.length; - var str = argsLen !== 0 && String(arguments[0]); +var BUILD = R++; +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; - if (argsLen > 1) { - // don't slice `arguments`, it prevents v8 optimizations - for (var a = 1; a < argsLen; a++) { - str += ' ' + args[a]; - } - } - if (!this.enabled || !str) { - return str; - } +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. - var nestedStyles = this._styles; - var i = nestedStyles.length; +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. - // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, - // see https://github.com/chalk/chalk/issues/58 - // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. - var originalDim = ansiStyles.dim.open; - if (isSimpleWindowsTerm && (nestedStyles.indexOf('gray') !== -1 || nestedStyles.indexOf('grey') !== -1)) { - ansiStyles.dim.open = ''; - } +var FULL = R++; +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?'; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; +src[FULL] = '^' + FULLPLAIN + '$'; - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - str = code.open + str.replace(code.closeRe, code.open) + code.close; - } +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?'; - // Reset the original 'dim' if we changed it to work around the Windows dimmed gray issue. - ansiStyles.dim.open = originalDim; +var LOOSE = R++; +src[LOOSE] = '^' + LOOSEPLAIN + '$'; - return str; -} +var GTLT = R++; +src[GTLT] = '((?:<|>)?=?)'; -function init() { - var ret = {}; +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++; +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; +var XRANGEIDENTIFIER = R++; +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; - Object.keys(styles).forEach(function (name) { - ret[name] = { - get: function () { - return build.call(this, [name]); - } - }; - }); +var XRANGEPLAIN = R++; +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?'; - return ret; -} +var XRANGEPLAINLOOSE = R++; +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?'; -defineProps(Chalk.prototype, init()); +var XRANGE = R++; +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; +var XRANGELOOSE = R++; +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; -module.exports = new Chalk(); -module.exports.styles = ansiStyles; -module.exports.hasColor = hasAnsi; -module.exports.stripColor = stripAnsi; -module.exports.supportsColor = supportsColor; +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++; +src[LONETILDE] = '(?:~>?)'; +var TILDETRIM = R++; +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); +var tildeTrimReplace = '$1~'; -/***/ }), -/* 16 */ -/***/ (function(module, exports) { +var TILDE = R++; +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; +var TILDELOOSE = R++; +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; -// Copyright 2015 Joyent, Inc. +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++; +src[LONECARET] = '(?:\\^)'; -var algInfo = { - 'dsa': { - parts: ['p', 'q', 'g', 'y'], - sizePart: 'p' - }, - 'rsa': { - parts: ['e', 'n'], - sizePart: 'n' - }, - 'ecdsa': { - parts: ['curve', 'Q'], - sizePart: 'Q' - }, - 'ed25519': { - parts: ['R'], - normalize: false, - sizePart: 'R' - } -}; -algInfo['curve25519'] = algInfo['ed25519']; +var CARETTRIM = R++; +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); +var caretTrimReplace = '$1^'; -var algPrivInfo = { - 'dsa': { - parts: ['p', 'q', 'g', 'y', 'x'] - }, - 'rsa': { - parts: ['n', 'e', 'd', 'iqmp', 'p', 'q'] - }, - 'ecdsa': { - parts: ['curve', 'Q', 'd'] - }, - 'ed25519': { - parts: ['R', 'r'], - normalize: false - } -}; -algPrivInfo['curve25519'] = algPrivInfo['ed25519']; +var CARET = R++; +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; +var CARETLOOSE = R++; +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; -var hashAlgs = { - 'md5': true, - 'sha1': true, - 'sha256': true, - 'sha384': true, - 'sha512': true -}; +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++; +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; +var COMPARATOR = R++; +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; -/* - * Taken from - * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf - */ -var curves = { - 'nistp256': { - size: 256, - pkcs8oid: '1.2.840.10045.3.1.7', - p: new Buffer(('00' + - 'ffffffff 00000001 00000000 00000000' + - '00000000 ffffffff ffffffff ffffffff'). - replace(/ /g, ''), 'hex'), - a: new Buffer(('00' + - 'FFFFFFFF 00000001 00000000 00000000' + - '00000000 FFFFFFFF FFFFFFFF FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: new Buffer(( - '5ac635d8 aa3a93e7 b3ebbd55 769886bc' + - '651d06b0 cc53b0f6 3bce3c3e 27d2604b'). - replace(/ /g, ''), 'hex'), - s: new Buffer(('00' + - 'c49d3608 86e70493 6a6678e1 139d26b7' + - '819f7e90'). - replace(/ /g, ''), 'hex'), - n: new Buffer(('00' + - 'ffffffff 00000000 ffffffff ffffffff' + - 'bce6faad a7179e84 f3b9cac2 fc632551'). - replace(/ /g, ''), 'hex'), - G: new Buffer(('04' + - '6b17d1f2 e12c4247 f8bce6e5 63a440f2' + - '77037d81 2deb33a0 f4a13945 d898c296' + - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' + - '2bce3357 6b315ece cbb64068 37bf51f5'). - replace(/ /g, ''), 'hex') - }, - 'nistp384': { - size: 384, - pkcs8oid: '1.3.132.0.34', - p: new Buffer(('00' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff fffffffe' + - 'ffffffff 00000000 00000000 ffffffff'). - replace(/ /g, ''), 'hex'), - a: new Buffer(('00' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' + - 'FFFFFFFF 00000000 00000000 FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: new Buffer(( - 'b3312fa7 e23ee7e4 988e056b e3f82d19' + - '181d9c6e fe814112 0314088f 5013875a' + - 'c656398d 8a2ed19d 2a85c8ed d3ec2aef'). - replace(/ /g, ''), 'hex'), - s: new Buffer(('00' + - 'a335926a a319a27a 1d00896a 6773a482' + - '7acdac73'). - replace(/ /g, ''), 'hex'), - n: new Buffer(('00' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff c7634d81 f4372ddf' + - '581a0db2 48b0a77a ecec196a ccc52973'). - replace(/ /g, ''), 'hex'), - G: new Buffer(('04' + - 'aa87ca22 be8b0537 8eb1c71e f320ad74' + - '6e1d3b62 8ba79b98 59f741e0 82542a38' + - '5502f25d bf55296c 3a545e38 72760ab7' + - '3617de4a 96262c6f 5d9e98bf 9292dc29' + - 'f8f41dbd 289a147c e9da3113 b5f0b8c0' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'). - replace(/ /g, ''), 'hex') - }, - 'nistp521': { - size: 521, - pkcs8oid: '1.3.132.0.35', - p: new Buffer(( - '01ffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffff').replace(/ /g, ''), 'hex'), - a: new Buffer(('01FF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + - 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC'). - replace(/ /g, ''), 'hex'), - b: new Buffer(('51' + - '953eb961 8e1c9a1f 929a21a0 b68540ee' + - 'a2da725b 99b315f3 b8b48991 8ef109e1' + - '56193951 ec7e937b 1652c0bd 3bb1bf07' + - '3573df88 3d2c34f1 ef451fd4 6b503f00'). - replace(/ /g, ''), 'hex'), - s: new Buffer(('00' + - 'd09e8800 291cb853 96cc6717 393284aa' + - 'a0da64ba').replace(/ /g, ''), 'hex'), - n: new Buffer(('01ff' + - 'ffffffff ffffffff ffffffff ffffffff' + - 'ffffffff ffffffff ffffffff fffffffa' + - '51868783 bf2f966b 7fcc0148 f709a5d0' + - '3bb5c9b8 899c47ae bb6fb71e 91386409'). - replace(/ /g, ''), 'hex'), - G: new Buffer(('04' + - '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' + - '9c648139 053fb521 f828af60 6b4d3dba' + - 'a14b5e77 efe75928 fe1dc127 a2ffa8de' + - '3348b3c1 856a429b f97e7e31 c2e5bd66' + - '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' + - '98f54449 579b4468 17afbd17 273e662c' + - '97ee7299 5ef42640 c550b901 3fad0761' + - '353c7086 a272c240 88be9476 9fd16650'). - replace(/ /g, ''), 'hex') - } -}; -module.exports = { - info: algInfo, - privInfo: algPrivInfo, - hashAlgs: hashAlgs, - curves: curves -}; +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++; +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); +var comparatorTrimReplace = '$1$2$3'; -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { -// Copyright 2017 Joyent, Inc. +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++; +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$'; -module.exports = Key; +var HYPHENRANGELOOSE = R++; +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$'; -var assert = __webpack_require__(9); -var algs = __webpack_require__(16); -var crypto = __webpack_require__(7); -var Fingerprint = __webpack_require__(73); -var Signature = __webpack_require__(33); -var DiffieHellman = __webpack_require__(263).DiffieHellman; -var errs = __webpack_require__(32); -var utils = __webpack_require__(13); -var PrivateKey = __webpack_require__(18); -var edCompat; +// Star ranges basically just allow anything at all. +var STAR = R++; +src[STAR] = '(<|>)?=?\\s*\\*'; -try { - edCompat = __webpack_require__(264); -} catch (e) { - /* Just continue through, and bail out if we try to use it. */ +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]); + if (!re[i]) + re[i] = new RegExp(src[i]); } -var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var KeyParseError = errs.KeyParseError; +exports.parse = parse; +function parse(version, loose) { + if (version instanceof SemVer) + return version; -var formats = {}; -formats['auto'] = __webpack_require__(265); -formats['pem'] = __webpack_require__(41); -formats['pkcs1'] = __webpack_require__(164); -formats['pkcs8'] = __webpack_require__(74); -formats['rfc4253'] = __webpack_require__(48); -formats['ssh'] = __webpack_require__(266); -formats['ssh-private'] = __webpack_require__(107); -formats['openssh'] = formats['ssh-private']; + if (typeof version !== 'string') + return null; -function Key(opts) { - assert.object(opts, 'options'); - assert.arrayOfObject(opts.parts, 'options.parts'); - assert.string(opts.type, 'options.type'); - assert.optionalString(opts.comment, 'options.comment'); + if (version.length > MAX_LENGTH) + return null; - var algInfo = algs.info[opts.type]; - if (typeof (algInfo) !== 'object') - throw (new InvalidAlgorithmError(opts.type)); + var r = loose ? re[LOOSE] : re[FULL]; + if (!r.test(version)) + return null; - var partLookup = {}; - for (var i = 0; i < opts.parts.length; ++i) { - var part = opts.parts[i]; - partLookup[part.name] = part; - } + try { + return new SemVer(version, loose); + } catch (er) { + return null; + } +} - this.type = opts.type; - this.parts = opts.parts; - this.part = partLookup; - this.comment = undefined; - this.source = opts.source; +exports.valid = valid; +function valid(version, loose) { + var v = parse(version, loose); + return v ? v.version : null; +} - /* for speeding up hashing/fingerprint operations */ - this._rfc4253Cache = opts._rfc4253Cache; - this._hashCache = {}; - var sz; - this.curve = undefined; - if (this.type === 'ecdsa') { - var curve = this.part.curve.data.toString(); - this.curve = curve; - sz = algs.curves[curve].size; - } else if (this.type === 'ed25519') { - sz = 256; - this.curve = 'curve25519'; - } else { - var szPart = this.part[algInfo.sizePart]; - sz = szPart.data.length; - sz = sz * 8 - utils.countZeros(szPart.data); - } - this.size = sz; +exports.clean = clean; +function clean(version, loose) { + var s = parse(version.trim().replace(/^[=v]+/, ''), loose); + return s ? s.version : null; } -Key.formats = formats; - -Key.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'ssh'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); +exports.SemVer = SemVer; - if (format === 'rfc4253') { - if (this._rfc4253Cache === undefined) - this._rfc4253Cache = formats['rfc4253'].write(this); - return (this._rfc4253Cache); - } +function SemVer(version, loose) { + if (version instanceof SemVer) { + if (version.loose === loose) + return version; + else + version = version.version; + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } - return (formats[format].write(this, options)); -}; + if (version.length > MAX_LENGTH) + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') -Key.prototype.toString = function (format, options) { - return (this.toBuffer(format, options).toString()); -}; + if (!(this instanceof SemVer)) + return new SemVer(version, loose); -Key.prototype.hash = function (algo) { - assert.string(algo, 'algorithm'); - algo = algo.toLowerCase(); - if (algs.hashAlgs[algo] === undefined) - throw (new InvalidAlgorithmError(algo)); + debug('SemVer', version, loose); + this.loose = loose; + var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); - if (this._hashCache[algo]) - return (this._hashCache[algo]); + if (!m) + throw new TypeError('Invalid Version: ' + version); - var hash = crypto.createHash(algo). - update(this.toBuffer('rfc4253')).digest(); - this._hashCache[algo] = hash; - return (hash); -}; + this.raw = version; -Key.prototype.fingerprint = function (algo) { - if (algo === undefined) - algo = 'sha256'; - assert.string(algo, 'algorithm'); - var opts = { - type: 'key', - hash: this.hash(algo), - algorithm: algo - }; - return (new Fingerprint(opts)); -}; + // these are actually numbers + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; -Key.prototype.defaultHashAlgorithm = function () { - var hashAlgo = 'sha1'; - if (this.type === 'rsa') - hashAlgo = 'sha256'; - if (this.type === 'dsa' && this.size > 1024) - hashAlgo = 'sha256'; - if (this.type === 'ed25519') - hashAlgo = 'sha512'; - if (this.type === 'ecdsa') { - if (this.size <= 256) - hashAlgo = 'sha256'; - else if (this.size <= 384) - hashAlgo = 'sha384'; - else - hashAlgo = 'sha512'; - } - return (hashAlgo); -}; + if (this.major > MAX_SAFE_INTEGER || this.major < 0) + throw new TypeError('Invalid major version') -Key.prototype.createVerify = function (hashAlgo) { - if (hashAlgo === undefined) - hashAlgo = this.defaultHashAlgorithm(); - assert.string(hashAlgo, 'hash algorithm'); + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) + throw new TypeError('Invalid minor version') - /* ED25519 is not supported by OpenSSL, use a javascript impl. */ - if (this.type === 'ed25519' && edCompat !== undefined) - return (new edCompat.Verifier(this, hashAlgo)); - if (this.type === 'curve25519') - throw (new Error('Curve25519 keys are not suitable for ' + - 'signing or verification')); + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) + throw new TypeError('Invalid patch version') - var v, nm, err; - try { - nm = hashAlgo.toUpperCase(); - v = crypto.createVerify(nm); - } catch (e) { - err = e; - } - if (v === undefined || (err instanceof Error && - err.message.match(/Unknown message digest/))) { - nm = 'RSA-'; - nm += hashAlgo.toUpperCase(); - v = crypto.createVerify(nm); - } - assert.ok(v, 'failed to create verifier'); - var oldVerify = v.verify.bind(v); - var key = this.toBuffer('pkcs8'); - var curve = this.curve; - var self = this; - v.verify = function (signature, fmt) { - if (Signature.isSignature(signature, [2, 0])) { - if (signature.type !== self.type) - return (false); - if (signature.hashAlgorithm && - signature.hashAlgorithm !== hashAlgo) - return (false); - if (signature.curve && self.type === 'ecdsa' && - signature.curve !== curve) - return (false); - return (oldVerify(key, signature.toBuffer('asn1'))); + // numberify any prerelease numeric ids + if (!m[4]) + this.prerelease = []; + else + this.prerelease = m[4].split('.').map(function(id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + if (num >= 0 && num < MAX_SAFE_INTEGER) + return num; + } + return id; + }); - } else if (typeof (signature) === 'string' || - Buffer.isBuffer(signature)) { - return (oldVerify(key, signature, fmt)); + this.build = m[5] ? m[5].split('.') : []; + this.format(); +} - /* - * Avoid doing this on valid arguments, walking the prototype - * chain can be quite slow. - */ - } else if (Signature.isSignature(signature, [1, 0])) { - throw (new Error('signature was created by too old ' + - 'a version of sshpk and cannot be verified')); +SemVer.prototype.format = function() { + this.version = this.major + '.' + this.minor + '.' + this.patch; + if (this.prerelease.length) + this.version += '-' + this.prerelease.join('.'); + return this.version; +}; - } else { - throw (new TypeError('signature must be a string, ' + - 'Buffer, or Signature object')); - } - }; - return (v); +SemVer.prototype.toString = function() { + return this.version; }; -Key.prototype.createDiffieHellman = function () { - if (this.type === 'rsa') - throw (new Error('RSA keys do not support Diffie-Hellman')); +SemVer.prototype.compare = function(other) { + debug('SemVer.compare', this.version, this.loose, other); + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); - return (new DiffieHellman(this)); + return this.compareMain(other) || this.comparePre(other); }; -Key.prototype.createDH = Key.prototype.createDiffieHellman; - -Key.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; - assert.object(formats[format], 'formats[format]'); +SemVer.prototype.compareMain = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); - try { - var k = formats[format].read(data, options); - if (k instanceof PrivateKey) - k = k.toPublic(); - if (!k.comment) - k.comment = options.filename; - return (k); - } catch (e) { - if (e.name === 'KeyEncryptedError') - throw (e); - throw (new KeyParseError(options.filename, format, e)); - } + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch); }; -Key.isKey = function (obj, ver) { - return (utils.isCompatible(obj, Key, ver)); -}; +SemVer.prototype.comparePre = function(other) { + if (!(other instanceof SemVer)) + other = new SemVer(other, this.loose); -/* - * API versions for Key: - * [1,0] -- initial ver, may take Signature for createVerify or may not - * [1,1] -- added pkcs1, pkcs8 formats - * [1,2] -- added auto, ssh-private, openssh formats - * [1,3] -- added defaultHashAlgorithm - * [1,4] -- added ed support, createDH - * [1,5] -- first explicitly tagged version - */ -Key.prototype._sshpkApiVersion = [1, 5]; + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) + return -1; + else if (!this.prerelease.length && other.prerelease.length) + return 1; + else if (!this.prerelease.length && !other.prerelease.length) + return 0; -Key._oldVersionDetect = function (obj) { - assert.func(obj.toBuffer); - assert.func(obj.fingerprint); - if (obj.createDH) - return ([1, 4]); - if (obj.defaultHashAlgorithm) - return ([1, 3]); - if (obj.formats['auto']) - return ([1, 2]); - if (obj.formats['pkcs1']) - return ([1, 1]); - return ([1, 0]); + var i = 0; + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + if (a === undefined && b === undefined) + return 0; + else if (b === undefined) + return 1; + else if (a === undefined) + return -1; + else if (a === b) + continue; + else + return compareIdentifiers(a, b); + } while (++i); }; +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) + this.inc('patch', identifier); + this.inc('pre', identifier); + break; -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) + this.major++; + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) + this.minor++; + this.patch = 0; + this.prerelease = []; + break; + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) + this.patch++; + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) + this.prerelease = [0]; + else { + var i = this.prerelease.length; + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + if (i === -1) // didn't increment anything + this.prerelease.push(0); + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) + this.prerelease = [identifier, 0]; + } else + this.prerelease = [identifier, 0]; + } + break; -// Copyright 2017 Joyent, Inc. + default: + throw new Error('invalid increment argument: ' + release); + } + this.format(); + this.raw = this.version; + return this; +}; -module.exports = PrivateKey; +exports.inc = inc; +function inc(version, release, loose, identifier) { + if (typeof(loose) === 'string') { + identifier = loose; + loose = undefined; + } -var assert = __webpack_require__(9); -var algs = __webpack_require__(16); -var crypto = __webpack_require__(7); -var Fingerprint = __webpack_require__(73); -var Signature = __webpack_require__(33); -var errs = __webpack_require__(32); -var util = __webpack_require__(2); -var utils = __webpack_require__(13); -var dhe = __webpack_require__(263); -var generateECDSA = dhe.generateECDSA; -var generateED25519 = dhe.generateED25519; -var edCompat; -var ed; + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } +} -try { - edCompat = __webpack_require__(264); -} catch (e) { - /* Just continue through, and bail out if we try to use it. */ +exports.diff = diff; +function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + if (v1.prerelease.length || v2.prerelease.length) { + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return 'pre'+key; + } + } + } + return 'prerelease'; + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return key; + } + } + } + } } -var Key = __webpack_require__(17); +exports.compareIdentifiers = compareIdentifiers; -var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var KeyParseError = errs.KeyParseError; -var KeyEncryptedError = errs.KeyEncryptedError; +var numeric = /^[0-9]+$/; +function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); -var formats = {}; -formats['auto'] = __webpack_require__(265); -formats['pem'] = __webpack_require__(41); -formats['pkcs1'] = __webpack_require__(164); -formats['pkcs8'] = __webpack_require__(74); -formats['rfc4253'] = __webpack_require__(48); -formats['ssh-private'] = __webpack_require__(107); -formats['openssh'] = formats['ssh-private']; -formats['ssh'] = formats['ssh-private']; + if (anum && bnum) { + a = +a; + b = +b; + } -function PrivateKey(opts) { - assert.object(opts, 'options'); - Key.call(this, opts); + return (anum && !bnum) ? -1 : + (bnum && !anum) ? 1 : + a < b ? -1 : + a > b ? 1 : + 0; +} - this._pubCache = undefined; +exports.rcompareIdentifiers = rcompareIdentifiers; +function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); } -util.inherits(PrivateKey, Key); -PrivateKey.formats = formats; +exports.major = major; +function major(a, loose) { + return new SemVer(a, loose).major; +} -PrivateKey.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'pkcs1'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); +exports.minor = minor; +function minor(a, loose) { + return new SemVer(a, loose).minor; +} - return (formats[format].write(this, options)); -}; +exports.patch = patch; +function patch(a, loose) { + return new SemVer(a, loose).patch; +} -PrivateKey.prototype.hash = function (algo) { - return (this.toPublic().hash(algo)); -}; +exports.compare = compare; +function compare(a, b, loose) { + return new SemVer(a, loose).compare(b); +} -PrivateKey.prototype.toPublic = function () { - if (this._pubCache) - return (this._pubCache); +exports.compareLoose = compareLoose; +function compareLoose(a, b) { + return compare(a, b, true); +} - var algInfo = algs.info[this.type]; - var pubParts = []; - for (var i = 0; i < algInfo.parts.length; ++i) { - var p = algInfo.parts[i]; - pubParts.push(this.part[p]); - } +exports.rcompare = rcompare; +function rcompare(a, b, loose) { + return compare(b, a, loose); +} - this._pubCache = new Key({ - type: this.type, - source: this, - parts: pubParts - }); - if (this.comment) - this._pubCache.comment = this.comment; - return (this._pubCache); -}; +exports.sort = sort; +function sort(list, loose) { + return list.sort(function(a, b) { + return exports.compare(a, b, loose); + }); +} -PrivateKey.prototype.derive = function (newType, newSize) { - assert.string(newType, 'type'); - assert.optionalNumber(newSize, 'size'); - var priv, pub; +exports.rsort = rsort; +function rsort(list, loose) { + return list.sort(function(a, b) { + return exports.rcompare(a, b, loose); + }); +} - if (this.type === 'ed25519' && newType === 'curve25519') { - if (ed === undefined) - ed = __webpack_require__(154); +exports.gt = gt; +function gt(a, b, loose) { + return compare(a, b, loose) > 0; +} - priv = this.part.r.data; - if (priv[0] === 0x00) - priv = priv.slice(1); - priv = priv.slice(0, 32); +exports.lt = lt; +function lt(a, b, loose) { + return compare(a, b, loose) < 0; +} - pub = ed.dh.publicKey(priv); - priv = utils.mpNormalize(Buffer.concat([priv, pub])); +exports.eq = eq; +function eq(a, b, loose) { + return compare(a, b, loose) === 0; +} - return (new PrivateKey({ - type: 'curve25519', - parts: [ - { name: 'R', data: utils.mpNormalize(pub) }, - { name: 'r', data: priv } - ] - })); - } else if (this.type === 'curve25519' && newType === 'ed25519') { - if (ed === undefined) - ed = __webpack_require__(154); +exports.neq = neq; +function neq(a, b, loose) { + return compare(a, b, loose) !== 0; +} - priv = this.part.r.data; - if (priv[0] === 0x00) - priv = priv.slice(1); - priv = priv.slice(0, 32); +exports.gte = gte; +function gte(a, b, loose) { + return compare(a, b, loose) >= 0; +} - pub = ed.eddsa.publicKey(priv.toString('binary')); - pub = new Buffer(pub, 'binary'); +exports.lte = lte; +function lte(a, b, loose) { + return compare(a, b, loose) <= 0; +} - priv = utils.mpNormalize(Buffer.concat([priv, pub])); +exports.cmp = cmp; +function cmp(a, op, b, loose) { + var ret; + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a === b; + break; + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + ret = a !== b; + break; + case '': case '=': case '==': ret = eq(a, b, loose); break; + case '!=': ret = neq(a, b, loose); break; + case '>': ret = gt(a, b, loose); break; + case '>=': ret = gte(a, b, loose); break; + case '<': ret = lt(a, b, loose); break; + case '<=': ret = lte(a, b, loose); break; + default: throw new TypeError('Invalid operator: ' + op); + } + return ret; +} - return (new PrivateKey({ - type: 'ed25519', - parts: [ - { name: 'R', data: utils.mpNormalize(pub) }, - { name: 'r', data: priv } - ] - })); - } - throw (new Error('Key derivation not supported from ' + this.type + - ' to ' + newType)); -}; +exports.Comparator = Comparator; +function Comparator(comp, loose) { + if (comp instanceof Comparator) { + if (comp.loose === loose) + return comp; + else + comp = comp.value; + } -PrivateKey.prototype.createVerify = function (hashAlgo) { - return (this.toPublic().createVerify(hashAlgo)); -}; + if (!(this instanceof Comparator)) + return new Comparator(comp, loose); -PrivateKey.prototype.createSign = function (hashAlgo) { - if (hashAlgo === undefined) - hashAlgo = this.defaultHashAlgorithm(); - assert.string(hashAlgo, 'hash algorithm'); + debug('comparator', comp, loose); + this.loose = loose; + this.parse(comp); - /* ED25519 is not supported by OpenSSL, use a javascript impl. */ - if (this.type === 'ed25519' && edCompat !== undefined) - return (new edCompat.Signer(this, hashAlgo)); - if (this.type === 'curve25519') - throw (new Error('Curve25519 keys are not suitable for ' + - 'signing or verification')); + if (this.semver === ANY) + this.value = ''; + else + this.value = this.operator + this.semver.version; - var v, nm, err; - try { - nm = hashAlgo.toUpperCase(); - v = crypto.createSign(nm); - } catch (e) { - err = e; - } - if (v === undefined || (err instanceof Error && - err.message.match(/Unknown message digest/))) { - nm = 'RSA-'; - nm += hashAlgo.toUpperCase(); - v = crypto.createSign(nm); - } - assert.ok(v, 'failed to create verifier'); - var oldSign = v.sign.bind(v); - var key = this.toBuffer('pkcs1'); - var type = this.type; - var curve = this.curve; - v.sign = function () { - var sig = oldSign(key); - if (typeof (sig) === 'string') - sig = new Buffer(sig, 'binary'); - sig = Signature.parse(sig, type, 'asn1'); - sig.hashAlgorithm = hashAlgo; - sig.curve = curve; - return (sig); - }; - return (v); -}; + debug('comp', this); +} -PrivateKey.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; +var ANY = {}; +Comparator.prototype.parse = function(comp) { + var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); - assert.object(formats[format], 'formats[format]'); + if (!m) + throw new TypeError('Invalid comparator: ' + comp); - try { - var k = formats[format].read(data, options); - assert.ok(k instanceof PrivateKey, 'key is not a private key'); - if (!k.comment) - k.comment = options.filename; - return (k); - } catch (e) { - if (e.name === 'KeyEncryptedError') - throw (e); - throw (new KeyParseError(options.filename, format, e)); - } + this.operator = m[1]; + if (this.operator === '=') + this.operator = ''; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) + this.semver = ANY; + else + this.semver = new SemVer(m[2], this.loose); }; -PrivateKey.isPrivateKey = function (obj, ver) { - return (utils.isCompatible(obj, PrivateKey, ver)); +Comparator.prototype.toString = function() { + return this.value; }; -PrivateKey.generate = function (type, options) { - if (options === undefined) - options = {}; - assert.object(options, 'options'); +Comparator.prototype.test = function(version) { + debug('Comparator.test', version, this.loose); - switch (type) { - case 'ecdsa': - if (options.curve === undefined) - options.curve = 'nistp256'; - assert.string(options.curve, 'options.curve'); - return (generateECDSA(options.curve)); - case 'ed25519': - return (generateED25519()); - default: - throw (new Error('Key generation not supported with key ' + - 'type "' + type + '"')); - } -}; + if (this.semver === ANY) + return true; -/* - * API versions for PrivateKey: - * [1,0] -- initial ver - * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats - * [1,2] -- added defaultHashAlgorithm - * [1,3] -- added derive, ed, createDH - * [1,4] -- first tagged version - */ -PrivateKey.prototype._sshpkApiVersion = [1, 4]; + if (typeof version === 'string') + version = new SemVer(version, this.loose); -PrivateKey._oldVersionDetect = function (obj) { - assert.func(obj.toPublic); - assert.func(obj.createSign); - if (obj.derive) - return ([1, 3]); - if (obj.defaultHashAlgorithm) - return ([1, 2]); - if (obj.formats['auto']) - return ([1, 1]); - return ([1, 0]); + return cmp(version, this.operator, this.semver, this.loose); }; -/***/ }), -/* 19 */ -/***/ (function(module, exports) { - -module.exports = function(module) { - if(!module.webpackPolyfill) { - module.deprecate = function() {}; - module.paths = []; - // module.parent = undefined by default - if(!module.children) module.children = []; - Object.defineProperty(module, "loaded", { - enumerable: true, - get: function() { - return module.l; - } - }); - Object.defineProperty(module, "id", { - enumerable: true, - get: function() { - return module.i; - } - }); - module.webpackPolyfill = 1; - } - return module; -}; +exports.Range = Range; +function Range(range, loose) { + if ((range instanceof Range) && range.loose === loose) + return range; + if (!(this instanceof Range)) + return new Range(range, loose); -/***/ }), -/* 20 */ -/***/ (function(module, exports) { + this.loose = loose; -module.exports = require("stream"); + // First, split based on boolean or || + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function(range) { + return this.parseRange(range.trim()); + }, this).filter(function(c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); -/***/ }), -/* 21 */ -/***/ (function(module, exports, __webpack_require__) { + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } -/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** - * @license - * Lodash <https://lodash.com/> - * Copyright JS Foundation and other contributors <https://js.foundation/> - * Released under MIT license <https://lodash.com/license> - * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { + this.format(); +} - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; +Range.prototype.format = function() { + this.range = this.set.map(function(comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; +}; - /** Used as the semantic version number. */ - var VERSION = '4.17.4'; +Range.prototype.toString = function() { + return this.range; +}; - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; +Range.prototype.parseRange = function(range) { + var loose = this.loose; + range = range.trim(); + debug('range', range, loose); + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function'; + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace); - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace); - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; + // normalize spaces + range = range.split(/\s+/).join(' '); - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; + // At this point, the range is completely trimmed and + // ready to be split into comparators. - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function(comp) { + return parseComparator(comp, loose); + }).join(' ').split(/\s+/); + if (this.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function(comp) { + return !!comp.match(compRe); + }); + } + set = set.map(function(comp) { + return new Comparator(comp, loose); + }); - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; + return set; +}; - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators; +function toComparators(range, loose) { + return new Range(range, loose).set.map(function(comp) { + return comp.map(function(c) { + return c.value; + }).join(' ').trim().split(' '); + }); +} - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator(comp, loose) { + debug('comp', comp); + comp = replaceCarets(comp, loose); + debug('caret', comp); + comp = replaceTildes(comp, loose); + debug('tildes', comp); + comp = replaceXRanges(comp, loose); + debug('xrange', comp); + comp = replaceStars(comp, loose); + debug('stars', comp); + return comp; +} - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; +function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; +} - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceTilde(comp, loose); + }).join(' '); +} - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; +function replaceTilde(comp, loose) { + var r = loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else if (pr) { + debug('replaceTilde pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; + debug('tilde return', ret); + return ret; + }); +} - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets(comp, loose) { + return comp.trim().split(/\s+/).map(function(comp) { + return replaceCaret(comp, loose); + }).join(' '); +} - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; +function replaceCaret(comp, loose) { + debug('caret', comp, loose); + var r = loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function(_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + if (isX(M)) + ret = ''; + else if (isX(m)) + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + else if (isX(p)) { + if (M === '0') + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + else + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } else if (pr) { + debug('replaceCaret pr', pr); + if (pr.charAt(0) !== '-') + pr = '-' + pr; + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + pr + + ' <' + (+M + 1) + '.0.0'; + } else { + debug('no pr'); + if (M === '0') { + if (m === '0') + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1); + else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0'; + } else + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0'; + } - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + debug('caret return', ret); + return ret; + }); +} - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; +function replaceXRanges(comp, loose) { + debug('replaceXRanges', comp, loose); + return comp.split(/\s+/).map(function(comp) { + return replaceXRange(comp, loose); + }).join(' '); +} - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - reLeadingDot = /^\./, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; +function replaceXRange(comp, loose) { + comp = comp.trim(); + var r = loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function(ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); + if (gtlt === '=' && anyX) + gtlt = ''; - /** Used to match leading and trailing whitespace. */ - var reTrim = /^\s+|\s+$/g, - reTrimStart = /^\s+/, - reTrimEnd = /\s+$/; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // replace X with 0 + if (xm) + m = 0; + if (xp) + p = 0; - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else if (xp) { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + if (xm) + M = +M + 1; + else + m = +m + 1; + } - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; + debug('xRange return', ret); - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + return ret; + }); +} - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars(comp, loose) { + debug('replaceStars', comp, loose); + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], ''); +} - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; + if (isX(fM)) + from = ''; + else if (isX(fm)) + from = '>=' + fM + '.0.0'; + else if (isX(fp)) + from = '>=' + fM + '.' + fm + '.0'; + else + from = '>=' + from; - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; + if (isX(tM)) + to = ''; + else if (isX(tm)) + to = '<' + (+tM + 1) + '.0.0'; + else if (isX(tp)) + to = '<' + tM + '.' + (+tm + 1) + '.0'; + else if (tpr) + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + else + to = '<=' + to; - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; + return (from + ' ' + to).trim(); +} - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function(version) { + if (!version) + return false; - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; + if (typeof version === 'string') + version = new SemVer(version, this.loose); - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version)) + return true; + } + return false; +}; - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; +function testSet(set, version) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) + return false; + } - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; + if (version.prerelease.length) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (var i = 0; i < set.length; i++) { + debug(set[i].semver); + if (set[i].semver === ANY) + continue; - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', - rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) + return true; + } + } - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); + // Version has a -pre, but it's not one of the ones we like. + return false; + } - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); + return true; +} - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); +exports.satisfies = satisfies; +function satisfies(version, range, loose) { + try { + range = new Range(range, loose); + } catch (er) { + return false; + } + return range.test(version); +} - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); +exports.maxSatisfying = maxSatisfying; +function maxSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return rcompare(a, b, loose); + })[0] || null; +} - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); +exports.minSatisfying = minSatisfying; +function minSatisfying(versions, range, loose) { + return versions.filter(function(version) { + return satisfies(version, range, loose); + }).sort(function(a, b) { + return compare(a, b, loose); + })[0] || null; +} - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; +exports.validRange = validRange; +function validRange(range, loose) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, loose).range || '*'; + } catch (er) { + return null; + } +} - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr; +function ltr(version, range, loose) { + return outside(version, range, '<', loose); +} - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr; +function gtr(version, range, loose) { + return outside(version, range, '>', loose); +} - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; +exports.outside = outside; +function outside(version, range, hilo, loose) { + version = new SemVer(version, loose); + range = new Range(range, loose); - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; + var gtfn, ltefn, ltfn, comp, ecomp; + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; + // If it satisifes the range it is not outside + if (satisfies(version, range, loose)) { + return false; + } - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; + var high = null; + var low = null; - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; + comparators.forEach(function(comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator; + low = low || comparator; + if (gtfn(comparator.semver, high.semver, loose)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, loose)) { + low = comparator; + } + }); - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false; + } - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + return true; +} - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); +exports.prerelease = prerelease; +function prerelease(version, loose) { + var parsed = parse(version, loose); + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +} - /** Detect free variable `exports`. */ - var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - /** Detect free variable `module`. */ - var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; +/***/ }), +/* 23 */ +/***/ (function(module, exports) { - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; +// Copyright 2015 Joyent, Inc. - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; +var algInfo = { + 'dsa': { + parts: ['p', 'q', 'g', 'y'], + sizePart: 'p' + }, + 'rsa': { + parts: ['e', 'n'], + sizePart: 'n' + }, + 'ecdsa': { + parts: ['curve', 'Q'], + sizePart: 'Q' + }, + 'ed25519': { + parts: ['R'], + normalize: false, + sizePart: 'R' + } +}; +algInfo['curve25519'] = algInfo['ed25519']; - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); +var algPrivInfo = { + 'dsa': { + parts: ['p', 'q', 'g', 'y', 'x'] + }, + 'rsa': { + parts: ['n', 'e', 'd', 'iqmp', 'p', 'q'] + }, + 'ecdsa': { + parts: ['curve', 'Q', 'd'] + }, + 'ed25519': { + parts: ['R', 'r'], + normalize: false + } +}; +algPrivInfo['curve25519'] = algPrivInfo['ed25519']; - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; +var hashAlgs = { + 'md5': true, + 'sha1': true, + 'sha256': true, + 'sha384': true, + 'sha512': true +}; - /*--------------------------------------------------------------------------*/ +/* + * Taken from + * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf + */ +var curves = { + 'nistp256': { + size: 256, + pkcs8oid: '1.2.840.10045.3.1.7', + p: new Buffer(('00' + + 'ffffffff 00000001 00000000 00000000' + + '00000000 ffffffff ffffffff ffffffff'). + replace(/ /g, ''), 'hex'), + a: new Buffer(('00' + + 'FFFFFFFF 00000001 00000000 00000000' + + '00000000 FFFFFFFF FFFFFFFF FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: new Buffer(( + '5ac635d8 aa3a93e7 b3ebbd55 769886bc' + + '651d06b0 cc53b0f6 3bce3c3e 27d2604b'). + replace(/ /g, ''), 'hex'), + s: new Buffer(('00' + + 'c49d3608 86e70493 6a6678e1 139d26b7' + + '819f7e90'). + replace(/ /g, ''), 'hex'), + n: new Buffer(('00' + + 'ffffffff 00000000 ffffffff ffffffff' + + 'bce6faad a7179e84 f3b9cac2 fc632551'). + replace(/ /g, ''), 'hex'), + G: new Buffer(('04' + + '6b17d1f2 e12c4247 f8bce6e5 63a440f2' + + '77037d81 2deb33a0 f4a13945 d898c296' + + '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' + + '2bce3357 6b315ece cbb64068 37bf51f5'). + replace(/ /g, ''), 'hex') + }, + 'nistp384': { + size: 384, + pkcs8oid: '1.3.132.0.34', + p: new Buffer(('00' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff fffffffe' + + 'ffffffff 00000000 00000000 ffffffff'). + replace(/ /g, ''), 'hex'), + a: new Buffer(('00' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' + + 'FFFFFFFF 00000000 00000000 FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: new Buffer(( + 'b3312fa7 e23ee7e4 988e056b e3f82d19' + + '181d9c6e fe814112 0314088f 5013875a' + + 'c656398d 8a2ed19d 2a85c8ed d3ec2aef'). + replace(/ /g, ''), 'hex'), + s: new Buffer(('00' + + 'a335926a a319a27a 1d00896a 6773a482' + + '7acdac73'). + replace(/ /g, ''), 'hex'), + n: new Buffer(('00' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff c7634d81 f4372ddf' + + '581a0db2 48b0a77a ecec196a ccc52973'). + replace(/ /g, ''), 'hex'), + G: new Buffer(('04' + + 'aa87ca22 be8b0537 8eb1c71e f320ad74' + + '6e1d3b62 8ba79b98 59f741e0 82542a38' + + '5502f25d bf55296c 3a545e38 72760ab7' + + '3617de4a 96262c6f 5d9e98bf 9292dc29' + + 'f8f41dbd 289a147c e9da3113 b5f0b8c0' + + '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'). + replace(/ /g, ''), 'hex') + }, + 'nistp521': { + size: 521, + pkcs8oid: '1.3.132.0.35', + p: new Buffer(( + '01ffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffff').replace(/ /g, ''), 'hex'), + a: new Buffer(('01FF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' + + 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC'). + replace(/ /g, ''), 'hex'), + b: new Buffer(('51' + + '953eb961 8e1c9a1f 929a21a0 b68540ee' + + 'a2da725b 99b315f3 b8b48991 8ef109e1' + + '56193951 ec7e937b 1652c0bd 3bb1bf07' + + '3573df88 3d2c34f1 ef451fd4 6b503f00'). + replace(/ /g, ''), 'hex'), + s: new Buffer(('00' + + 'd09e8800 291cb853 96cc6717 393284aa' + + 'a0da64ba').replace(/ /g, ''), 'hex'), + n: new Buffer(('01ff' + + 'ffffffff ffffffff ffffffff ffffffff' + + 'ffffffff ffffffff ffffffff fffffffa' + + '51868783 bf2f966b 7fcc0148 f709a5d0' + + '3bb5c9b8 899c47ae bb6fb71e 91386409'). + replace(/ /g, ''), 'hex'), + G: new Buffer(('04' + + '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' + + '9c648139 053fb521 f828af60 6b4d3dba' + + 'a14b5e77 efe75928 fe1dc127 a2ffa8de' + + '3348b3c1 856a429b f97e7e31 c2e5bd66' + + '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' + + '98f54449 579b4468 17afbd17 273e662c' + + '97ee7299 5ef42640 c550b901 3fad0761' + + '353c7086 a272c240 88be9476 9fd16650'). + replace(/ /g, ''), 'hex') + } +}; - /** - * Adds the key-value `pair` to `map`. - * - * @private - * @param {Object} map The map to modify. - * @param {Array} pair The key-value pair to add. - * @returns {Object} Returns `map`. - */ - function addMapEntry(map, pair) { - // Don't return `map.set` because it's not chainable in IE 11. - map.set(pair[0], pair[1]); - return map; - } +module.exports = { + info: algInfo, + privInfo: algPrivInfo, + hashAlgs: hashAlgs, + curves: curves +}; - /** - * Adds `value` to `set`. - * - * @private - * @param {Object} set The set to modify. - * @param {*} value The value to add. - * @returns {Object} Returns `set`. - */ - function addSetEntry(set, value) { - // Don't return `set.add` because it's not chainable in IE 11. - set.add(value); - return set; - } - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } +/***/ }), +/* 24 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; +// Copyright 2017 Joyent, Inc. - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } +module.exports = Key; - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; +var assert = __webpack_require__(11); +var algs = __webpack_require__(23); +var crypto = __webpack_require__(8); +var Fingerprint = __webpack_require__(116); +var Signature = __webpack_require__(45); +var DiffieHellman = __webpack_require__(316).DiffieHellman; +var errs = __webpack_require__(44); +var utils = __webpack_require__(17); +var PrivateKey = __webpack_require__(25); +var edCompat; - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } +try { + edCompat = __webpack_require__(317); +} catch (e) { + /* Just continue through, and bail out if we try to use it. */ +} - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; +var InvalidAlgorithmError = errs.InvalidAlgorithmError; +var KeyParseError = errs.KeyParseError; - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } +var formats = {}; +formats['auto'] = __webpack_require__(318); +formats['pem'] = __webpack_require__(58); +formats['pkcs1'] = __webpack_require__(225); +formats['pkcs8'] = __webpack_require__(117); +formats['rfc4253'] = __webpack_require__(75); +formats['ssh'] = __webpack_require__(319); +formats['ssh-private'] = __webpack_require__(143); +formats['openssh'] = formats['ssh-private']; - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; +function Key(opts) { + assert.object(opts, 'options'); + assert.arrayOfObject(opts.parts, 'options.parts'); + assert.string(opts.type, 'options.type'); + assert.optionalString(opts.comment, 'options.comment'); - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } + var algInfo = algs.info[opts.type]; + if (typeof (algInfo) !== 'object') + throw (new InvalidAlgorithmError(opts.type)); - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + var partLookup = {}; + for (var i = 0; i < opts.parts.length; ++i) { + var part = opts.parts[i]; + partLookup[part.name] = part; + } - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } + this.type = opts.type; + this.parts = opts.parts; + this.part = partLookup; + this.comment = undefined; + this.source = opts.source; - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } + /* for speeding up hashing/fingerprint operations */ + this._rfc4253Cache = opts._rfc4253Cache; + this._hashCache = {}; - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; + var sz; + this.curve = undefined; + if (this.type === 'ecdsa') { + var curve = this.part.curve.data.toString(); + this.curve = curve; + sz = algs.curves[curve].size; + } else if (this.type === 'ed25519') { + sz = 256; + this.curve = 'curve25519'; + } else { + var szPart = this.part[algInfo.sizePart]; + sz = szPart.data.length; + sz = sz * 8 - utils.countZeros(szPart.data); + } + this.size = sz; +} - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } +Key.formats = formats; - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); +Key.prototype.toBuffer = function (format, options) { + if (format === undefined) + format = 'ssh'; + assert.string(format, 'format'); + assert.object(formats[format], 'formats[format]'); + assert.optionalObject(options, 'options'); - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } + if (format === 'rfc4253') { + if (this._rfc4253Cache === undefined) + this._rfc4253Cache = formats['rfc4253'].write(this); + return (this._rfc4253Cache); + } - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; + return (formats[format].write(this, options)); +}; - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } +Key.prototype.toString = function (format, options) { + return (this.toBuffer(format, options).toString()); +}; - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; +Key.prototype.hash = function (algo) { + assert.string(algo, 'algorithm'); + algo = algo.toLowerCase(); + if (algs.hashAlgs[algo] === undefined) + throw (new InvalidAlgorithmError(algo)); - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } + if (this._hashCache[algo]) + return (this._hashCache[algo]); - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } + var hash = crypto.createHash(algo). + update(this.toBuffer('rfc4253')).digest(); + this._hashCache[algo] = hash; + return (hash); +}; - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; +Key.prototype.fingerprint = function (algo) { + if (algo === undefined) + algo = 'sha256'; + assert.string(algo, 'algorithm'); + var opts = { + type: 'key', + hash: this.hash(algo), + algorithm: algo + }; + return (new Fingerprint(opts)); +}; - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } +Key.prototype.defaultHashAlgorithm = function () { + var hashAlgo = 'sha1'; + if (this.type === 'rsa') + hashAlgo = 'sha256'; + if (this.type === 'dsa' && this.size > 1024) + hashAlgo = 'sha256'; + if (this.type === 'ed25519') + hashAlgo = 'sha512'; + if (this.type === 'ecdsa') { + if (this.size <= 256) + hashAlgo = 'sha256'; + else if (this.size <= 384) + hashAlgo = 'sha384'; + else + hashAlgo = 'sha512'; + } + return (hashAlgo); +}; - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); +Key.prototype.createVerify = function (hashAlgo) { + if (hashAlgo === undefined) + hashAlgo = this.defaultHashAlgorithm(); + assert.string(hashAlgo, 'hash algorithm'); - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); - } + /* ED25519 is not supported by OpenSSL, use a javascript impl. */ + if (this.type === 'ed25519' && edCompat !== undefined) + return (new edCompat.Verifier(this, hashAlgo)); + if (this.type === 'curve25519') + throw (new Error('Curve25519 keys are not suitable for ' + + 'signing or verification')); - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } + var v, nm, err; + try { + nm = hashAlgo.toUpperCase(); + v = crypto.createVerify(nm); + } catch (e) { + err = e; + } + if (v === undefined || (err instanceof Error && + err.message.match(/Unknown message digest/))) { + nm = 'RSA-'; + nm += hashAlgo.toUpperCase(); + v = crypto.createVerify(nm); + } + assert.ok(v, 'failed to create verifier'); + var oldVerify = v.verify.bind(v); + var key = this.toBuffer('pkcs8'); + var curve = this.curve; + var self = this; + v.verify = function (signature, fmt) { + if (Signature.isSignature(signature, [2, 0])) { + if (signature.type !== self.type) + return (false); + if (signature.hashAlgorithm && + signature.hashAlgorithm !== hashAlgo) + return (false); + if (signature.curve && self.type === 'ecdsa' && + signature.curve !== curve) + return (false); + return (oldVerify(key, signature.toBuffer('asn1'))); - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; - } + } else if (typeof (signature) === 'string' || + Buffer.isBuffer(signature)) { + return (oldVerify(key, signature, fmt)); - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + /* + * Avoid doing this on valid arguments, walking the prototype + * chain can be quite slow. + */ + } else if (Signature.isSignature(signature, [1, 0])) { + throw (new Error('signature was created by too old ' + + 'a version of sshpk and cannot be verified')); - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } + } else { + throw (new TypeError('signature must be a string, ' + + 'Buffer, or Signature object')); + } + }; + return (v); +}; - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); - } +Key.prototype.createDiffieHellman = function () { + if (this.type === 'rsa') + throw (new Error('RSA keys do not support Diffie-Hellman')); - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; + return (new DiffieHellman(this)); +}; +Key.prototype.createDH = Key.prototype.createDiffieHellman; - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } +Key.parse = function (data, format, options) { + if (typeof (data) !== 'string') + assert.buffer(data, 'data'); + if (format === undefined) + format = 'auto'; + assert.string(format, 'format'); + if (typeof (options) === 'string') + options = { filename: options }; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalString(options.filename, 'options.filename'); + if (options.filename === undefined) + options.filename = '(unnamed)'; - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; - } + assert.object(formats[format], 'formats[format]'); - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; - } + try { + var k = formats[format].read(data, options); + if (k instanceof PrivateKey) + k = k.toPublic(); + if (!k.comment) + k.comment = options.filename; + return (k); + } catch (e) { + if (e.name === 'KeyEncryptedError') + throw (e); + throw (new KeyParseError(options.filename, format, e)); + } +}; - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; - } +Key.isKey = function (obj, ver) { + return (utils.isCompatible(obj, Key, ver)); +}; - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; - } +/* + * API versions for Key: + * [1,0] -- initial ver, may take Signature for createVerify or may not + * [1,1] -- added pkcs1, pkcs8 formats + * [1,2] -- added auto, ssh-private, openssh formats + * [1,3] -- added defaultHashAlgorithm + * [1,4] -- added ed support, createDH + * [1,5] -- first explicitly tagged version + */ +Key.prototype._sshpkApiVersion = [1, 5]; - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; - } +Key._oldVersionDetect = function (obj) { + assert.func(obj.toBuffer); + assert.func(obj.fingerprint); + if (obj.createDH) + return ([1, 4]); + if (obj.defaultHashAlgorithm) + return ([1, 3]); + if (obj.formats['auto']) + return ([1, 2]); + if (obj.formats['pkcs1']) + return ([1, 1]); + return ([1, 0]); +}; - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; +// Copyright 2017 Joyent, Inc. - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; - } +module.exports = PrivateKey; - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +var assert = __webpack_require__(11); +var algs = __webpack_require__(23); +var crypto = __webpack_require__(8); +var Fingerprint = __webpack_require__(116); +var Signature = __webpack_require__(45); +var errs = __webpack_require__(44); +var util = __webpack_require__(2); +var utils = __webpack_require__(17); +var dhe = __webpack_require__(316); +var generateECDSA = dhe.generateECDSA; +var generateED25519 = dhe.generateED25519; +var edCompat; +var ed; - while (++index < n) { - result[index] = iteratee(index); - } - return result; - } +try { + edCompat = __webpack_require__(317); +} catch (e) { + /* Just continue through, and bail out if we try to use it. */ +} - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } +var Key = __webpack_require__(24); - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; - } +var InvalidAlgorithmError = errs.InvalidAlgorithmError; +var KeyParseError = errs.KeyParseError; +var KeyEncryptedError = errs.KeyEncryptedError; - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); - } +var formats = {}; +formats['auto'] = __webpack_require__(318); +formats['pem'] = __webpack_require__(58); +formats['pkcs1'] = __webpack_require__(225); +formats['pkcs8'] = __webpack_require__(117); +formats['rfc4253'] = __webpack_require__(75); +formats['ssh-private'] = __webpack_require__(143); +formats['openssh'] = formats['ssh-private']; +formats['ssh'] = formats['ssh-private']; - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); - } +function PrivateKey(opts) { + assert.object(opts, 'options'); + Key.call(this, opts); - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; + this._pubCache = undefined; +} +util.inherits(PrivateKey, Key); - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } +PrivateKey.formats = formats; - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; +PrivateKey.prototype.toBuffer = function (format, options) { + if (format === undefined) + format = 'pkcs1'; + assert.string(format, 'format'); + assert.object(formats[format], 'formats[format]'); + assert.optionalObject(options, 'options'); - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; - } + return (formats[format].write(this, options)); +}; - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; +PrivateKey.prototype.hash = function (algo) { + return (this.toPublic().hash(algo)); +}; - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } +PrivateKey.prototype.toPublic = function () { + if (this._pubCache) + return (this._pubCache); - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); + var algInfo = algs.info[this.type]; + var pubParts = []; + for (var i = 0; i < algInfo.parts.length; ++i) { + var p = algInfo.parts[i]; + pubParts.push(this.part[p]); + } - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); + this._pubCache = new Key({ + type: this.type, + source: this, + parts: pubParts + }); + if (this.comment) + this._pubCache.comment = this.comment; + return (this._pubCache); +}; - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } +PrivateKey.prototype.derive = function (newType, newSize) { + assert.string(newType, 'type'); + assert.optionalNumber(newSize, 'size'); + var priv, pub; - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } + if (this.type === 'ed25519' && newType === 'curve25519') { + if (ed === undefined) + ed = __webpack_require__(215); - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } + priv = this.part.r.data; + if (priv[0] === 0x00) + priv = priv.slice(1); + priv = priv.slice(0, 32); - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } + pub = ed.dh.publicKey(priv); + priv = utils.mpNormalize(Buffer.concat([priv, pub])); - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; + return (new PrivateKey({ + type: 'curve25519', + parts: [ + { name: 'R', data: utils.mpNormalize(pub) }, + { name: 'r', data: priv } + ] + })); + } else if (this.type === 'curve25519' && newType === 'ed25519') { + if (ed === undefined) + ed = __webpack_require__(215); - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } + priv = this.part.r.data; + if (priv[0] === 0x00) + priv = priv.slice(1); + priv = priv.slice(0, 32); - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); + pub = ed.eddsa.publicKey(priv.toString('binary')); + pub = new Buffer(pub, 'binary'); - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } + priv = utils.mpNormalize(Buffer.concat([priv, pub])); - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } + return (new PrivateKey({ + type: 'ed25519', + parts: [ + { name: 'R', data: utils.mpNormalize(pub) }, + { name: 'r', data: priv } + ] + })); + } + throw (new Error('Key derivation not supported from ' + this.type + + ' to ' + newType)); +}; - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; +PrivateKey.prototype.createVerify = function (hashAlgo) { + return (this.toPublic().createVerify(hashAlgo)); +}; - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } +PrivateKey.prototype.createSign = function (hashAlgo) { + if (hashAlgo === undefined) + hashAlgo = this.defaultHashAlgorithm(); + assert.string(hashAlgo, 'hash algorithm'); - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); + /* ED25519 is not supported by OpenSSL, use a javascript impl. */ + if (this.type === 'ed25519' && edCompat !== undefined) + return (new edCompat.Signer(this, hashAlgo)); + if (this.type === 'curve25519') + throw (new Error('Curve25519 keys are not suitable for ' + + 'signing or verification')); - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } + var v, nm, err; + try { + nm = hashAlgo.toUpperCase(); + v = crypto.createSign(nm); + } catch (e) { + err = e; + } + if (v === undefined || (err instanceof Error && + err.message.match(/Unknown message digest/))) { + nm = 'RSA-'; + nm += hashAlgo.toUpperCase(); + v = crypto.createSign(nm); + } + assert.ok(v, 'failed to create verifier'); + var oldSign = v.sign.bind(v); + var key = this.toBuffer('pkcs1'); + var type = this.type; + var curve = this.curve; + v.sign = function () { + var sig = oldSign(key); + if (typeof (sig) === 'string') + sig = new Buffer(sig, 'binary'); + sig = Signature.parse(sig, type, 'asn1'); + sig.hashAlgorithm = hashAlgo; + sig.curve = curve; + return (sig); + }; + return (v); +}; - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); +PrivateKey.parse = function (data, format, options) { + if (typeof (data) !== 'string') + assert.buffer(data, 'data'); + if (format === undefined) + format = 'auto'; + assert.string(format, 'format'); + if (typeof (options) === 'string') + options = { filename: options }; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalString(options.filename, 'options.filename'); + if (options.filename === undefined) + options.filename = '(unnamed)'; - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } + assert.object(formats[format], 'formats[format]'); - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; + try { + var k = formats[format].read(data, options); + assert.ok(k instanceof PrivateKey, 'key is not a private key'); + if (!k.comment) + k.comment = options.filename; + return (k); + } catch (e) { + if (e.name === 'KeyEncryptedError') + throw (e); + throw (new KeyParseError(options.filename, format, e)); + } +}; - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } +PrivateKey.isPrivateKey = function (obj, ver) { + return (utils.isCompatible(obj, PrivateKey, ver)); +}; - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } - } - return index; - } +PrivateKey.generate = function (type, options) { + if (options === undefined) + options = {}; + assert.object(options, 'options'); - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } + switch (type) { + case 'ecdsa': + if (options.curve === undefined) + options.curve = 'nistp256'; + assert.string(options.curve, 'options.curve'); + return (generateECDSA(options.curve)); + case 'ed25519': + return (generateED25519()); + default: + throw (new Error('Key generation not supported with key ' + + 'type "' + type + '"')); + } +}; - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } +/* + * API versions for PrivateKey: + * [1,0] -- initial ver + * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats + * [1,2] -- added defaultHashAlgorithm + * [1,3] -- added derive, ed, createDH + * [1,4] -- first tagged version + */ +PrivateKey.prototype._sshpkApiVersion = [1, 4]; - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); +PrivateKey._oldVersionDetect = function (obj) { + assert.func(obj.toPublic); + assert.func(obj.createSign); + if (obj.derive) + return ([1, 3]); + if (obj.defaultHashAlgorithm) + return ([1, 2]); + if (obj.formats['auto']) + return ([1, 1]); + return ([1, 0]); +}; - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } +/***/ }), +/* 26 */ +/***/ (function(module, exports) { - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } +module.exports = require("stream"); - /*--------------------------------------------------------------------------*/ +/***/ }), +/* 27 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); +var isObject = __webpack_require__(43); +module.exports = function(it){ + if(!isObject(it))throw TypeError(it + ' is not an object!'); + return it; +}; - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; +/***/ }), +/* 28 */ +/***/ (function(module, exports, __webpack_require__) { - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** + * @license + * Lodash <https://lodash.com/> + * Copyright JS Foundation and other contributors <https://js.foundation/> + * Released under MIT license <https://lodash.com/license> + * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; + /** Used as the semantic version number. */ + var VERSION = '4.17.4'; - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; - /** Used to generate unique IDs. */ - var idCounter = 0; + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function'; - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - /** Used to lookup unminified function names. */ - var realNames = {}; + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; - /*------------------------------------------------------------------------*/ + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + reLeadingDot = /^\./, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined; - } + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB) as well as ES2015 template strings. Change the - * following template settings to use alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ - lodash.templateSettings = { + /** Used to match leading and trailing whitespace. */ + var reTrim = /^\s+|\s+$/g, + reTrimStart = /^\s+/, + reTrimEnd = /\s+$/; - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; - /*------------------------------------------------------------------------*/ + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = copyArray(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = copyArray(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = copyArray(this.__views__); - return result; - } + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; - } + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - outer: - while (length-- && resIndex < takeCount) { - index += dir; + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; - var iterIndex = -1, - value = array[index]; + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)', + rsOrdUpper = '\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; - } - return result; - } + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - /*------------------------------------------------------------------------*/ + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; - /*------------------------------------------------------------------------*/ + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); - return index < 0 ? undefined : data[index][1]; - } + /** Detect free variable `exports`. */ + var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } + /** Detect free variable `module`. */ + var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); - /*------------------------------------------------------------------------*/ + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; + /*--------------------------------------------------------------------------*/ - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } + /** + * Adds the key-value `pair` to `map`. + * + * @private + * @param {Object} map The map to modify. + * @param {Array} pair The key-value pair to add. + * @returns {Object} Returns `map`. + */ + function addMapEntry(map, pair) { + // Don't return `map.set` because it's not chainable in IE 11. + map.set(pair[0], pair[1]); + return map; + } - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } + /** + * Adds `value` to `set`. + * + * @private + * @param {Object} set The set to modify. + * @param {*} value The value to add. + * @returns {Object} Returns `set`. + */ + function addSetEntry(set, value) { + // Don't return `set.add` because it's not chainable in IE 11. + set.add(value); + return set; + } - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); } + return func.apply(thisArg, args); + } - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); } + return accumulator; + } - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } } + return array; + } - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; - /*------------------------------------------------------------------------*/ + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; } } + return true; + } - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } } + return result; + } - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } - /*------------------------------------------------------------------------*/ + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } } + return false; + } - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; + } - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - this.size = data.size; - return result; + while (++index < length) { + array[offset + index] = values[index]; } + return array; + } - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); + if (initAccum && length) { + accumulator = array[++index]; } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - - /*------------------------------------------------------------------------*/ - - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; } - return result; } + return false; + } - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; } - } + }); + return result; + } - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } } + return -1; + } - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; } - return -1; } + return -1; + } - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; - } + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; + array.sort(comparer); + while (length--) { + array[length] = array[length].value; } + return array; + } - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG; + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; + } + return result; + } - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, baseClone, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); - - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; + while (++index < n) { + result[index] = iteratee(index); } + return result; + } - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length], - predicate = source[key], - value = object[key]; + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } + + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; } - return result; } + return result; + } - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } - while (++index < length) { - var value = array[index], - current = iteratee(value); + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; + while (!(data = iterator.next()).done) { + result.push(data.value); } + return result; + } - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } - predicate || (predicate = isFlattenable); - result || (result = []); + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; } - return result; } + return result; + } - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); - - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); - - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } - var index = 0, - length = path.length; + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; - while (object != null && index < length) { - object = object[toKey(path[index++])]; + while (++index < length) { + if (array[index] === value) { + return index; } - return (index && index == length) ? object : undefined; - } - - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } + return -1; + } - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); } + return index; + } - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; } + return result; + } - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } - var index = -1, - seen = caches[0]; + /*--------------------------------------------------------------------------*/ - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } + /** Used to generate unique IDs. */ + var idCounter = 0; - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); + var nativeObjectToString = objectProto.toString; - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ /** - * The base implementation of `_.isNative` without bad shim checks. + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); + return new LodashWrapper(value); } /** - * The base implementation of `_.isRegExp` without Node.js optimizations. + * The base implementation of `_.create` without support for assigning + * properties to the created object. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); /** - * The base implementation of `_.isSet` without Node.js optimizations. + * The function whose prototype chain sequence wrappers inherit from. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; + function baseLodash() { + // No operation performed. } /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. + * The base constructor for creating `lodash` wrapper objects. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; } /** - * The base implementation of `_.iteratee`. + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. + * @static + * @memberOf _ + * @type {Object} */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } + lodash.templateSettings = { - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash } - return result; - } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @constructor + * @param {*} value The value to wrap. */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; - - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; } /** - * The base implementation of `_.lt` which doesn't coerce arguments. + * Creates a clone of the lazy wrapper object. * * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. */ - function baseLt(value, other) { - return value < other; + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; } /** - * The base implementation of `_.map` without support for iteratee shorthands. + * Reverses the direction of lazy iteration. * * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } return result; } /** - * The base implementation of `_.matches` which doesn't clone `source`. + * Extracts the unwrapped value from its lazy wrapper. * * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); + + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } + return result; } + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * Creates a hash object. * * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; } /** - * The base implementation of `_.merge` without support for multiple sources. + * Removes all key-value entries from the hash. * * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. + * @name clear + * @memberOf Hash */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - if (isObject(srcValue)) { - stack || (stack = new Stack); - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(object[key], srcValue, (key + ''), object, source, stack) - : undefined; - - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; } /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. + * Removes `key` and its value from the hash. * * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = object[key], - srcValue = source[key], - stacked = stack.get(srcValue); - - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; - - var isCommon = newValue === undefined; - - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); - - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; } /** - * The base implementation of `_.nth` which doesn't coerce arguments. + * Gets the hash value for `key`. * * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; + return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** - * The base implementation of `_.orderBy` without param guards. + * Checks if a hash value for `key` exists. * * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function baseOrderBy(collection, iteratees, orders) { - var index = -1; - iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); - - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** - * The base implementation of `_.pick` without support for individual - * property identifiers. + * Sets the hash `key` to `value`. * * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; } + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. + * Creates an list cache object. * * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function basePickBy(object, paths, predicate) { + function ListCache(entries) { var index = -1, - length = paths.length, - result = {}; + length = entries == null ? 0 : entries.length; + this.clear(); while (++index < length) { - var path = paths[index], - value = baseGet(object, path); - - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } + var entry = entries[index]; + this.set(entry[0], entry[1]); } - return result; } /** - * A specialized version of `baseProperty` which supports deep paths. + * Removes all key-value entries from the list cache. * * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. + * @name clear + * @memberOf ListCache */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; + function listCacheClear() { + this.__data__ = []; + this.size = 0; } /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. + * Removes `key` and its value from the list cache. * * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); + if (index < 0) { + return false; } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; - - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); } - return array; + --this.size; + return true; } /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. + * Gets the list cache value for `key`. * * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; + return index < 0 ? undefined : data[index][1]; } /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. + * Checks if a list cache value for `key` exists. * * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. + * Sets the list cache `key` to `value`. * * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; } - return result; + return this; } + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + /** - * The base implementation of `_.repeat` which doesn't coerce arguments. + * Creates a map cache object to store key-value pairs. * * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); + function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - return result; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * Removes all key-value entries from the map. * * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. + * @name clear + * @memberOf MapCache */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } /** - * The base implementation of `_.sample`. + * Removes `key` and its value from the map. * * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function baseSample(collection) { - return arraySample(values(collection)); + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; } /** - * The base implementation of `_.sampleSize` without param guards. + * Gets the map value for `key`. * * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); + function mapCacheGet(key) { + return getMapData(this, key).get(key); } /** - * The base implementation of `_.set`. + * Checks if a map value for `key` exists. * * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; - - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; - - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; + function mapCacheHas(key) { + return getMapData(this, key).has(key); } /** - * The base implementation of `setData` without support for hot loop shorting. + * Sets the map `key` to `value`. * * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ /** - * The base implementation of `setToString` without support for hot loop shorting. + * + * Creates an array cache object to store unique values. * * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. + * @constructor + * @param {Array} [values] The values to cache. */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; + function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } + } /** - * The base implementation of `_.shuffle`. + * Adds `value` to the array cache. * * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; } /** - * The base implementation of `_.slice` without an iteratee call guard. + * Checks if `value` is in the array cache. * * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; + function setCacheHas(value) { + return this.__data__.has(value); + } - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } + /*------------------------------------------------------------------------*/ /** - * The base implementation of `_.some` without support for iteratee shorthands. + * Creates a stack cache object to store key-value pairs. * * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function baseSome(collection, predicate) { - var result; - - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; } /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. + * Removes all key-value entries from the stack. * * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. + * @name clear + * @memberOf Stack */ - function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; - - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; - - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; } /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). + * Removes `key` and its value from the stack. * * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - value = iteratee(value); - - var low = 0, - high = array == null ? 0 : array.length, - valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; - - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); + this.size = data.size; + return result; } /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. + * Gets the stack value for `key`. * * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; + function stackGet(key) { + return this.__data__.get(key); } /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. + * Checks if a stack value for `key` exists. * * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; + function stackHas(key) { + return this.__data__.has(key); } /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. + * Sets the stack `key` to `value`. * * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + data.set(key, value); + this.size = data.size; + return this; } + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * Creates an array of the enumerable property names of the array-like `value`. * * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; - - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); } } return result; } /** - * The base implementation of `_.unset`. + * A specialized version of `_.sample` for arrays. * * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; } /** - * The base implementation of `_.update`. + * A specialized version of `_.sampleSize` for arrays. * * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. + * A specialized version of `_.shuffle` for arrays. * * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; - - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} - - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); } /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. * * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); } /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); - - while (++index < length) { - var array = arrays[index], - othIndex = -1; - - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. + * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; - - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } } - return result; + return -1; } /** - * Casts `value` to an empty array if it's not an array like object. + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. * * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; } /** - * Casts `value` to `identity` if it's not a function. + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. * * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); } /** - * Casts `value` to a path array if it's not one. + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. * * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); } /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. * * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - var castRest = baseRest; + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } + } /** - * Casts `array` to a slice if it's needed. + * The base implementation of `_.at` without support for individual paths. * * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; } /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } /** - * Creates a clone of `buffer`. + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. * * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; - buffer.copy(result); + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, baseClone, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); return result; } /** - * Creates a clone of `arrayBuffer`. + * The base implementation of `_.conforms` which doesn't clone `source`. * * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; } /** - * Creates a clone of `dataView`. + * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; } /** - * Creates a clone of `map`. + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. * * @private - * @param {Object} map The map to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned map. + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. */ - function cloneMap(map, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); - return arrayReduce(array, addMapEntry, new map.constructor); + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); } /** - * Creates a clone of `regexp`. + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. * * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } return result; } /** - * Creates a clone of `set`. + * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private - * @param {Object} set The set to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned set. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - function cloneSet(set, isDeep, cloneFunc) { - var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); - return arrayReduce(array, addSetEntry, new set.constructor); - } + var baseEach = createBaseEach(baseForOwn); /** - * Creates a clone of the `symbol` object. + * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } + var baseEachRight = createBaseEach(baseForOwnRight, true); /** - * Creates a clone of `typedArray`. + * The base implementation of `_.every` without support for iteratee shorthands. * * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; } /** - * Compares values to sort them in ascending order. + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. * * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = isSymbol(value); + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = isSymbol(other); + while (++index < length) { + var value = array[index], + current = iteratee(value); - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; } } - return 0; + return result; } /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. + * The base implementation of `_.fill` without an iteratee call guard. * * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; + function baseFill(array, value, start, end) { + var length = array.length; - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; } /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. + * The base implementation of `_.filter` without support for iteratee shorthands. * * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; - - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } + }); return result; } /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. + * The base implementation of `_.flatten` with support for restricting flattening. * * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; + function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; } } return result; } /** - * Copies the values of `source` to `array`. + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. */ - function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } + var baseFor = createBaseFor(); /** - * Copies properties of `source` to `object`. + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. * * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } + var baseForRight = createBaseFor(true); /** - * Copies own symbols of `source` to `object`. + * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); } /** - * Copies own and inherited symbols of `source` to `object`. + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); } /** - * Creates a function like `_.groupBy`. + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. * * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; - - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); } /** - * Creates a function like `_.assign`. + * The base implementation of `_.get` without support for default values. * * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; + function baseGet(object, path) { + path = castPath(path, object); - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + var index = 0, + length = path.length; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; } /** - * Creates a `baseEach` or `baseEachRight` function. + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. * * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; + /** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); } /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * The base implementation of `_.gt` which doesn't coerce arguments. * * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; + function baseGt(value, other) { + return value > other; + } - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; + /** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); } /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. + * The base implementation of `_.hasIn` without support for deep paths. * * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); + function baseHasIn(object, key) { + return object != null && key in Object(object); + } - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; + /** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** - * Creates a function like `_.lowerFirst`. + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; - var strSymbols = hasUnicode(string) - ? stringToArray(string) + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) : undefined; + } + array = arrays[0]; - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); + var index = -1, + seen = caches[0]; - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; - return chr[methodName]() + trailing; - }; + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; } /** - * Creates a function like `_.camelCase`. + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. * * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; } /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * The base implementation of `_.invoke` without support for individual + * method arguments. * * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); - - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); } /** - * Creates a function that wraps `func` to enable currying. + * The base implementation of `_.isArguments`. * * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); - - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); - - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; } /** - * Creates a `_.find` or `_.findLast` function. + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** - * Creates a `_.flow` or `_.flowRight` function. + * The base implementation of `_.isDate` without Node.js optimizations. * * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; - - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; - - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; - - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; + } - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); + /** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. * * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } - return fn.apply(thisBinding, args); } - return wrapper; + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** - * Creates a function like `_.invertBy`. + * The base implementation of `_.isMap` without Node.js optimizations. * * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; } /** - * Creates a function that performs a mathematical operation on two values. + * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; } - if (other !== undefined) { - if (result === undefined) { - return other; + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; } - result = operator(value, other); } - return result; - }; + } + return true; } /** - * Creates a function like `_.over`. + * The base implementation of `_.isNative` without bad shim checks. * * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); } /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. + * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); - - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. + * The base implementation of `_.isSet` without Node.js optimizations. * * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); - } - return wrapper; + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; } /** - * Creates a `_.range` or `_.rangeRight` function. + * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** - * Creates a function that performs a relational operation on two values. + * The base implementation of `_.iteratee`. * * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); } /** - * Creates a function that wraps `func` to continue currying. + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; - - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; - - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); + return result; } /** - * Creates a function like `_.round`. + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); } - return func(number); - }; + } + return result; } /** - * Creates a set object of `values`. + * The base implementation of `_.lt` which doesn't coerce arguments. * * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; + function baseLt(value, other) { + return value < other; + } /** - * Creates a `_.toPairs` or `_.toPairsIn` function. + * The base implementation of `_.map` without support for iteratee shorthands. * * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } + + /** + * The base implementation of `_.matches` which doesn't clone `source`. * * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. */ - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; - - partials = holders = undefined; - } - var data = isBindKey ? undefined : getData(func); - - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; - - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); - - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; } /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); } - return objValue; + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; } /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. + * The base implementation of `_.merge` without support for multiple sources. * * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. - * @returns {*} Returns the value to assign. */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; } - return objValue; - } + baseFor(source, function(srcValue, key) { + if (isObject(srcValue)) { + stack || (stack = new Stack); + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(object[key], srcValue, (key + ''), object, source, stack) + : undefined; - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); } /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. * * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = object[key], + srcValue = source[key], + stacked = stack.get(srcValue); - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(array); - if (stacked && stack.get(other)) { - return stacked == other; + if (stacked) { + assignMergeValue(object, key, stacked); + return; } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; - stack.set(array, other); - stack.set(other, array); + var isCommon = newValue === undefined; - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; } - result = false; - break; } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; + else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; } } - stack['delete'](array); - stack['delete'](other); - return result; + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); } /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * The base implementation of `_.nth` which doesn't coerce arguments. * * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); - - case errorTag: - return object.name == other.name && object.message == other.message; - - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag: - var convert = mapToArray; - - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; } - return false; + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; } /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. + * The base implementation of `_.orderBy` without param guards. * * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked && stack.get(other)) { - return stacked == other; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; + function baseOrderBy(collection, iteratees, orders) { + var index = -1; + iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); } /** - * A specialized version of `baseRest` which flattens the rest array. + * The base implementation of `_.pick` without support for individual + * property identifiers. * * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); } /** - * Creates an array of own enumerable property names and symbols of `object`. + * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; } /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. + * A specialized version of `baseProperty` which supports deep paths. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; } /** - * Gets metadata for `func`. + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. * * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } /** - * Gets the name of `func`. + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. * * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } } } - return result; + return array; } /** - * Gets the argument placeholder value for `func`. + * The base implementation of `_.random` without support for returning + * floating-point numbers. * * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. * * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; } /** - * Gets the data for `map`. + * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; } /** - * Gets the property names, values, and compare flags of `object`. + * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. */ - function getMatchData(object) { - var result = keys(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); + } - result[length] = [key, value, isStrictComparable(value)]; - } - return result; + /** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); } /** - * Gets the native function at `key` of `object`. + * The base implementation of `_.sampleSize` without param guards. * * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * The base implementation of `_.set`. * * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } } + assignValue(nested, key, newValue); + nested = nested[key]; } - return result; + return object; } /** - * Creates an array of the own enumerable symbols of `object`. + * The base implementation of `setData` without support for hot loop shorting. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; }; /** - * Creates an array of the own and inherited enumerable symbols of `object`. + * The base implementation of `setToString` without support for hot loop shorting. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); }; /** - * Gets the `toStringTag` of `value`. + * The base implementation of `_.shuffle`. * * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. */ - var getTag = baseGetTag; - - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; + function baseShuffle(collection) { + return shuffleSelf(values(collection)); } /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. + * The base implementation of `_.slice` without an iteratee call guard. * * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. */ - function getView(start, end, transforms) { + function baseSlice(array, start, end) { var index = -1, - length = transforms.length; + length = array.length; - while (++index < length) { - var data = transforms[index], - size = data.size; + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; } - return { 'start': start, 'end': end }; + return result; } /** - * Extracts wrapper details from the `source` body comment. + * The base implementation of `_.some` without support for iteratee shorthands. * * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; } /** - * Checks if `path` exists on `object`. + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. * * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; - var index = -1, - length = path.length, - result = false; + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } } - object = object[key]; + return high; } - if (result || ++index != length) { - return result; + return baseSortedIndexBy(array, value, identity, retHighest); + } + + /** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ + function baseSortedIndexBy(array, value, iteratee, retHighest) { + value = iteratee(value); + + var low = 0, + high = array == null ? 0 : array.length, + valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); + return nativeMin(high, MAX_ARRAY_INDEX); } /** - * Initializes an array clone. + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. * * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. */ - function initCloneArray(array) { - var length = array.length, - result = array.constructor(length); + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } } return result; } /** - * Initializes an object clone. + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. * * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. + * @param {*} value The value to process. + * @returns {number} Returns the number. */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; } /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. * * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {Function} cloneFunc The function to clone values. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. + * @param {*} value The value to process. + * @returns {string} Returns the string. */ - function initCloneByTag(object, tag, cloneFunc, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - - case boolTag: - case dateTag: - return new Ctor(+object); - - case dataViewTag: - return cloneDataView(object, isDeep); - - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); - - case mapTag: - return cloneMap(object, isDeep, cloneFunc); - - case numberTag: - case stringTag: - return new Ctor(object); - - case regexpTag: - return cloneRegExp(object); - - case setTag: - return cloneSet(object, isDeep, cloneFunc); - - case symbolTag: - return cloneSymbol(object); + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * Inserts wrapper `details` in a comment at the top of the `source` body. + * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; } /** - * Checks if `value` is a flattenable `arguments` object or array. + * The base implementation of `_.unset`. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; } /** - * Checks if `value` is a valid array-like index. + * The base implementation of `_.update`. * * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. */ - function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** - * Checks if the given arguments are from an iteratee call. + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. * * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** - * Checks if `value` is a property name and not a property path. + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. * * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); } /** - * Checks if `value` is suitable for use as unique object key. + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); + + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } + } + return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** - * Checks if `func` has a lazy counterpart. + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; + function baseZipObject(props, values, assignFunc) { + var index = -1, + length = props.length, + valsLength = values.length, + result = {}; - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); } - var data = getData(other); - return !!data && func === data[0]; + return result; } /** - * Checks if `func` has its source masked. + * Casts `value` to an empty array if it's not an array like object. * * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; } /** - * Checks if `func` is capable of being masked. + * Casts `value` to `identity` if it's not a function. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. */ - var isMaskable = coreJsData ? isFunction : stubFalse; + function castFunction(value) { + return typeof value == 'function' ? value : identity; + } /** - * Checks if `value` is likely a prototype object. + * Casts `value` to a path array if it's not one. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; + function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. */ - function isStrictComparable(value) { - return value === value && !isObject(value); - } + var castRest = baseRest; /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. + * Casts `array` to a slice if it's needed. * * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); } /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. + * @param {number|Object} id The timer id or timeout object of the timer to clear. */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; - } + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. + * Creates a clone of `buffer`. * * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - return data; + buffer.copy(result); + return result; } /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. + * Creates a clone of `arrayBuffer`. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** - * Converts `value` to a string using `Object.prototype.toString`. + * Creates a clone of `dataView`. * * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. */ - function objectToString(value) { - return nativeObjectToString.call(value); + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** - * A specialized version of `baseRest` which transforms the rest array. + * Creates a clone of `map`. * * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. + * @param {Object} map The map to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned map. */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; + function cloneMap(map, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); + return arrayReduce(array, addMapEntry, new map.constructor); } /** - * Gets the parent value at `path` of `object`. + * Creates a clone of `regexp`. * * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; } /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. + * Creates a clone of `set`. * * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. - */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; + * @param {Object} set The set to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned set. + */ + function cloneSet(set, isDeep, cloneFunc) { + var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); + return arrayReduce(array, addSetEntry, new set.constructor); } /** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. + * Creates a clone of the `symbol` object. * * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. */ - var setData = shortOut(baseSetData); + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; + } /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * Creates a clone of `typedArray`. * * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } /** - * Sets the `toString` method of `func` to return `string`. + * Compares values to sort them in ascending order. * * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. */ - var setToString = shortOut(baseSetToString); + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); - /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. - * - * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. - */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; } /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. * * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; } - } else { - count = 0; + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); } - return func.apply(undefined, arguments); - }; + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; } /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. * * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. */ - function shuffleSelf(array, size) { - var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; - array[rand] = array[index]; - array[index] = value; + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; } - array.length = size; - return array; + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; } /** - * Converts `string` to a property path array. + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. * * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (reLeadingDot.test(string)) { - result.push(''); + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } } - string.replace(rePropName, function(match, number, quote, string) { - result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); - }); return result; - }); + } /** - * Converts `value` to a string key if it's not a string or symbol. + * Copies the values of `source` to `array`. * * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + return array; } /** - * Converts `func` to its source code. + * Copies properties of `source` to `object`. * * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } } - return ''; + return object; } /** - * Updates wrapper `details` based on `bitmask` flags. + * Copies own symbols of `source` to `object`. * * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); } /** - * Creates a clone of `wrapper`. + * Copies own and inherited symbols of `source` to `object`. * * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); } - /*------------------------------------------------------------------------*/ - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] + * Creates a function like `_.groupBy`. * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; + return func(collection, setter, getIteratee(iteratee, 2), accumulator); + }; } /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example + * Creates a function like `_.assign`. * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. */ - function compact(array) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; - while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; } - } - return result; + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); } /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] + * Creates a `baseEach` or `baseEachRight` function. * - * console.log(array); - * // => [1] + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; } /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example + * Creates a base function for methods like `_.forIn` and `_.forOwn`. * - * _.difference([2, 1], [2, 3]); - * // => [1] + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); - - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] - * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); + return wrapper; } /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] + * Creates a function like `_.lowerFirst`. * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; } /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] + * Creates a function like `_.camelCase`. * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; } /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; } /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] + * Creates a function that wraps `func` to enable currying. * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); } - return baseFill(array, value, start, end); + return wrapper; } /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 + * Creates a `_.find` or `_.findLast` function. * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; } /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 + * Creates a `_.flow` or `_.flowRight` function. * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); } /** - * Flattens `array` a single level deep. + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; } /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example + * Creates a function like `_.invertBy`. * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; } /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; - * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] + * Creates a function that performs a mathematical operation on two values. * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; } /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example + * Creates a function like `_.over`. * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; - - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; - } - return result; + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); } /** - * Gets the first element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example - * - * _.head([1, 2, 3]); - * // => 1 + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. * - * _.head([]); - * // => undefined + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. */ - function head(array) { - return (array && array.length) ? array[0] : undefined; + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); } /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); } - return baseIndexOf(array, value, index); + return wrapper; } /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * Creates a `_.range` or `_.rangeRight` function. * - * _.initial([1, 2, 3]); - * // => [1, 2] + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; } /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example + * Creates a function that performs a relational operation on two values. * - * _.intersection([2, 1], [2, 3]); - * // => [2] + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] + * Creates a function that wraps `func` to continue currying. * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; - if (iteratee === last(mapped)) { - iteratee = undefined; - } else { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] - */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); + } /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example + * Creates a function like `_.round`. * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; } /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example + * Creates a set object of `values`. * - * _.last([1, 2, 3]); - * // => 3 + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; - } + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. + * Creates a `_.toPairs` or `_.toPairsIn` function. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; } /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. * - * _.nth(array, -2); - * // => 'c'; + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; - } + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; - /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] - */ - var pull = baseRest(pullAll); + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; - /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; - * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] - */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); } /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; } /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; } /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. * - * console.log(pulled); - * // => ['b', 'd'] + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - - return result; - }); + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. * - * console.log(evens); - * // => [2, 4] + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(array); + if (stacked && stack.get(other)) { + return stacked == other; } var index = -1, - indexes = [], - length = array.length; + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; } } - basePullAt(array, indexes); + stack['delete'](array); + stack['delete'](other); return result; } /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. * - * _.reverse(array); - * // => [3, 2, 1] + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * console.log(array); - * // => [3, 2, 1] + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; } /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked && stack.get(other)) { + return stacked == other; } - return baseSlice(array, start, end); + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; } /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example + * A specialized version of `baseRest` which flattens the rest array. * - * _.sortedIndex([30, 50], 40); - * // => 1 + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); } /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * Creates an array of own enumerable property names and symbols of `object`. * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); + } + + /** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. + * Gets metadata for `func`. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; + + /** + * Gets the name of `func`. * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; } } - return -1; + return result; } /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example + * Gets the argument placeholder value for `func`. * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; } /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; } /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example + * Gets the data for `map`. * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; } /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example + * Gets the property names, values, and compare flags of `object`. * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; } /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example + * Gets the native function at `key` of `object`. * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * - * _.tail([1, 2, 3]); - * // => [2, 3] + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; } /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] + * Creates an array of the own enumerable symbols of `object`. * - * _.take([1, 2, 3], 0); - * // => [] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. */ - function take(array, n, guard) { - if (!(array && array.length)) { + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { return []; } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); - } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] + * Creates an array of the own and inherited enumerable symbols of `object`. * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; + + /** + * Gets the `toStringTag` of `value`. * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; + } + + /** + * Gets the view, applying any `transforms` to the `start` and `end` positions. * - * _.takeRight([1, 2, 3], 0); - * // => [] + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; + } } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); + return { 'start': start, 'end': end }; } /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). + * Extracts wrapper details from the `source` body comment. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; } /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] + * Checks if `path` exists on `object`. * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); } /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example + * Initializes an array clone. * - * _.union([2], [1, 2]); - * // => [2, 1] + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); + function initCloneArray(array) { + var length = array.length, + result = array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; + } /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). + * Initializes an object clone. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; + } + + /** + * Initializes an object clone based on its `toStringTag`. * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {Function} cloneFunc The function to clone values. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; + function initCloneByTag(object, tag, cloneFunc, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return cloneMap(object, isDeep, cloneFunc); + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return cloneSet(object, isDeep, cloneFunc); + + case symbolTag: + return cloneSymbol(object); } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); + } /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * Inserts wrapper `details` in a comment at the top of the `source` body. * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); + } /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example + * Checks if `value` is a flattenable `arguments` object or array. * - * _.uniq([2, 1, 2]); - * // => [2, 1] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); } /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] + * Checks if `value` is a valid array-like index. * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); } /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * Checks if the given arguments are from an iteratee call. * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; } /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * Checks if `value` is a property name and not a property path. * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ - function unzip(array) { - if (!(array && array.length)) { - return []; + function isKey(value, object) { + if (isArray(value)) { + return false; } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); } /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example + * Checks if `value` is suitable for use as unique object key. * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } + + /** + * Checks if `func` has a lazy counterpart. * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; } - var result = unzip(array); - if (iteratee == null) { - return result; + if (func === other) { + return true; } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); + var data = getData(other); + return !!data && func === data[0]; } /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example + * Checks if `func` has its source masked. * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); + } /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. + * Checks if `func` is capable of being masked. * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ + var isMaskable = coreJsData ? isFunction : stubFalse; + + /** + * Checks if `value` is likely a prototype object. * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; + } /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] - * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); + function isStrictComparable(value) { + return value === value && !isObject(value); + } /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; + } /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. */ - var zip = baseRest(unzip); + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); - /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example - * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } - */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); + var cache = result.cache; + return result; } /** - * This method is like `_.zipObject` except that it supports property paths. + * Merges the function metadata of `source` into `data`. * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); - } + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] - */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; - /*------------------------------------------------------------------------*/ + return data; + } /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } return result; } /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example + * Converts `value` to a string using `Object.prototype.toString`. * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. */ - function tap(value, interceptor) { - interceptor(value); - return value; + function objectToString(value) { + return nativeObjectToString.call(value); } /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example + * A specialized version of `baseRest` which transforms the rest array. * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. */ - function thru(value, interceptor) { - return interceptor(value); + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; } /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example + * Gets the parent value at `path` of `object`. * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + + /** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); - } - return array; - }); - }); + return array; + } /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; + * Sets metadata for `func`. * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - function wrapperChain() { - return chain(this); - } + var setData = shortOut(baseSetData); /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * - * console.log(array); - * // => [1, 2, 3] + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } + * Sets the `toString` method of `func` to return `string`. * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; + var setToString = shortOut(baseSetToString); - return { 'done': done, 'value': value }; + /** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** - * Enables the wrapper to be iterable. + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true - * - * Array.from(wrapped); - * // => [1, 2] + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. */ - function wrapperToIterator() { - return this; + function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; } /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); - * - * other.value(); - * // => [9, 16] + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * - * wrapped.value(); - * // => [1, 4] + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. */ - function wrapperPlant(value) { - var result, - parent = this; + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; - } - var previous = clone; - parent = parent.__wrapped__; + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; } - previous.__wrapped__ = value; - return result; + array.length = size; + return array; } /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example + * Converts `string` to a property path array. * - * var array = [1, 2, 3]; + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (reLeadingDot.test(string)) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, string) { + result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); + + /** + * Converts `value` to a string key if it's not a string or symbol. * - * _(array).reverse().value() - * // => [3, 2, 1] + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + } + + /** + * Converts `func` to its source code. * - * console.log(array); - * // => [3, 2, 1] + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} } - return this.thru(reverse); + return ''; } /** - * Executes the chain sequence to resolve the unwrapped value. + * Updates wrapper `details` based on `bitmask` flags. * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; } /*------------------------------------------------------------------------*/ /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. * * @static * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. * @example * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; } else { - baseAssignValue(result, key, 1); + size = nativeMax(toInteger(size), 0); } - }); + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; + } /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } } - return func(collection, getIteratee(predicate, 3)); + return result; } /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. + * Creates a new array concatenating `array` with any additional arrays + * and/or values. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. * @example * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] + * console.log(other); + * // => [1, 2, 3, [4]] * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] + * console.log(array); + * // => [1] */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor * @example * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' - * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' + * _.difference([2, 1], [2, 3]); + * // => [1] */ - var find = createFind(findIndex); + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - var findLast = createFind(findLastIndex); + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * function duplicate(n) { - * return [n, n]; - * } + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); - } + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. + * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); - } - - /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. + * _.drop([1, 2, 3]); + * // => [2, 3] * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example + * _.drop([1, 2, 3], 2); + * // => [3] * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * _.drop([1, 2, 3], 5); + * // => [] * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. + * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. + * _.dropRight([1, 2, 3]); + * // => [1, 2] * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). - */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); - } - - /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. + * _.dropRight([1, 2, 3], 2); + * // => [1] * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example + * _.dropRight([1, 2, 3], 5); + * // => [] * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); } /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } - * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); - } - }); - - /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * _.includes([1, 2, 3], 1); - * // => true + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] * - * _.includes([1, 2, 3], 1, 2); - * // => false + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] * - * _.includes('abcd', 'bc'); - * // => true + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; - - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; } /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). * * @static * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; - - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result; - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * **Note:** This method mutates `array`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. * @example * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] + * var array = [1, 2, 3]; * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; + * _.fill(Array(3), 2); + * // => [2, 2, 2] * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); } /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } * ]; * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); } - return baseOrderBy(collection, iteratees, orders); + return baseFindIndex(array, getIteratee(predicate, 3), index); } /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. * * @static * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } * ]; * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 * * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 * * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] + * _.findLastIndex(users, ['active', false]); + * // => 2 * * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] + * _.findLastIndex(users, 'active'); + * // => 0 */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` + * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; } /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. + * Recursively flattens `array`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * var array = [[0, 1], [2, 3], [4, 5]]; - * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; } /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. + * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. * @example * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; - * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] + * var array = [1, [2, [3, [4]], 5]]; * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); } /** - * Gets a random element from `collection`. + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. * * @static * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. * @example * - * _.sample([1, 2, 3, 4]); - * // => 2 + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; } /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. + * Gets the first element of `array`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. * @example * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] + * _.head([1, 2, 3]); + * // => 1 * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] + * _.head([]); + * // => undefined */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); + function head(array) { + return (array && array.length) ? array[0] : undefined; } /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); } /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. + * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 - * - * _.size('pebbles'); - * // => 7 + * _.initial([1, 2, 3]); + * // => [1, 2] */ - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; } /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. * @example * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] * * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); } - return func(collection, getIteratee(predicate, 3)); - } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. * @example * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; }); - /*------------------------------------------------------------------------*/ - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). + * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. * @example * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' */ - var now = ctxNow || function() { - return root.Date.now(); - }; - - /*------------------------------------------------------------------------*/ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. + * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. * @example * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. + * _.last([1, 2, 3]); + * // => 3 */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; } /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. * * @static * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); } /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. * * @static * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. * @example * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; - }; + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. * @example * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); + var pull = baseRest(pullAll); /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. + * This method is like `_.pull` except that it accepts an array of values to remove. * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. + * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. * @example * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' - * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; - * - * bound('!'); - * // => 'hiya fred!' + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). * - * **Note:** This method doesn't set the "length" property of curried functions. + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. * @example * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * - * var curried = _.curry(abc); + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). * - * curried(1)(2)(3); - * // => [1, 2, 3] + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * - * curried(1, 2)(3); - * // => [1, 2, 3] + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example * - * curried(1, 2, 3); - * // => [1, 2, 3] + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; } /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. * - * **Note:** This method doesn't set the "length" property of curried functions. + * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. * @example * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); * - * curried(1, 2, 3); - * // => [1, 2, 3] + * console.log(array); + * // => ['a', 'c'] * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] + * console.log(pulled); + * // => ['b', 'd'] */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + return result; - } + }); /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. * @example * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); + * console.log(array); + * // => [1, 3] * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); + * console.log(evens); + * // => [2, 4] */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } - - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; - - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } - - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } - - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - result = wait - timeSinceLastCall; - - return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; - } - - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; - - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } - - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } - - function trailingEdge(time) { - timerId = undefined; - - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined; + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { return result; } + var index = -1, + indexes = [], + length = array.length; - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } - - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } - - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); - - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); } - return result; } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; + basePullAt(array, indexes); + return result; } /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. * @example * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } /** - * Creates a function that invokes `func` with arguments reversed. + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); - * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] + * _.sortedIndex([30, 50], 40); + * // => 1 */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); + function sortedIndex(array, value) { + return baseSortedIndex(array, value); } /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } - // Expose `MapCache`. - memoize.Cache = MapCache; - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * function isEven(n) { - * return n % 2 == 0; - * } - * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; } - return !predicate.apply(this, args); - }; + } + return -1; } /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 */ - function once(func) { - return before(2, func); + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); } /** - * Creates a function that invokes `func` with its arguments transformed. + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * * @static - * @since 4.0.0 * @memberOf _ - * @category Function - * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * func(9, 3); - * // => [81, 6] + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 * - * func(10, 5); - * // => [100, 10] + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); - - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. * * @static * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. * * @static * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. * @example * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. * * @static * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); - * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. - * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). + * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); - * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' + * _.tail([1, 2, 3]); + * // => [2, 3] */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; } /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). + * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); + * _.take([1, 2, 3]); + * // => [1] * - * say(['fred', 'hello']); - * // => 'fred says hello' + * _.take([1, 2, 3], 2); + * // => [1, 2] * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 + * _.take([1, 2, 3], 0); + * // => [] */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + function take(array, n, guard) { + if (!(array && array.length)) { + return []; } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); - - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); } /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. + * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * _.takeRight([1, 2, 3]); + * // => [3] * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * * @static * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] */ - function unary(func) { - return ary(func, 1); + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; } /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * * @static * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * var p = _.wrap(_.escape, function(func, text) { - * return '<p>' + func(text) + '</p>'; - * }); + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * p('fred, barney, & pebbles'); - * // => '<p>fred, barney, & pebbles</p>' + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; } - /*------------------------------------------------------------------------*/ - /** - * Casts `value` as an array if it's not one. + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * * @static * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. * @example * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true + * _.union([2], [1, 2]); + * // => [2, 1] */ - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; - } + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. * @example * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. * @example * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); /** - * This method is like `_.clone` except that it recursively clones `value`. + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. * * @static * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. * @example * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false + * _.uniq([2, 1, 2]); + * // => [2, 1] */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; } /** - * This method is like `_.cloneWith` except that it recursively clones `value`. + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. * @example * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] * - * _.eq(NaN, NaN); - * // => true + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] */ - function eq(value, other) { - return value === other || (value !== value && other !== other); + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); } /** - * Checks if `value` is greater than `other`. + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. * @example * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] * - * _.gt(1, 3); - * // => false + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] */ - var gt = createRelationalOperation(baseGt); + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } /** - * Checks if `value` is greater than or equal to `other`. + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor * @example * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true - * - * _.gte(1, 3); - * // => false + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; }); /** - * Checks if `value` is likely an `arguments` object. + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without * @example * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false + * _.xor([2, 1], [2, 3]); + * // => [1, 3] */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); /** - * Checks if `value` is classified as an `Array` object. + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] * - * _.isArray(_.noop); - * // => false + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - var isArray = Array.isArray; + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); /** - * Checks if `value` is classified as an `ArrayBuffer` object. + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.isArrayBuffer(new Array(2)); - * // => false + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. * @example * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } + var zip = baseRest(unzip); /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. * @example * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); } /** - * Checks if `value` is classified as a boolean primitive or object. + * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. * @example * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); } /** - * Checks if `value` is a buffer. + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. * @example * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] */ - var isBuffer = nativeIsBuffer || stubFalse; + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ /** - * Checks if `value` is classified as a `Date` object. + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.isDate(new Date); - * // => true + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; * - * _.isDate('Mon April 23 2012'); - * // => false + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; + } /** - * Checks if `value` is likely a DOM element. + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. * @example * - * _.isElement(document.body); - * // => true - * - * _.isElement('<body>'); - * // => false + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + function tap(value, interceptor) { + interceptor(value); + return value; } /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @since 3.0.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. * @example * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] + */ + function thru(value, interceptor) { + return interceptor(value); + } + + /** + * This method is the wrapper version of `_.at`. * - * _.isEmpty(1); - * // => true + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example * - * _.isEmpty([1, 2, 3]); - * // => false + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * - * _.isEmpty({ 'a': 1 }); - * // => false + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); } - } - return true; - } + return array; + }); + }); /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. + * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * - * @static + * @name chain * @memberOf _ * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 } + * ]; * - * _.isEqual(object, other); - * // => true + * // A sequence without explicit chaining. + * _(users).head(); + * // => { 'user': 'barney', 'age': 36 } * - * object === other; - * // => false + * // A sequence with explicit chaining. + * _(users) + * .chain() + * .head() + * .pick('user') + * .value(); + * // => { 'user': 'barney' } */ - function isEqual(value, other) { - return baseIsEqual(value, other); + function wrapperChain() { + return chain(this); } /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * Executes the chain sequence and returns the wrapped result. * - * @static + * @name commit * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } + * var array = [1, 2]; + * var wrapped = _(array).push(3); * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } + * console.log(array); + * // => [1, 2] * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] * - * _.isEqualWith(array, other, customizer); - * // => true + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); } /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * - * @static + * @name next * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. * @example * - * _.isError(new Error); - * // => true + * var wrapped = _([1, 2]); * - * _.isError(Error); - * // => false + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } */ - function isError(value) { - if (!isObjectLike(value)) { - return false; + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; } /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * Enables the wrapper to be iterable. * - * @static + * @name Symbol.iterator * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. * @example * - * _.isFinite(3); - * // => true + * var wrapped = _([1, 2]); * - * _.isFinite(Number.MIN_VALUE); + * wrapped[Symbol.iterator]() === wrapped; * // => true * - * _.isFinite(Infinity); - * // => false - * - * _.isFinite('3'); - * // => false + * Array.from(wrapped); + * // => [1, 2] */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); + function wrapperToIterator() { + return this; } /** - * Checks if `value` is classified as a `Function` object. + * Creates a clone of the chain sequence planting `value` as the wrapped value. * - * @static + * @name plant * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.isFunction(_); - * // => true + * function square(n) { + * return n * n; + * } * - * _.isFunction(/abc/); - * // => false + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] */ - function isFunction(value) { - if (!isObject(value)) { - return false; + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + previous.__wrapped__ = value; + return result; } /** - * Checks if `value` is an integer. + * This method is the wrapper version of `_.reverse`. * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * **Note:** This method mutates the wrapped array. * - * @static + * @name reverse * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false + * var array = [1, 2, 3]; * - * _.isInteger(Infinity); - * // => false + * _(array).reverse().value() + * // => [3, 2, 1] * - * _.isInteger('3'); - * // => false + * console.log(array); + * // => [3, 2, 1] */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); - } - - /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * Executes the chain sequence to resolve the unwrapped value. + * + * @name value * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @since 0.1.0 + * @alias toJSON, valueOf + * @category Seq + * @returns {*} Returns the resolved unwrapped value. * @example * - * _.isLength(3); - * // => true + * _([1, 2, 3]).value(); + * // => [1, 2, 3] + */ + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). * - * _.isLength(Number.MIN_VALUE); - * // => false + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example * - * _.isLength(Infinity); - * // => false + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } * - * _.isLength('3'); - * // => false + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. * @example * - * _.isObject({}); - * // => true + * _.every([true, 1, null, 'yes'], Boolean); + * // => false * - * _.isObject([1, 2, 3]); - * // => true + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; * - * _.isObject(_.noop); + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); * // => true * - * _.isObject(null); + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); * // => false */ - function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); + function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); } /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject * @example * - * _.isObjectLike({}); - * // => true + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; * - * _.isObjectLike([1, 2, 3]); - * // => true + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] * - * _.isObjectLike(_.noop); - * // => false + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] * - * _.isObjectLike(null); - * // => false + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; + function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); } /** - * Checks if `value` is classified as a `Map` object. + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. * @example * - * _.isMap(new Map); - * // => true + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; * - * _.isMap(new WeakMap); - * // => false + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + var find = createFind(findIndex); /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. * * @static * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. * @example * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true - * - * _.isMatch(object, { 'b': 1 }); - * // => false + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } + var findLast = createFind(findLastIndex); /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. * @example * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } + * function duplicate(n) { + * return [n, n]; * } * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; - * - * _.isMatchWith(object, source, customizer); - * // => true + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); } /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. * @example * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true + * function duplicate(n) { + * return [[[n, n]]]; + * } * - * _.isNaN(undefined); - * // => false + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); } /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. * * @static * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. * @example * - * _.isNative(Array.prototype.push); - * // => true + * function duplicate(n) { + * return [[[n, n]]]; + * } * - * _.isNative(_); - * // => false + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); } /** - * Checks if `value` is `null`. + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight * @example * - * _.isNull(null); - * // => true + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. * - * _.isNull(void 0); - * // => false + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ - function isNull(value) { - return value === null; + function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); } /** - * Checks if `value` is `null` or `undefined`. + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach * @example * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true - * - * _.isNil(NaN); - * // => false + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. */ - function isNil(value) { - return value == null; + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); } /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. * @example * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } * - * _.isNumber('3'); - * // => false + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); - } + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. * * @static * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false + * _.includes([1, 2, 3], 1); + * // => true * - * _.isPlainObject([1, 2, 3]); + * _.includes([1, 2, 3], 1, 2); * // => false * - * _.isPlainObject({ 'x': 0, 'y': 0 }); + * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * - * _.isPlainObject(Object.create(null)); + * _.includes('abcd', 'bc'); * // => true */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** - * Checks if `value` is classified as a `RegExp` object. + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. * @example * - * _.isRegExp(/abc/); - * // => true + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] * - * _.isRegExp('/abc/'); - * // => false + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. * @example * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; * - * _.isSafeInteger(Infinity); - * // => false + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * - * _.isSafeInteger('3'); - * // => false + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); /** - * Checks if `value` is classified as a `Set` object. + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. * @example * - * _.isSet(new Set); - * // => true + * function square(n) { + * return n * n; + * } * - * _.isSet(new WeakSet); - * // => false - */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - - /** - * Checks if `value` is classified as a `String` primitive or object. + * _.map([4, 8], square); + * // => [16, 64] * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) * - * _.isString('abc'); - * // => true + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; * - * _.isString(1); - * // => false + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); } /** - * Checks if `value` is classified as a `Symbol` primitive or object. + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. * @example * - * _.isSymbol(Symbol.iterator); - * // => true + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; * - * _.isSymbol('abc'); - * // => false + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); } /** - * Checks if `value` is classified as a typed array. + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. * @example * - * _.isTypedArray(new Uint8Array); - * // => true + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; * - * _.isTypedArray([]); - * // => false + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); /** - * Checks if `value` is `undefined`. + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight * @example * - * _.isUndefined(void 0); - * // => true + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 * - * _.isUndefined(null); - * // => false + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ - function isUndefined(value) { - return value === undefined; + function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** - * Checks if `value` is classified as a `WeakMap` object. + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce * @example * - * _.isWeakMap(new WeakMap); - * // => true + * var array = [[0, 1], [2, 3], [4, 5]]; * - * _.isWeakMap(new Map); - * // => false + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** - * Checks if `value` is classified as a `WeakSet` object. + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. * * @static * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter * @example * - * _.isWeakSet(new WeakSet); - * // => true + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; * - * _.isWeakSet(new Set); - * // => false + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); } /** - * Checks if `value` is less than `other`. + * Gets a random element from `collection`. * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. * @example * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false - * - * _.lt(3, 1); - * // => false + * _.sample([1, 2, 3, 4]); + * // => 2 */ - var lt = createRelationalOperation(baseLt); + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } /** - * Checks if `value` is less than or equal to `other`. + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. * * @static * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. * @example * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] * - * _.lte(3, 1); - * // => false + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } /** - * Converts `value` to an array. + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static - * @since 0.1.0 * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. * @example * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] - * - * _.toArray(null); - * // => [] + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); - - return func(value); + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); } /** - * Converts `value` to a finite number. + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. * @example * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 + * _.size([1, 2, 3]); + * // => 3 * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 * - * _.toFinite('3.2'); - * // => 3.2 + * _.size('pebbles'); + * // => 7 */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; + function size(collection) { + if (collection == null) { + return 0; } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; } - return value === value ? value : 0; + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; } /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example * - * _.toInteger(3.2); - * // => 3 + * _.some([null, 0, 'yes', false], Boolean); + * // => true * - * _.toInteger(Number.MIN_VALUE); - * // => 0 + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false * - * _.toInteger('3.2'); - * // => 3 + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; - - return result === result ? (remainder ? result - remainder : result) : 0; + function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); } /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. * @example * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 34 } + * ]; * - * _.toLength(Infinity); - * // => 4294967295 + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * - * _.toLength('3.2'); - * // => 3 + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ /** - * Converts `value` to a number. + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. * @example * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. */ - function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; - } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); - } + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. * * @static * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. * @example * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var saves = ['profile', 'settings']; * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); + function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; } /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. * @example * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); + function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. * @example * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. */ - function toString(value) { - return value == null ? '' : baseToString(value); + function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; } - /*------------------------------------------------------------------------*/ - /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. * * @static * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. * @example * - * function Foo() { - * this.a = 1; + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; * } * - * function Bar() { - * this.c = 3; - * } + * var object = { 'user': 'fred' }; * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } + var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG; } + return createWrap(func, bitmask, thisArg, partials, holders); }); /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. * - * **Note:** This method mutates `object`. + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ - * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. * @example * - * function Foo() { - * this.a = 1; - * } + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; * - * function Bar() { - * this.c = 3; - * } + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); }); /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. * - * **Note:** This method mutates `object`. + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. * @example * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; * - * var defaults = _.partialRight(_.assignInWith, customizer); + * var curried = _.curry(abc); * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. * - * **Note:** This method mutates `object`. + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. * @example * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; * - * var defaults = _.partialRight(_.assignWith, customizer); + * var curried = _.curryRight(abc); * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); - - /** - * Creates an array of values corresponding to `paths` of `object`. + * curried(3)(2)(1); + * // => [1, 2, 3] * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Array} Returns the picked values. - * @example + * curried(2, 3)(1); + * // => [1, 2, 3] * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * curried(1, 2, 3); + * // => [1, 2, 3] * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] */ - var at = flatRest(baseAt); - - /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. * @example * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); * - * var circle = new Circle; - * circle instanceof Circle; - * // => true + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); * - * circle instanceof Shape; - * // => true + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + result = wait - timeSinceLastCall; + + return maxing ? nativeMin(result, maxWait - timeSinceLastInvoke) : result; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; } /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. * @example * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. */ - var defaults = baseRest(function(args) { - args.push(undefined, customDefaultsAssignIn); - return apply(assignInWith, undefined, args); + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); }); /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. - * - * **Note:** This method mutates `object`. + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. * * @static * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. * @example * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); }); /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. + * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. * @example * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) - * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); } /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. * @example * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] * - * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' + * values(other); + * // => [3, 4] * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' + * object.a = 2; + * values(object); + * // => [1, 2] * - * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; } + // Expose `MapCache`. + memoize.Cache = MapCache; + /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. * * @static * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; + * function isEven(n) { + * return n % 2 == 0; * } * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); + function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; } /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); + function once(func) { + return before(2, func); } /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. + * Creates a function that invokes `func` with its arguments transformed. * * @static + * @since 4.0.0 * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; + * function doubled(n) { + * return n * 2; * } * - * Foo.prototype.c = 3; + * function square(n) { + * return n * n; + * } * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); - } + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; + * function greet(greeting, name) { + * return greeting + ' ' + name; * } * - * Foo.prototype.c = 3; + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); - } + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); /** - * Creates an array of function property names from own enumerable properties - * of `object`. + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. * @example * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); + * function greet(greeting, name) { + * return greeting + ' ' + name; * } * - * Foo.prototype.c = _.constant('c'); + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' * - * _.functions(new Foo); - * // => ['a', 'b'] + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); - } + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. * @example * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); * - * _.functionsIn(new Foo); + * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); } /** - * Checks if `path` is a direct property of `object`. + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. * @example * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); * - * _.has(object, 'a.b'); - * // => true + * say(['fred', 'hello']); + * // => 'fred says hello' * - * _.has(object, ['a', 'b']); - * // => true + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); * - * _.has(other, 'a'); - * // => false + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); } /** - * Checks if `path` is a direct or inherited property of `object`. + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. * @example * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * - * _.hasIn(object, 'a'); - * // => true + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); * - * _.hasIn(object, 'a.b'); - * // => true + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. * - * _.hasIn(object, ['a', 'b']); - * // => true + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example * - * _.hasIn(object, 'b'); - * // => false + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); + function unary(func) { + return ary(func, 1); } /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. * * @static * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * var p = _.wrap(_.escape, function(func, text) { + * return '<p>' + func(text) + '</p>'; + * }); * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } + * p('fred, barney, & pebbles'); + * // => '<p>fred, barney, & pebbles</p>' */ - var invert = createInverter(function(result, value, key) { - result[value] = key; - }, constant(identity)); + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). + * Casts `value` as an array if it's not one. * * @static * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * _.castArray(1); + * // => [1] * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true */ - var invertBy = createInverter(function(result, value, key) { - if (hasOwnProperty.call(result, value)) { - result[value].push(key); - } else { - result[value] = [key]; + function castArray() { + if (!arguments.length) { + return []; } - }, getIteratee); + var value = arguments[0]; + return isArray(value) ? value : [value]; + } /** - * Invokes the method at `path` of `object`. + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep * @example * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * var objects = [{ 'a': 1 }, { 'b': 2 }]; * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true */ - var invoke = baseRest(baseInvoke); + function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG); + } /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } * } * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) + * var el = _.cloneWith(document.body, customizer); * - * _.keys('hi'); - * // => ['0', '1'] + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. + * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * var objects = [{ 'a': 1 }, { 'b': 2 }]; * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). + * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith * @example * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; + function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. * * @static * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; + * var object = { 'a': 1, 'b': 2 }; * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); } /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; + * _.eq(object, object); + * // => true * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); + function eq(value, other) { + return value === other || (value !== value && other !== other); + } /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). - * - * **Note:** This method mutates `object`. + * Checks if `value` is greater than `other`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt * @example * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } + * _.gt(3, 1); + * // => true * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; + * _.gt(3, 3); + * // => false * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } + * _.gt(1, 3); + * // => false */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); + var gt = createRelationalOperation(baseGt); /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. - * - * **Note:** This method is considerably slower than `_.pick`. + * Checks if `value` is greater than or equal to `other`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to omit. - * @returns {Object} Returns the new object. + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * _.gte(3, 1); + * // => true * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); - } - return result; + var gte = createRelationalOperation(function(value, other) { + return value >= other; }); /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). + * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * _.isArguments(function() { return arguments; }()); + * // => true * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } + * _.isArguments([1, 2, 3]); + * // => false */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } + var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); + }; /** - * Creates an object composed of the picked `object` properties. + * Checks if `value` is classified as an `Array` object. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * _.isArray([1, 2, 3]); + * // => true * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); + var isArray = Array.isArray; /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). + * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } + * _.isArrayBuffer(new Array(2)); + * // => false */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 + * _.isArrayLike([1, 2, 3]); + * // => true * - * _.result(object, 'a[0].b.c2'); - * // => 4 + * _.isArrayLike(document.body.children); + * // => true * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' + * _.isArrayLike('abc'); + * // => true * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' + * _.isArrayLike(_.noop); + * // => false */ - function result(object, path, defaultValue) { - path = castPath(path, object); - - var index = -1, - length = path.length; - - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } - while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; - } - object = isFunction(value) ? value.call(object) : value; - } - return object; + function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); } /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. - * - * **Note:** This method mutates `object`. + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. * * @static * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * _.isArrayLikeObject([1, 2, 3]); + * // => true * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 + * _.isArrayLikeObject(document.body.children); + * // => true * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); } /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. + * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * - * var object = {}; + * _.isBoolean(false); + * // => true * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } + * _.isBoolean(null); + * // => false */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); + function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); } /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. + * Checks if `value` is a buffer. * * @static * @memberOf _ - * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * _.isBuffer(new Buffer(2)); + * // => true * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + * _.isBuffer(new Uint8Array(2)); + * // => false */ - var toPairs = createToPairs(keys); + var isBuffer = nativeIsBuffer || stubFalse; /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. + * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ - * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * _.isDate(new Date); + * // => true * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + * _.isDate('Mon April 23 2012'); + * // => false */ - var toPairsIn = createToPairs(keysIn); + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. + * Checks if `value` is likely a DOM element. * * @static * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] + * _.isElement(document.body); + * // => true * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } + * _.isElement('<body>'); + * // => false */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** - * Removes the property at `path` of `object`. + * Checks if `value` is an empty object, collection, map, or set. * - * **Note:** This method mutates `object`. + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); + * _.isEmpty(null); * // => true * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; + * _.isEmpty(true); + * // => true * - * _.unset(object, ['a', '0', 'b', 'c']); + * _.isEmpty(1); * // => true * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); + function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; } /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). + * Performs a deep comparison between two values to determine if they are + * equivalent. * - * **Note:** This method mutates `object`. + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 + * _.isEqual(object, other); + * // => true * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 + * object === other; + * // => false */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); + function isEqual(value, other) { + return baseIsEqual(value, other); } /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * - * var object = {}; + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true */ - function updateWith(object, path, updater, customizer) { + function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) + * _.isError(new Error); + * // => true * - * _.values('hi'); - * // => ['h', 'i'] + * _.isError(Error); + * // => false */ - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. + * Checks if `value` is a finite primitive number. * - * **Note:** Non-object values are coerced to objects. + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * _.isFinite(3); + * // => true * - * Foo.prototype.c = 3; + * _.isFinite(Number.MIN_VALUE); + * // => true * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); + function isFinite(value) { + return typeof value == 'number' && nativeIsFinite(value); } - /*------------------------------------------------------------------------*/ - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. + * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * - * _.clamp(-10, -5, 5); - * // => -5 + * _.isFunction(_); + * // => true * - * _.clamp(10, -5, 5); - * // => 5 + * _.isFunction(/abc/); + * // => false */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; + function isFunction(value) { + if (!isObject(value)) { + return false; } - return baseClamp(toNumber(number), lower, upper); + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); + * _.isInteger(3); * // => true * - * _.inRange(4, 2); + * _.isInteger(Number.MIN_VALUE); * // => false * - * _.inRange(2, 2); + * _.isInteger(Infinity); * // => false * - * _.inRange(1.2, 2); - * // => true - * - * _.inRange(5.2, 4); + * _.isInteger('3'); * // => false - * - * _.inRange(-3, -2, -6); - * // => true */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); } /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. + * Checks if `value` is a valid array-like length. * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * - * _.random(0, 5); - * // => an integer between 0 and 5 + * _.isLength(3); + * // => true * - * _.random(5); - * // => also an integer between 0 and 5 + * _.isLength(Number.MIN_VALUE); + * // => false * - * _.random(5, true); - * // => a floating-point number between 0 and 5 + * _.isLength(Infinity); + * // => false * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 + * _.isLength('3'); + * // => false */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); + function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } - /*------------------------------------------------------------------------*/ - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * - * _.camelCase('Foo Bar'); - * // => 'fooBar' + * _.isObject({}); + * // => true * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' + * _.isObject([1, 2, 3]); + * // => true * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); + function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); + } /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * - * _.capitalize('FRED'); - * // => 'Fred' + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); + function isObjectLike(value) { + return value != null && typeof value == 'object'; } /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * - * _.deburr('déjà vu'); - * // => 'deja vu' + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** - * Checks if `string` ends with the given target string. + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * - * _.endsWith('abc', 'c'); + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); * // => true * - * _.endsWith('abc', 'b'); + * _.isMatch(object, { 'b': 1 }); * // => false - * - * _.endsWith('abc', 'b', 2); - * // => true */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); } /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. * * @static - * @since 0.1.0 * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; + function isNaN(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; } /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. * @example * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); } /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * Checks if `value` is `null`. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' + * _.isNull(null); + * // => true * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' + * _.isNull(void 0); + * // => false */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); + function isNull(value) { + return value === null; + } /** - * Converts `string`, as space separated words, to lower case. + * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' + * _.isNil(null); + * // => true * - * _.lowerCase('fooBar'); - * // => 'foo bar' + * _.isNil(void 0); + * // => true * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' + * _.isNil(NaN); + * // => false */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); + function isNil(value) { + return value == null; + } /** - * Converts the first character of `string` to lower case. + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * - * _.lowerFirst('Fred'); - * // => 'fred' + * _.isNumber(3); + * // => true * - * _.lowerFirst('FRED'); - * // => 'fRED' + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false */ - var lowerFirst = createCaseFirst('toLowerCase'); + function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); + } /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * - * _.pad('abc', 8); - * // => ' abc ' + * function Foo() { + * this.a = 1; + * } * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' + * _.isPlainObject(new Foo); + * // => false * - * _.pad('abc', 3); - * // => 'abc' + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; } /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' + * _.isRegExp(/abc/); + * // => true * - * _.padEnd('abc', 3); - * // => 'abc' + * _.isRegExp('/abc/'); + * // => false */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; - } + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * - * _.padStart('abc', 6); - * // => ' abc' + * _.isSafeInteger(3); + * // => true * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' + * _.isSafeInteger(Number.MIN_VALUE); + * // => false * - * _.padStart('abc', 3); - * // => 'abc' + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * - * _.parseInt('08'); - * // => 8 + * _.isSet(new Set); + * // => true * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] + * _.isSet(new WeakSet); + * // => false */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** - * Repeats the given string `n` times. + * Checks if `value` is classified as a `String` primitive or object. * * @static + * @since 0.1.0 * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' + * _.isString('abc'); + * // => true * - * _.repeat('abc', 0); - * // => '' + * _.isString(1); + * // => false */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); + function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). + * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' + * _.isTypedArray(new Uint8Array); + * // => true * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' + * _.isTypedArray([]); + * // => false */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); - }); + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). + * Checks if `value` is `undefined`. * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false */ - function split(string, separator, limit) { - if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { - separator = limit = undefined; - } - limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && ( - typeof separator == 'string' || - (separator != null && !isRegExp(separator)) - )) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); + function isUndefined(value) { + return value === undefined; } /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' + * _.isWeakMap(new WeakMap); + * // => true * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' + * _.isWeakMap(new Map); + * // => false */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } /** - * Checks if `string` starts with the given target string. + * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, - * else `false`. + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * - * _.startsWith('abc', 'a'); + * _.isWeakSet(new WeakSet); * // => true * - * _.startsWith('abc', 'b'); + * _.isWeakSet(new Set); * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true */ - function startsWith(string, target, position) { - string = toString(string); - position = position == null - ? 0 - : baseClamp(toInteger(position), 0, string.length); - - target = baseToString(target); - return string.slice(position, position + target.length) == target; + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * Checks if `value` is less than `other`. * * @static - * @since 0.1.0 * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt * @example * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<b><%- value %></b>'); - * compiled({ 'value': '<script>' }); - * // => '<b><script></b>' - * - * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. - * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); - * compiled({ 'users': ['fred', 'barney'] }); - * // => '<li>fred</li><li>barney</li>' - * - * // Use the internal `print` function in "evaluate" delimiters. - * var compiled = _.template('<% print("hello " + user); %>!'); - * compiled({ 'user': 'barney' }); - * // => 'hello barney!' - * - * // Use the ES template literal delimiter as an "interpolate" delimiter. - * // Disable support by replacing the "interpolate" delimiter. - * var compiled = _.template('hello ${ user }!'); - * compiled({ 'user': 'pebbles' }); - * // => 'hello pebbles!' - * - * // Use backslashes to treat delimiters as plain text. - * var compiled = _.template('<%= "\\<%- value %\\>" %>'); - * compiled({ 'value': 'ignored' }); - * // => '<%- value %>' - * - * // Use the `imports` option to import `jQuery` as `jq`. - * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; - * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); - * compiled({ 'users': ['fred', 'barney'] }); - * // => '<li>fred</li><li>barney</li>' - * - * // Use the `sourceURL` option to specify a custom sourceURL for the template. - * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); - * compiled(data); - * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. - * - * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. - * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); - * compiled.source; - * // => function(data) { - * // var __t, __p = ''; - * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; - * // return __p; - * // } + * _.lt(1, 3); + * // => true * - * // Use custom template delimiters. - * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; - * var compiled = _.template('hello {{ user }}!'); - * compiled({ 'user': 'mustache' }); - * // => 'hello mustache!' + * _.lt(3, 3); + * // => false * - * // Use the `source` property to inline compiled templates for meaningful - * // line numbers in error messages and stack traces. - * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ - * var JST = {\ - * "main": ' + _.template(mainText).source + '\ - * };\ - * '); + * _.lt(3, 1); + * // => false */ - function template(string, options, guard) { - // Based on John Resig's `tmpl` implementation - // (http://ejohn.org/blog/javascript-micro-templating/) - // and Laura Doktorova's doT.js (https://github.com/olado/doT). - var settings = lodash.templateSettings; - - if (guard && isIterateeCall(string, options, guard)) { - options = undefined; - } - string = toString(string); - options = assignInWith({}, options, settings, customDefaultsAssignIn); - - var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), - importsKeys = keys(imports), - importsValues = baseValues(imports, importsKeys); - - var isEscaping, - isEvaluating, - index = 0, - interpolate = options.interpolate || reNoMatch, - source = "__p += '"; - - // Compile the regexp to match each delimiter. - var reDelimiters = RegExp( - (options.escape || reNoMatch).source + '|' + - interpolate.source + '|' + - (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + - (options.evaluate || reNoMatch).source + '|$' - , 'g'); - - // Use a sourceURL for easier debugging. - var sourceURL = '//# sourceURL=' + - ('sourceURL' in options - ? options.sourceURL - : ('lodash.templateSources[' + (++templateCounter) + ']') - ) + '\n'; - - string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { - interpolateValue || (interpolateValue = esTemplateValue); - - // Escape characters that can't be included in string literals. - source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); - - // Replace delimiters with snippets. - if (escapeValue) { - isEscaping = true; - source += "' +\n__e(" + escapeValue + ") +\n'"; - } - if (evaluateValue) { - isEvaluating = true; - source += "';\n" + evaluateValue + ";\n__p += '"; - } - if (interpolateValue) { - source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; - } - index = offset + match.length; - - // The JS engine embedded in Adobe products needs `match` returned in - // order to produce the correct `offset` value. - return match; - }); - - source += "';\n"; - - // If `variable` is not specified wrap a with-statement around the generated - // code to add the data object to the top of the scope chain. - var variable = options.variable; - if (!variable) { - source = 'with (obj) {\n' + source + '\n}\n'; - } - // Cleanup code by stripping empty strings. - source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) - .replace(reEmptyStringMiddle, '$1') - .replace(reEmptyStringTrailing, '$1;'); - - // Frame code as the function body. - source = 'function(' + (variable || 'obj') + ') {\n' + - (variable - ? '' - : 'obj || (obj = {});\n' - ) + - "var __t, __p = ''" + - (isEscaping - ? ', __e = _.escape' - : '' - ) + - (isEvaluating - ? ', __j = Array.prototype.join;\n' + - "function print() { __p += __j.call(arguments, '') }\n" - : ';\n' - ) + - source + - 'return __p\n}'; - - var result = attempt(function() { - return Function(importsKeys, sourceURL + 'return ' + source) - .apply(undefined, importsValues); - }); - - // Provide the compiled function's source by its `toString` method or - // the `source` property as a convenience for inlining compiled templates. - result.source = source; - if (isError(result)) { - throw result; - } - return result; - } + var lt = createRelationalOperation(baseLt); /** - * Converts `string`, as a whole, to lower case just like - * [String#toLowerCase](https://mdn.io/toLowerCase). + * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte * @example * - * _.toLower('--Foo-Bar--'); - * // => '--foo-bar--' + * _.lte(1, 3); + * // => true * - * _.toLower('fooBar'); - * // => 'foobar' + * _.lte(3, 3); + * // => true * - * _.toLower('__FOO_BAR__'); - * // => '__foo_bar__' + * _.lte(3, 1); + * // => false */ - function toLower(value) { - return toString(value).toLowerCase(); - } + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); /** - * Converts `string`, as a whole, to upper case just like - * [String#toUpperCase](https://mdn.io/toUpperCase). + * Converts `value` to an array. * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the upper cased string. + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. * @example * - * _.toUpper('--foo-bar--'); - * // => '--FOO-BAR--' + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] * - * _.toUpper('fooBar'); - * // => 'FOOBAR' + * _.toArray('abc'); + * // => ['a', 'b', 'c'] * - * _.toUpper('__foo_bar__'); - * // => '__FOO_BAR__' + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] */ - function toUpper(value) { - return toString(value).toUpperCase(); + function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); } /** - * Removes leading and trailing whitespace or specified characters from `string`. + * Converts `value` to a finite number. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. * @example * - * _.trim(' abc '); - * // => 'abc' + * _.toFinite(3.2); + * // => 3.2 * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 */ - function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; } - if (!string || !(chars = baseToString(chars))) { - return string; + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); + return value === value ? value : 0; } /** - * Removes trailing whitespace or specified characters from `string`. + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. * @example * - * _.trimEnd(' abc '); - * // => ' abc' + * _.toInteger(3.2); + * // => 3 * - * _.trimEnd('-_-abc-_-', '_-'); - * // => '-_-abc' + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 */ - function trimEnd(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrimEnd, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - return castSlice(strSymbols, 0, end).join(''); + return result === result ? (remainder ? result - remainder : result) : 0; } /** - * Removes leading whitespace or specified characters from `string`. + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. * @example * - * _.trimStart(' abc '); - * // => 'abc ' + * _.toLength(3.2); + * // => 3 * - * _.trimStart('-_-abc-_-', '_-'); - * // => 'abc-_-' + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 */ - function trimStart(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrimStart, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - start = charsStartIndex(strSymbols, stringToArray(chars)); - - return castSlice(strSymbols, start).join(''); + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** - * Truncates `string` if it's longer than the given maximum string length. - * The last characters of the truncated string are replaced with the omission - * string which defaults to "...". + * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to truncate. - * @param {Object} [options={}] The options object. - * @param {number} [options.length=30] The maximum string length. - * @param {string} [options.omission='...'] The string to indicate text is omitted. - * @param {RegExp|string} [options.separator] The separator pattern to truncate to. - * @returns {string} Returns the truncated string. + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. * @example * - * _.truncate('hi-diddly-ho there, neighborino'); - * // => 'hi-diddly-ho there, neighbo...' + * _.toNumber(3.2); + * // => 3.2 * - * _.truncate('hi-diddly-ho there, neighborino', { - * 'length': 24, - * 'separator': ' ' - * }); - * // => 'hi-diddly-ho there,...' + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 * - * _.truncate('hi-diddly-ho there, neighborino', { - * 'length': 24, - * 'separator': /,? +/ - * }); - * // => 'hi-diddly-ho there...' + * _.toNumber(Infinity); + * // => Infinity * - * _.truncate('hi-diddly-ho there, neighborino', { - * 'omission': ' [...]' - * }); - * // => 'hi-diddly-ho there, neig [...]' + * _.toNumber('3.2'); + * // => 3.2 */ - function truncate(string, options) { - var length = DEFAULT_TRUNC_LENGTH, - omission = DEFAULT_TRUNC_OMISSION; - - if (isObject(options)) { - var separator = 'separator' in options ? options.separator : separator; - length = 'length' in options ? toInteger(options.length) : length; - omission = 'omission' in options ? baseToString(options.omission) : omission; - } - string = toString(string); - - var strLength = string.length; - if (hasUnicode(string)) { - var strSymbols = stringToArray(string); - strLength = strSymbols.length; - } - if (length >= strLength) { - return string; - } - var end = length - stringSize(omission); - if (end < 1) { - return omission; + function toNumber(value) { + if (typeof value == 'number') { + return value; } - var result = strSymbols - ? castSlice(strSymbols, 0, end).join('') - : string.slice(0, end); - - if (separator === undefined) { - return result + omission; + if (isSymbol(value)) { + return NAN; } - if (strSymbols) { - end += (result.length - end); + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; } - if (isRegExp(separator)) { - if (string.slice(end).search(separator)) { - var match, - substring = result; - - if (!separator.global) { - separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); - } - separator.lastIndex = 0; - while ((match = separator.exec(substring))) { - var newEnd = match.index; - } - result = result.slice(0, newEnd === undefined ? end : newEnd); - } - } else if (string.indexOf(baseToString(separator), end) != end) { - var index = result.lastIndexOf(separator); - if (index > -1) { - result = result.slice(0, index); - } + if (typeof value != 'string') { + return value === 0 ? value : +value; } - return result + omission; + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); } /** - * The inverse of `_.escape`; this method converts the HTML entities - * `&`, `<`, `>`, `"`, and `'` in `string` to - * their corresponding characters. - * - * **Note:** No other HTML entities are unescaped. To unescape additional - * HTML entities use a third-party library like [_he_](https://mths.be/he). + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ - * @since 0.6.0 - * @category String - * @param {string} [string=''] The string to unescape. - * @returns {string} Returns the unescaped string. + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. * @example * - * _.unescape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } */ - function unescape(string) { - string = toString(string); - return (string && reHasEscapedHtml.test(string)) - ? string.replace(reEscapedHtml, unescapeHtmlChar) - : string; + function toPlainObject(value) { + return copyObject(value, keysIn(value)); } /** - * Converts `string`, as space separated words, to upper case. + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the upper cased string. + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. * @example * - * _.upperCase('--foo-bar'); - * // => 'FOO BAR' + * _.toSafeInteger(3.2); + * // => 3 * - * _.upperCase('fooBar'); - * // => 'FOO BAR' + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 * - * _.upperCase('__foo_bar__'); - * // => 'FOO BAR' + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 */ - var upperCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toUpperCase(); - }); + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } /** - * Converts the first character of `string` to upper case. + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. + * @category Lang + * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * - * _.upperFirst('fred'); - * // => 'Fred' - * - * _.upperFirst('FRED'); - * // => 'FRED' - */ - var upperFirst = createCaseFirst('toUpperCase'); - - /** - * Splits `string` into an array of its words. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {RegExp|string} [pattern] The pattern to match words. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the words of `string`. - * @example + * _.toString(null); + * // => '' * - * _.words('fred, barney, & pebbles'); - * // => ['fred', 'barney', 'pebbles'] + * _.toString(-0); + * // => '-0' * - * _.words('fred, barney, & pebbles', /[^, ]+/g); - * // => ['fred', 'barney', '&', 'pebbles'] + * _.toString([1, 2, 3]); + * // => '1,2,3' */ - function words(string, pattern, guard) { - string = toString(string); - pattern = guard ? undefined : pattern; - - if (pattern === undefined) { - return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); - } - return string.match(pattern) || []; + function toString(value) { + return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** - * Attempts to invoke `func`, returning either the result or the caught error - * object. Any additional arguments are provided to `func` when it's invoked. + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ - * @since 3.0.0 - * @category Util - * @param {Function} func The function to attempt. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {*} Returns the `func` result or error object. + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn * @example * - * // Avoid throwing errors for invalid selectors. - * var elements = _.attempt(function(selector) { - * return document.querySelectorAll(selector); - * }, '>_>'); + * function Foo() { + * this.a = 1; + * } * - * if (_.isError(elements)) { - * elements = []; + * function Bar() { + * this.c = 3; * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } */ - var attempt = baseRest(function(func, args) { - try { - return apply(func, undefined, args); - } catch (e) { - return isError(e) ? e : new Error(e); + var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + assignValue(object, key, source[key]); + } } }); /** - * Binds methods of an object to the object itself, overwriting the existing - * method. + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. * - * **Note:** This method doesn't set the "length" property of bound functions. + * **Note:** This method mutates `object`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Util - * @param {Object} object The object to bind and assign the bound methods to. - * @param {...(string|string[])} methodNames The object method names to bind. + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. + * @see _.assign * @example * - * var view = { - * 'label': 'docs', - * 'click': function() { - * console.log('clicked ' + this.label); - * } - * }; + * function Foo() { + * this.a = 1; + * } * - * _.bindAll(view, ['click']); - * jQuery(element).on('click', view.click); - * // => Logs 'clicked docs' when clicked. + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ - var bindAll = flatRest(function(object, methodNames) { - arrayEach(methodNames, function(key) { - key = toKey(key); - baseAssignValue(object, key, bind(object[key], object)); - }); - return object; + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); }); /** - * Creates a function that iterates over `pairs` and invokes the corresponding - * function of the first predicate to return truthy. The predicate-function - * pairs are invoked with the `this` binding and arguments of the created - * function. + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 - * @category Util - * @param {Array} pairs The predicate-function pairs. - * @returns {Function} Returns the new composite function. + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith * @example * - * var func = _.cond([ - * [_.matches({ 'a': 1 }), _.constant('matches A')], - * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], - * [_.stubTrue, _.constant('no match')] - * ]); - * - * func({ 'a': 1, 'b': 2 }); - * // => 'matches A' + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } * - * func({ 'a': 0, 'b': 1 }); - * // => 'matches B' + * var defaults = _.partialRight(_.assignInWith, customizer); * - * func({ 'a': '1', 'b': '2' }); - * // => 'no match' + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } */ - function cond(pairs) { - var length = pairs == null ? 0 : pairs.length, - toIteratee = getIteratee(); - - pairs = !length ? [] : arrayMap(pairs, function(pair) { - if (typeof pair[1] != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return [toIteratee(pair[0]), pair[1]]; - }); - - return baseRest(function(args) { - var index = -1; - while (++index < length) { - var pair = pairs[index]; - if (apply(pair[0], this, args)) { - return apply(pair[1], this, args); - } - } - }); - } + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); /** - * Creates a function that invokes the predicate properties of `source` with - * the corresponding property values of a given object, returning `true` if - * all predicates return truthy, else `false`. + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). * - * **Note:** The created function is equivalent to `_.conformsTo` with - * `source` partially applied. + * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 - * @category Util - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith * @example * - * var objects = [ - * { 'a': 2, 'b': 1 }, - * { 'a': 1, 'b': 2 } - * ]; + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } * - * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); - * // => [{ 'a': 1, 'b': 2 }] + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } */ - function conforms(source) { - return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); - } + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); + }); /** - * Creates a function that returns `value`. + * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. * @example * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * - * console.log(objects[0] === objects[1]); - * // => true + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] */ - function constant(value) { - return function() { - return value; - }; - } + var at = flatRest(baseAt); /** - * Checks `value` to determine whether a default value should be returned in - * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, - * or `undefined`. + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. * * @static * @memberOf _ - * @since 4.14.0 - * @category Util - * @param {*} value The value to check. - * @param {*} defaultValue The default value. - * @returns {*} Returns the resolved value. + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. * @example * - * _.defaultTo(1, 10); - * // => 1 + * function Shape() { + * this.x = 0; + * this.y = 0; + * } * - * _.defaultTo(undefined, 10); - * // => 10 + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true */ - function defaultTo(value, defaultValue) { - return (value == null || value !== value) ? defaultValue : value; + function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); } /** - * Creates a function that returns the result of invoking the given functions - * with the `this` binding of the created function, where each successive - * invocation is supplied the return value of the previous. + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. * * @static + * @since 0.1.0 * @memberOf _ - * @since 3.0.0 - * @category Util - * @param {...(Function|Function[])} [funcs] The functions to invoke. - * @returns {Function} Returns the new composite function. - * @see _.flowRight + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep * @example * - * function square(n) { - * return n * n; - * } - * - * var addSquare = _.flow([_.add, square]); - * addSquare(1, 2); - * // => 9 + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } */ - var flow = createFlow(); + var defaults = baseRest(function(args) { + args.push(undefined, customDefaultsAssignIn); + return apply(assignInWith, undefined, args); + }); /** - * This method is like `_.flow` except that it creates a function that - * invokes the given functions from right to left. + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. * * @static - * @since 3.0.0 * @memberOf _ - * @category Util - * @param {...(Function|Function[])} [funcs] The functions to invoke. - * @returns {Function} Returns the new composite function. - * @see _.flow + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults * @example * - * function square(n) { - * return n * n; - * } - * - * var addSquare = _.flowRight([square, _.add]); - * addSquare(1, 2); - * // => 9 + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } */ - var flowRight = createFlow(true); + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); /** - * This method returns the first argument it receives. + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. * * @static - * @since 0.1.0 * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. * @example * - * var object = { 'a': 1 }; + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; * - * console.log(_.identity(object) === object); - * // => true + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' */ - function identity(value) { - return value; + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** - * Creates a function that invokes `func` with the arguments of the created - * function. If `func` is a property name, the created function returns the - * property value for a given element. If `func` is an array or object, the - * created function returns `true` for elements that contain the equivalent - * source properties, otherwise it returns `false`. + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. * * @static - * @since 4.0.0 * @memberOf _ - * @category Util - * @param {*} [func=_.identity] The value to convert to a callback. - * @returns {Function} Returns the callback. + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. * @example * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. - * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); - * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, _.iteratee(['user', 'fred'])); - * // => [{ 'user': 'fred', 'age': 40 }] + * _.findLastKey(users, ['active', false]); + * // => 'fred' * * // The `_.property` iteratee shorthand. - * _.map(users, _.iteratee('user')); - * // => ['barney', 'fred'] - * - * // Create custom iteratee shorthands. - * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { - * return !_.isRegExp(func) ? iteratee(func) : function(string) { - * return func.test(string); - * }; - * }); - * - * _.filter(['abc', 'def'], /ef/); - * // => ['def'] + * _.findLastKey(users, 'active'); + * // => 'pebbles' */ - function iteratee(func) { - return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** - * Creates a function that performs a partial deep comparison between a given - * object and `source`, returning `true` if the given object has equivalent - * property values, else `false`. - * - * **Note:** The created function is equivalent to `_.isMatch` with `source` - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Util - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight * @example * - * var objects = [ - * { 'a': 1, 'b': 2, 'c': 3 }, - * { 'a': 4, 'b': 5, 'c': 6 } - * ]; + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); - * // => [{ 'a': 4, 'b': 5, 'c': 6 }] + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ - function matches(source) { - return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** - * Creates a function that performs a partial deep comparison between the - * value at `path` of a given object to `srcValue`, returning `true` if the - * object value is equivalent, else `false`. - * - * **Note:** Partial comparisons will match empty array and empty object - * `srcValue` values against any array or object value, respectively. See - * `_.isEqual` for a list of supported value comparisons. + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. * * @static * @memberOf _ - * @since 3.2.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn * @example * - * var objects = [ - * { 'a': 1, 'b': 2, 'c': 3 }, - * { 'a': 4, 'b': 5, 'c': 6 } - * ]; + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.find(objects, _.matchesProperty('a', 4)); - * // => { 'a': 4, 'b': 5, 'c': 6 } + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ - function matchesProperty(path, srcValue) { - return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** - * Creates a function that invokes the method at `path` of a given object. - * Any additional arguments are provided to the invoked method. + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. * * @static * @memberOf _ - * @since 3.7.0 - * @category Util - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {Function} Returns the new invoker function. + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight * @example * - * var objects = [ - * { 'a': { 'b': _.constant(2) } }, - * { 'a': { 'b': _.constant(1) } } - * ]; + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.map(objects, _.method('a.b')); - * // => [2, 1] + * Foo.prototype.c = 3; * - * _.map(objects, _.method(['a', 'b'])); - * // => [2, 1] + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ - var method = baseRest(function(path, args) { - return function(object) { - return baseInvoke(object, path, args); - }; - }); + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } /** - * The opposite of `_.method`; this method creates a function that invokes - * the method at a given path of `object`. Any additional arguments are - * provided to the invoked method. + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. * * @static * @memberOf _ - * @since 3.7.0 - * @category Util - * @param {Object} object The object to query. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {Function} Returns the new invoker function. + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn * @example * - * var array = _.times(3, _.constant), - * object = { 'a': array, 'b': array, 'c': array }; + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.map(['a[2]', 'c[0]'], _.methodOf(object)); - * // => [2, 0] + * Foo.prototype.c = 3; * - * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); - * // => [2, 0] + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ - var methodOf = baseRest(function(object, args) { - return function(path) { - return baseInvoke(object, path, args); - }; - }); + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } /** - * Adds all own enumerable string keyed function properties of a source - * object to the destination object. If `object` is a function, then methods - * are added to its prototype as well. - * - * **Note:** Use `_.runInContext` to create a pristine `lodash` function to - * avoid conflicts caused by modifying the original. + * Creates an array of function property names from own enumerable properties + * of `object`. * * @static * @since 0.1.0 * @memberOf _ - * @category Util - * @param {Function|Object} [object=lodash] The destination object. - * @param {Object} source The object of functions to add. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.chain=true] Specify whether mixins are chainable. - * @returns {Function|Object} Returns `object`. + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn * @example * - * function vowels(string) { - * return _.filter(string, function(v) { - * return /[aeiou]/i.test(v); - * }); + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); * } * - * _.mixin({ 'vowels': vowels }); - * _.vowels('fred'); - * // => ['e'] - * - * _('fred').vowels().value(); - * // => ['e'] + * Foo.prototype.c = _.constant('c'); * - * _.mixin({ 'vowels': vowels }, { 'chain': false }); - * _('fred').vowels(); - * // => ['e'] + * _.functions(new Foo); + * // => ['a', 'b'] */ - function mixin(object, source, options) { - var props = keys(source), - methodNames = baseFunctions(source, props); - - if (options == null && - !(isObject(source) && (methodNames.length || !props.length))) { - options = source; - source = object; - object = this; - methodNames = baseFunctions(source, keys(source)); - } - var chain = !(isObject(options) && 'chain' in options) || !!options.chain, - isFunc = isFunction(object); - - arrayEach(methodNames, function(methodName) { - var func = source[methodName]; - object[methodName] = func; - if (isFunc) { - object.prototype[methodName] = function() { - var chainAll = this.__chain__; - if (chain || chainAll) { - var result = object(this.__wrapped__), - actions = result.__actions__ = copyArray(this.__actions__); - - actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); - result.__chain__ = chainAll; - return result; - } - return func.apply(object, arrayPush([this.value()], arguments)); - }; - } - }); - - return object; + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); } /** - * Reverts the `_` variable to its previous value and returns a reference to - * the `lodash` function. + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Util - * @returns {Function} Returns the `lodash` function. + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions * @example * - * var lodash = _.noConflict(); - */ - function noConflict() { - if (root._ === this) { - root._ = oldDash; - } - return this; - } - - /** - * This method returns `undefined`. + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example + * Foo.prototype.c = _.constant('c'); * - * _.times(2, _.noop); - * // => [undefined, undefined] + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] */ - function noop() { - // No operation performed. + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); } /** - * Creates a function that gets the argument at index `n`. If `n` is negative, - * the nth argument from the end is returned. + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {number} [n=0] The index of the argument to return. - * @returns {Function} Returns the new pass-thru function. + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. * @example * - * var func = _.nthArg(1); - * func('a', 'b', 'c', 'd'); - * // => 'b' + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * - * var func = _.nthArg(-2); - * func('a', 'b', 'c', 'd'); - * // => 'c' + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' */ - function nthArg(n) { - n = toInteger(n); - return baseRest(function(args) { - return baseNth(args, n); - }); + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; } /** - * Creates a function that invokes `iteratees` with the arguments it receives - * and returns their results. + * Checks if `path` is a direct property of `object`. * * @static + * @since 0.1.0 * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to invoke. - * @returns {Function} Returns the new function. + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * - * var func = _.over([Math.max, Math.min]); + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * - * func(1, 2, 3, 4); - * // => [4, 1] + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false */ - var over = createOver(arrayMap); + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } /** - * Creates a function that checks if **all** of the `predicates` return - * truthy when invoked with the arguments it receives. + * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 - * @category Util - * @param {...(Function|Function[])} [predicates=[_.identity]] - * The predicates to check. - * @returns {Function} Returns the new function. + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * - * var func = _.overEvery([Boolean, isFinite]); + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * - * func('1'); + * _.hasIn(object, 'a'); * // => true * - * func(null); - * // => false + * _.hasIn(object, 'a.b'); + * // => true * - * func(NaN); + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); * // => false */ - var overEvery = createOver(arrayEvery); + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } /** - * Creates a function that checks if **any** of the `predicates` return - * truthy when invoked with the arguments it receives. + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. * * @static * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {...(Function|Function[])} [predicates=[_.identity]] - * The predicates to check. - * @returns {Function} Returns the new function. + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. * @example * - * var func = _.overSome([Boolean, isFinite]); - * - * func('1'); - * // => true - * - * func(null); - * // => true + * var object = { 'a': 1, 'b': 2, 'c': 1 }; * - * func(NaN); - * // => false + * _.invert(object); + * // => { '1': 'c', '2': 'b' } */ - var overSome = createOver(arraySome); + var invert = createInverter(function(result, value, key) { + result[value] = key; + }, constant(identity)); /** - * Creates a function that returns the value at `path` of a given object. + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). * * @static * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. * @example * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; + * var object = { 'a': 1, 'b': 2, 'c': 1 }; * - * _.map(objects, _.property('a.b')); - * // => [2, 1] + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } + var invertBy = createInverter(function(result, value, key) { + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); /** - * The opposite of `_.property`; this method creates a function that returns - * the value at a given path of `object`. + * Invokes the method at `path` of `object`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Util + * @since 4.0.0 + * @category Object * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. * @example * - * var array = [0, 1, 2], - * object = { 'a': array, 'b': array, 'c': array }; - * - * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); - * // => [2, 0] + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * - * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); - * // => [2, 0] + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] */ - function propertyOf(object) { - return function(path) { - return object == null ? undefined : baseGet(object, path); - }; - } + var invoke = baseRest(baseInvoke); /** - * Creates an array of numbers (positive and/or negative) progressing from - * `start` up to, but not including, `end`. A step of `-1` is used if a negative - * `start` is specified without an `end` or `step`. If `end` is not specified, - * it's set to `start` with `start` then set to `0`. + * Creates an array of the own enumerable property names of `object`. * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. * * @static * @since 0.1.0 * @memberOf _ - * @category Util - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @param {number} [step=1] The value to increment or decrement by. - * @returns {Array} Returns the range of numbers. - * @see _.inRange, _.rangeRight + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. * @example * - * _.range(4); - * // => [0, 1, 2, 3] - * - * _.range(-4); - * // => [0, -1, -2, -3] - * - * _.range(1, 5); - * // => [1, 2, 3, 4] - * - * _.range(0, 20, 5); - * // => [0, 5, 10, 15] + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.range(0, -4, -1); - * // => [0, -1, -2, -3] + * Foo.prototype.c = 3; * - * _.range(1, 4, 0); - * // => [1, 1, 1] + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) * - * _.range(0); - * // => [] + * _.keys('hi'); + * // => ['0', '1'] */ - var range = createRange(); + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } /** - * This method is like `_.range` except that it populates values in - * descending order. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Util - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @param {number} [step=1] The value to increment or decrement by. - * @returns {Array} Returns the range of numbers. - * @see _.inRange, _.range - * @example - * - * _.rangeRight(4); - * // => [3, 2, 1, 0] - * - * _.rangeRight(-4); - * // => [-3, -2, -1, 0] - * - * _.rangeRight(1, 5); - * // => [4, 3, 2, 1] - * - * _.rangeRight(0, 20, 5); - * // => [15, 10, 5, 0] - * - * _.rangeRight(0, -4, -1); - * // => [-3, -2, -1, 0] - * - * _.rangeRight(1, 4, 0); - * // => [1, 1, 1] + * Creates an array of the own and inherited enumerable property names of `object`. * - * _.rangeRight(0); - * // => [] - */ - var rangeRight = createRange(true); - - /** - * This method returns a new empty array. + * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. * @example * - * var arrays = _.times(2, _.stubArray); + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * console.log(arrays); - * // => [[], []] + * Foo.prototype.c = 3; * - * console.log(arrays[0] === arrays[1]); - * // => false + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ - function stubArray() { - return []; + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** - * This method returns `false`. + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). * * @static * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues * @example * - * _.times(2, _.stubFalse); - * // => [false, false] + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } */ - function stubFalse() { - return false; + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; } /** - * This method returns a new empty object. + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). * * @static * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Object} Returns the new empty object. + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys * @example * - * var objects = _.times(2, _.stubObject); + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; * - * console.log(objects); - * // => [{}, {}] + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * - * console.log(objects[0] === objects[1]); - * // => false + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ - function stubObject() { - return {}; + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; } /** - * This method returns an empty string. + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {string} Returns the empty string. + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. * @example * - * _.times(2, _.stubString); - * // => ['', ''] + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ - function stubString() { - return ''; - } + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); /** - * This method returns `true`. + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `true`. + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. * @example * - * _.times(2, _.stubTrue); - * // => [true, true] + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } */ - function stubTrue() { - return true; - } + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); /** - * Invokes the iteratee `n` times, returning an array of the results of - * each invocation. The iteratee is invoked with one argument; (index). + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ - * @category Util - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of results. + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. * @example * - * _.times(3, String); - * // => ['0', '1', '2'] + * var object = { 'a': 1, 'b': '2', 'c': 3 }; * - * _.times(4, _.constant(0)); - * // => [0, 0, 0, 0] + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } */ - function times(n, iteratee) { - n = toInteger(n); - if (n < 1 || n > MAX_SAFE_INTEGER) { - return []; + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; } - var index = MAX_ARRAY_LENGTH, - length = nativeMin(n, MAX_ARRAY_LENGTH); - - iteratee = getIteratee(iteratee); - n -= MAX_ARRAY_LENGTH; - - var result = baseTimes(length, iteratee); - while (++index < n) { - iteratee(index); + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); } return result; - } + }); /** - * Converts `value` to a property path array. + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 - * @category Util - * @param {*} value The value to convert. - * @returns {Array} Returns the new property path array. + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. * @example * - * _.toPath('a.b.c'); - * // => ['a', 'b', 'c'] + * var object = { 'a': 1, 'b': '2', 'c': 3 }; * - * _.toPath('a[0].b.c'); - * // => ['a', '0', 'b', 'c'] + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } */ - function toPath(value) { - if (isArray(value)) { - return arrayMap(value, toKey); - } - return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); } /** - * Generates a unique ID. If `prefix` is given, the ID is appended to it. + * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ - * @category Util - * @param {string} [prefix=''] The value to prefix the ID with. - * @returns {string} Returns the unique ID. + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. * @example * - * _.uniqueId('contact_'); - * // => 'contact_104' + * var object = { 'a': 1, 'b': '2', 'c': 3 }; * - * _.uniqueId(); - * // => '105' + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } */ - function uniqueId(prefix) { - var id = ++idCounter; - return toString(prefix) + id; - } - - /*------------------------------------------------------------------------*/ + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); /** - * Adds two numbers. + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ - * @since 3.4.0 - * @category Math - * @param {number} augend The first number in an addition. - * @param {number} addend The second number in an addition. - * @returns {number} Returns the total. + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. * @example * - * _.add(6, 4); - * // => 10 + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } */ - var add = createMathOperation(function(augend, addend) { - return augend + addend; - }, 0); + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } /** - * Computes `number` rounded up to `precision`. + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. * * @static + * @since 0.1.0 * @memberOf _ - * @since 3.10.0 - * @category Math - * @param {number} number The number to round up. - * @param {number} [precision=0] The precision to round up to. - * @returns {number} Returns the rounded up number. + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. * @example * - * _.ceil(4.006); - * // => 5 + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * - * _.ceil(6.004, 2); - * // => 6.01 + * _.result(object, 'a[0].b.c1'); + * // => 3 * - * _.ceil(6040, -2); - * // => 6100 - */ - var ceil = createRound('ceil'); - - /** - * Divide two numbers. + * _.result(object, 'a[0].b.c2'); + * // => 4 * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Math - * @param {number} dividend The first number in a division. - * @param {number} divisor The second number in a division. - * @returns {number} Returns the quotient. - * @example + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' * - * _.divide(6, 4); - * // => 1.5 + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' */ - var divide = createMathOperation(function(dividend, divisor) { - return dividend / divisor; - }, 1); + function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } /** - * Computes `number` rounded down to `precision`. + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 3.10.0 - * @category Math - * @param {number} number The number to round down. - * @param {number} [precision=0] The precision to round down to. - * @returns {number} Returns the rounded down number. + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. * @example * - * _.floor(4.006); - * // => 4 + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * - * _.floor(0.046, 2); - * // => 0.04 + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 * - * _.floor(4060, -2); - * // => 4000 + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 */ - var floor = createRound('floor'); + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } /** - * Computes the maximum value of `array`. If `array` is empty or falsey, - * `undefined` is returned. + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Math - * @param {Array} array The array to iterate over. - * @returns {*} Returns the maximum value. + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. * @example * - * _.max([4, 2, 8, 6]); - * // => 8 + * var object = {}; * - * _.max([]); - * // => undefined + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } */ - function max(array) { - return (array && array.length) - ? baseExtremum(array, identity, baseGt) - : undefined; + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); } /** - * This method is like `_.max` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * the value is ranked. The iteratee is invoked with one argument: (value). + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. * * @static * @memberOf _ * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {*} Returns the maximum value. + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. * @example * - * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.maxBy(objects, function(o) { return o.n; }); - * // => { 'n': 2 } + * Foo.prototype.c = 3; * - * // The `_.property` iteratee shorthand. - * _.maxBy(objects, 'n'); - * // => { 'n': 2 } + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ - function maxBy(array, iteratee) { - return (array && array.length) - ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) - : undefined; - } + var toPairs = createToPairs(keys); /** - * Computes the mean of the values in `array`. + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @returns {number} Returns the mean. + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. * @example * - * _.mean([4, 2, 8, 6]); - * // => 5 + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ - function mean(array) { - return baseMean(array, identity); - } + var toPairsIn = createToPairs(keysIn); /** - * This method is like `_.mean` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the value to be averaged. - * The iteratee is invoked with one argument: (value). + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ - * @since 4.7.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the mean. + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. * @example * - * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; - * - * _.meanBy(objects, function(o) { return o.n; }); - * // => 5 + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] * - * // The `_.property` iteratee shorthand. - * _.meanBy(objects, 'n'); - * // => 5 + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } */ - function meanBy(array, iteratee) { - return baseMean(array, getIteratee(iteratee, 2)); + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; } /** - * Computes the minimum value of `array`. If `array` is empty or falsey, - * `undefined` is returned. + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Math - * @param {Array} array The array to iterate over. - * @returns {*} Returns the minimum value. + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * - * _.min([4, 2, 8, 6]); - * // => 2 + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true * - * _.min([]); - * // => undefined + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; */ - function min(array) { - return (array && array.length) - ? baseExtremum(array, identity, baseLt) - : undefined; + function unset(object, path) { + return object == null ? true : baseUnset(object, path); } /** - * This method is like `_.min` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * the value is ranked. The iteratee is invoked with one argument: (value). + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {*} Returns the minimum value. + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. * @example * - * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * - * _.minBy(objects, function(o) { return o.n; }); - * // => { 'n': 1 } + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 * - * // The `_.property` iteratee shorthand. - * _.minBy(objects, 'n'); - * // => { 'n': 1 } + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 */ - function minBy(array, iteratee) { - return (array && array.length) - ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) - : undefined; + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** - * Multiply two numbers. + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. * * @static * @memberOf _ - * @since 4.7.0 - * @category Math - * @param {number} multiplier The first number in a multiplication. - * @param {number} multiplicand The second number in a multiplication. - * @returns {number} Returns the product. + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. * @example * - * _.multiply(6, 4); - * // => 24 + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } */ - var multiply = createMathOperation(function(multiplier, multiplicand) { - return multiplier * multiplicand; - }, 1); + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } /** - * Computes `number` rounded to `precision`. + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. * * @static + * @since 0.1.0 * @memberOf _ - * @since 3.10.0 - * @category Math - * @param {number} number The number to round. - * @param {number} [precision=0] The precision to round to. - * @returns {number} Returns the rounded number. + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. * @example * - * _.round(4.006); - * // => 4 + * function Foo() { + * this.a = 1; + * this.b = 2; + * } * - * _.round(4.006, 2); - * // => 4.01 + * Foo.prototype.c = 3; * - * _.round(4060, -2); - * // => 4100 + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] */ - var round = createRound('round'); + function values(object) { + return object == null ? [] : baseValues(object, keys(object)); + } /** - * Subtract two numbers. + * Creates an array of the own and inherited enumerable string keyed property + * values of `object`. + * + * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {number} minuend The first number in a subtraction. - * @param {number} subtrahend The second number in a subtraction. - * @returns {number} Returns the difference. + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. * @example * - * _.subtract(6, 4); - * // => 2 + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) */ - var subtract = createMathOperation(function(minuend, subtrahend) { - return minuend - subtrahend; - }, 0); + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ /** - * Computes the sum of the values in `array`. + * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ - * @since 3.4.0 - * @category Math - * @param {Array} array The array to iterate over. - * @returns {number} Returns the sum. + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. * @example * - * _.sum([4, 2, 8, 6]); - * // => 20 + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 */ - function sum(array) { - return (array && array.length) - ? baseSum(array, identity) - : 0; + function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); } /** - * This method is like `_.sum` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the value to be summed. - * The iteratee is invoked with one argument: (value). + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. * * @static * @memberOf _ - * @since 4.0.0 - * @category Math - * @param {Array} array The array to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the sum. + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight * @example * - * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * _.inRange(3, 2, 4); + * // => true * - * _.sumBy(objects, function(o) { return o.n; }); - * // => 20 + * _.inRange(4, 8); + * // => true * - * // The `_.property` iteratee shorthand. - * _.sumBy(objects, 'n'); - * // => 20 + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true */ - function sumBy(array, iteratee) { - return (array && array.length) - ? baseSum(array, getIteratee(iteratee, 2)) - : 0; + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); } - /*------------------------------------------------------------------------*/ - - // Add methods that return wrapped values in chain sequences. - lodash.after = after; - lodash.ary = ary; - lodash.assign = assign; - lodash.assignIn = assignIn; - lodash.assignInWith = assignInWith; - lodash.assignWith = assignWith; - lodash.at = at; - lodash.before = before; - lodash.bind = bind; - lodash.bindAll = bindAll; - lodash.bindKey = bindKey; - lodash.castArray = castArray; - lodash.chain = chain; - lodash.chunk = chunk; - lodash.compact = compact; - lodash.concat = concat; - lodash.cond = cond; - lodash.conforms = conforms; - lodash.constant = constant; - lodash.countBy = countBy; - lodash.create = create; - lodash.curry = curry; - lodash.curryRight = curryRight; - lodash.debounce = debounce; - lodash.defaults = defaults; - lodash.defaultsDeep = defaultsDeep; - lodash.defer = defer; - lodash.delay = delay; - lodash.difference = difference; - lodash.differenceBy = differenceBy; - lodash.differenceWith = differenceWith; - lodash.drop = drop; - lodash.dropRight = dropRight; - lodash.dropRightWhile = dropRightWhile; - lodash.dropWhile = dropWhile; - lodash.fill = fill; - lodash.filter = filter; - lodash.flatMap = flatMap; - lodash.flatMapDeep = flatMapDeep; - lodash.flatMapDepth = flatMapDepth; - lodash.flatten = flatten; - lodash.flattenDeep = flattenDeep; - lodash.flattenDepth = flattenDepth; - lodash.flip = flip; - lodash.flow = flow; - lodash.flowRight = flowRight; - lodash.fromPairs = fromPairs; - lodash.functions = functions; - lodash.functionsIn = functionsIn; - lodash.groupBy = groupBy; - lodash.initial = initial; - lodash.intersection = intersection; - lodash.intersectionBy = intersectionBy; - lodash.intersectionWith = intersectionWith; - lodash.invert = invert; - lodash.invertBy = invertBy; - lodash.invokeMap = invokeMap; - lodash.iteratee = iteratee; - lodash.keyBy = keyBy; - lodash.keys = keys; - lodash.keysIn = keysIn; - lodash.map = map; - lodash.mapKeys = mapKeys; - lodash.mapValues = mapValues; - lodash.matches = matches; - lodash.matchesProperty = matchesProperty; - lodash.memoize = memoize; - lodash.merge = merge; - lodash.mergeWith = mergeWith; - lodash.method = method; - lodash.methodOf = methodOf; - lodash.mixin = mixin; - lodash.negate = negate; - lodash.nthArg = nthArg; - lodash.omit = omit; - lodash.omitBy = omitBy; - lodash.once = once; - lodash.orderBy = orderBy; - lodash.over = over; - lodash.overArgs = overArgs; - lodash.overEvery = overEvery; - lodash.overSome = overSome; - lodash.partial = partial; - lodash.partialRight = partialRight; - lodash.partition = partition; - lodash.pick = pick; - lodash.pickBy = pickBy; - lodash.property = property; - lodash.propertyOf = propertyOf; - lodash.pull = pull; - lodash.pullAll = pullAll; - lodash.pullAllBy = pullAllBy; - lodash.pullAllWith = pullAllWith; - lodash.pullAt = pullAt; - lodash.range = range; - lodash.rangeRight = rangeRight; - lodash.rearg = rearg; - lodash.reject = reject; - lodash.remove = remove; - lodash.rest = rest; - lodash.reverse = reverse; - lodash.sampleSize = sampleSize; - lodash.set = set; - lodash.setWith = setWith; - lodash.shuffle = shuffle; - lodash.slice = slice; - lodash.sortBy = sortBy; - lodash.sortedUniq = sortedUniq; - lodash.sortedUniqBy = sortedUniqBy; - lodash.split = split; - lodash.spread = spread; - lodash.tail = tail; - lodash.take = take; - lodash.takeRight = takeRight; - lodash.takeRightWhile = takeRightWhile; - lodash.takeWhile = takeWhile; - lodash.tap = tap; - lodash.throttle = throttle; - lodash.thru = thru; - lodash.toArray = toArray; - lodash.toPairs = toPairs; - lodash.toPairsIn = toPairsIn; - lodash.toPath = toPath; - lodash.toPlainObject = toPlainObject; - lodash.transform = transform; - lodash.unary = unary; - lodash.union = union; - lodash.unionBy = unionBy; - lodash.unionWith = unionWith; - lodash.uniq = uniq; - lodash.uniqBy = uniqBy; - lodash.uniqWith = uniqWith; - lodash.unset = unset; - lodash.unzip = unzip; - lodash.unzipWith = unzipWith; - lodash.update = update; - lodash.updateWith = updateWith; - lodash.values = values; - lodash.valuesIn = valuesIn; - lodash.without = without; - lodash.words = words; - lodash.wrap = wrap; - lodash.xor = xor; - lodash.xorBy = xorBy; - lodash.xorWith = xorWith; - lodash.zip = zip; - lodash.zipObject = zipObject; - lodash.zipObjectDeep = zipObjectDeep; - lodash.zipWith = zipWith; - - // Add aliases. - lodash.entries = toPairs; - lodash.entriesIn = toPairsIn; - lodash.extend = assignIn; - lodash.extendWith = assignInWith; - - // Add methods to `lodash.prototype`. - mixin(lodash, lodash); - - /*------------------------------------------------------------------------*/ - - // Add methods that return unwrapped values in chain sequences. - lodash.add = add; - lodash.attempt = attempt; - lodash.camelCase = camelCase; - lodash.capitalize = capitalize; - lodash.ceil = ceil; - lodash.clamp = clamp; - lodash.clone = clone; - lodash.cloneDeep = cloneDeep; - lodash.cloneDeepWith = cloneDeepWith; - lodash.cloneWith = cloneWith; - lodash.conformsTo = conformsTo; - lodash.deburr = deburr; - lodash.defaultTo = defaultTo; - lodash.divide = divide; - lodash.endsWith = endsWith; - lodash.eq = eq; - lodash.escape = escape; - lodash.escapeRegExp = escapeRegExp; - lodash.every = every; - lodash.find = find; - lodash.findIndex = findIndex; - lodash.findKey = findKey; - lodash.findLast = findLast; - lodash.findLastIndex = findLastIndex; - lodash.findLastKey = findLastKey; - lodash.floor = floor; - lodash.forEach = forEach; - lodash.forEachRight = forEachRight; - lodash.forIn = forIn; - lodash.forInRight = forInRight; - lodash.forOwn = forOwn; - lodash.forOwnRight = forOwnRight; - lodash.get = get; - lodash.gt = gt; - lodash.gte = gte; - lodash.has = has; - lodash.hasIn = hasIn; - lodash.head = head; - lodash.identity = identity; - lodash.includes = includes; - lodash.indexOf = indexOf; - lodash.inRange = inRange; - lodash.invoke = invoke; - lodash.isArguments = isArguments; - lodash.isArray = isArray; - lodash.isArrayBuffer = isArrayBuffer; - lodash.isArrayLike = isArrayLike; - lodash.isArrayLikeObject = isArrayLikeObject; - lodash.isBoolean = isBoolean; - lodash.isBuffer = isBuffer; - lodash.isDate = isDate; - lodash.isElement = isElement; - lodash.isEmpty = isEmpty; - lodash.isEqual = isEqual; - lodash.isEqualWith = isEqualWith; - lodash.isError = isError; - lodash.isFinite = isFinite; - lodash.isFunction = isFunction; - lodash.isInteger = isInteger; - lodash.isLength = isLength; - lodash.isMap = isMap; - lodash.isMatch = isMatch; - lodash.isMatchWith = isMatchWith; - lodash.isNaN = isNaN; - lodash.isNative = isNative; - lodash.isNil = isNil; - lodash.isNull = isNull; - lodash.isNumber = isNumber; - lodash.isObject = isObject; - lodash.isObjectLike = isObjectLike; - lodash.isPlainObject = isPlainObject; - lodash.isRegExp = isRegExp; - lodash.isSafeInteger = isSafeInteger; - lodash.isSet = isSet; - lodash.isString = isString; - lodash.isSymbol = isSymbol; - lodash.isTypedArray = isTypedArray; - lodash.isUndefined = isUndefined; - lodash.isWeakMap = isWeakMap; - lodash.isWeakSet = isWeakSet; - lodash.join = join; - lodash.kebabCase = kebabCase; - lodash.last = last; - lodash.lastIndexOf = lastIndexOf; - lodash.lowerCase = lowerCase; - lodash.lowerFirst = lowerFirst; - lodash.lt = lt; - lodash.lte = lte; - lodash.max = max; - lodash.maxBy = maxBy; - lodash.mean = mean; - lodash.meanBy = meanBy; - lodash.min = min; - lodash.minBy = minBy; - lodash.stubArray = stubArray; - lodash.stubFalse = stubFalse; - lodash.stubObject = stubObject; - lodash.stubString = stubString; - lodash.stubTrue = stubTrue; - lodash.multiply = multiply; - lodash.nth = nth; - lodash.noConflict = noConflict; - lodash.noop = noop; - lodash.now = now; - lodash.pad = pad; - lodash.padEnd = padEnd; - lodash.padStart = padStart; - lodash.parseInt = parseInt; - lodash.random = random; - lodash.reduce = reduce; - lodash.reduceRight = reduceRight; - lodash.repeat = repeat; - lodash.replace = replace; - lodash.result = result; - lodash.round = round; - lodash.runInContext = runInContext; - lodash.sample = sample; - lodash.size = size; - lodash.snakeCase = snakeCase; - lodash.some = some; - lodash.sortedIndex = sortedIndex; - lodash.sortedIndexBy = sortedIndexBy; - lodash.sortedIndexOf = sortedIndexOf; - lodash.sortedLastIndex = sortedLastIndex; - lodash.sortedLastIndexBy = sortedLastIndexBy; - lodash.sortedLastIndexOf = sortedLastIndexOf; - lodash.startCase = startCase; - lodash.startsWith = startsWith; - lodash.subtract = subtract; - lodash.sum = sum; - lodash.sumBy = sumBy; - lodash.template = template; - lodash.times = times; - lodash.toFinite = toFinite; - lodash.toInteger = toInteger; - lodash.toLength = toLength; - lodash.toLower = toLower; - lodash.toNumber = toNumber; - lodash.toSafeInteger = toSafeInteger; - lodash.toString = toString; - lodash.toUpper = toUpper; - lodash.trim = trim; - lodash.trimEnd = trimEnd; - lodash.trimStart = trimStart; - lodash.truncate = truncate; - lodash.unescape = unescape; - lodash.uniqueId = uniqueId; - lodash.upperCase = upperCase; - lodash.upperFirst = upperFirst; - - // Add aliases. - lodash.each = forEach; - lodash.eachRight = forEachRight; - lodash.first = head; - - mixin(lodash, (function() { - var source = {}; - baseForOwn(lodash, function(func, methodName) { - if (!hasOwnProperty.call(lodash.prototype, methodName)) { - source[methodName] = func; + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; } - }); - return source; - }()), { 'chain': false }); + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } /*------------------------------------------------------------------------*/ /** - * The semantic version number. + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ - * @type {string} + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' */ - lodash.VERSION = VERSION; - - // Assign default placeholders. - arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { - lodash[methodName].placeholder = lodash; + var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); }); - // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. - arrayEach(['drop', 'take'], function(methodName, index) { - LazyWrapper.prototype[methodName] = function(n) { - n = n === undefined ? 1 : nativeMax(toInteger(n), 0); - - var result = (this.__filtered__ && !index) - ? new LazyWrapper(this) - : this.clone(); - - if (result.__filtered__) { - result.__takeCount__ = nativeMin(n, result.__takeCount__); - } else { - result.__views__.push({ - 'size': nativeMin(n, MAX_ARRAY_LENGTH), - 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') - }); - } - return result; - }; + /** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } - LazyWrapper.prototype[methodName + 'Right'] = function(n) { - return this.reverse()[methodName](n).reverse(); - }; - }); + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } - // Add `LazyWrapper` methods that accept an `iteratee` value. - arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { - var type = index + 1, - isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); - LazyWrapper.prototype[methodName] = function(iteratee) { - var result = this.clone(); - result.__iteratees__.push({ - 'iteratee': getIteratee(iteratee, 3), - 'type': type - }); - result.__filtered__ = result.__filtered__ || isFilter; - return result; - }; - }); + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); - // Add `LazyWrapper` methods for `_.head` and `_.last`. - arrayEach(['head', 'last'], function(methodName, index) { - var takeName = 'take' + (index ? 'Right' : ''); + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } - LazyWrapper.prototype[methodName] = function() { - return this[takeName](1).value()[0]; - }; - }); + /** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; + } - // Add `LazyWrapper` methods for `_.initial` and `_.tail`. - arrayEach(['initial', 'tail'], function(methodName, index) { - var dropName = 'drop' + (index ? '' : 'Right'); + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } - LazyWrapper.prototype[methodName] = function() { - return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); - }; + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); }); - LazyWrapper.prototype.compact = function() { - return this.filter(identity); - }; + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); - LazyWrapper.prototype.find = function(predicate) { - return this.filter(predicate).head(); - }; + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); - LazyWrapper.prototype.findLast = function(predicate) { - return this.reverse().find(predicate); - }; + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); - LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { - if (typeof path == 'function') { - return new LazyWrapper(this); + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; } - return this.map(function(value) { - return baseInvoke(value, path, args); - }); - }); - - LazyWrapper.prototype.reject = function(predicate) { - return this.filter(negate(getIteratee(predicate))); - }; + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } - LazyWrapper.prototype.slice = function(start, end) { - start = toInteger(start); + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); - var result = this; - if (result.__filtered__ && (start > 0 || end < 0)) { - return new LazyWrapper(result); - } - if (start < 0) { - result = result.takeRight(-start); - } else if (start) { - result = result.drop(start); - } - if (end !== undefined) { - end = toInteger(end); - result = end < 0 ? result.dropRight(-end) : result.take(end - start); - } - return result; - }; + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } - LazyWrapper.prototype.takeRightWhile = function(predicate) { - return this.reverse().takeWhile(predicate).reverse(); - }; + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); - LazyWrapper.prototype.toArray = function() { - return this.take(MAX_ARRAY_LENGTH); - }; + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } - // Add `LazyWrapper` methods to `lodash.prototype`. - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), - isTaker = /^(?:head|last)$/.test(methodName), - lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], - retUnwrapped = isTaker || /^find/.test(methodName); + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } - if (!lodashFunc) { - return; + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); } - lodash.prototype[methodName] = function() { - var value = this.__wrapped__, - args = isTaker ? [1] : arguments, - isLazy = value instanceof LazyWrapper, - iteratee = args[0], - useLazy = isLazy || isArray(value); + return baseRepeat(toString(string), n); + } - var interceptor = function(value) { - var result = lodashFunc.apply(lodash, arrayPush([value], args)); - return (isTaker && chainAll) ? result[0] : result; - }; + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); - if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { - // Avoid lazy use if the iteratee has a "length" value other than `1`. - isLazy = useLazy = false; - } - var chainAll = this.__chain__, - isHybrid = !!this.__actions__.length, - isUnwrapped = retUnwrapped && !chainAll, - onlyLazy = isLazy && !isHybrid; + return args.length < 3 ? string : string.replace(args[1], args[2]); + } - if (!retUnwrapped && useLazy) { - value = onlyLazy ? value : new LazyWrapper(this); - var result = func.apply(value, args); - result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); - return new LodashWrapper(result, chainAll); - } - if (isUnwrapped && onlyLazy) { - return func.apply(this, args); - } - result = this.thru(interceptor); - return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; - }; + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); }); - // Add `Array` methods to `lodash.prototype`. - arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { - var func = arrayProto[methodName], - chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', - retUnwrapped = /^(?:pop|shift)$/.test(methodName); - - lodash.prototype[methodName] = function() { - var args = arguments; - if (retUnwrapped && !this.__chain__) { - var value = this.value(); - return func.apply(isArray(value) ? value : [], args); + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); } - return this[chainName](function(value) { - return func.apply(isArray(value) ? value : [], args); - }); - }; - }); - - // Map minified method names to their real names. - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var lodashFunc = lodash[methodName]; - if (lodashFunc) { - var key = (lodashFunc.name + ''), - names = realNames[key] || (realNames[key] = []); - - names.push({ 'name': methodName, 'func': lodashFunc }); } - }); - - realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ - 'name': 'wrapper', - 'func': undefined - }]; - - // Add methods to `LazyWrapper`. - LazyWrapper.prototype.clone = lazyClone; - LazyWrapper.prototype.reverse = lazyReverse; - LazyWrapper.prototype.value = lazyValue; - - // Add chain sequence methods to the `lodash` wrapper. - lodash.prototype.at = wrapperAt; - lodash.prototype.chain = wrapperChain; - lodash.prototype.commit = wrapperCommit; - lodash.prototype.next = wrapperNext; - lodash.prototype.plant = wrapperPlant; - lodash.prototype.reverse = wrapperReverse; - lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; - - // Add lazy aliases. - lodash.prototype.first = lodash.prototype.head; - - if (symIterator) { - lodash.prototype[symIterator] = wrapperToIterator; + return string.split(separator, limit); } - return lodash; - }); - - /*--------------------------------------------------------------------------*/ - - // Export lodash. - var _ = runInContext(); - // Some AMD build optimizers, like r.js, check for condition patterns like: - if (true) { - // Expose Lodash on the global object to prevent errors when Lodash is - // loaded by a script tag in the presence of an AMD loader. - // See http://requirejs.org/docs/errors.html#mismatch for more details. - // Use `_.noConflict` to remove Lodash from the global object. - root._ = _; + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); - // Define as an anonymous module so, through path mapping, it can be - // referenced as the "underscore" module. - !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { - return _; - }.call(exports, __webpack_require__, exports, module), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } - // Check for `exports` after `define` in case a build optimizer adds it. - else if (freeModule) { - // Export for Node.js. - (freeModule.exports = _)._ = _; - // Export for CommonJS support. - freeExports._ = _; - } - else { - // Export to the global object. - root._ = _; - } -}.call(this)); + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } -/***/ }), -/* 22 */ -/***/ (function(module, exports) { + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<b><%- value %></b>'); + * compiled({ 'value': '<script>' }); + * // => '<b><script></b>' + * + * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. + * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); + * compiled({ 'users': ['fred', 'barney'] }); + * // => '<li>fred</li><li>barney</li>' + * + * // Use the internal `print` function in "evaluate" delimiters. + * var compiled = _.template('<% print("hello " + user); %>!'); + * compiled({ 'user': 'barney' }); + * // => 'hello barney!' + * + * // Use the ES template literal delimiter as an "interpolate" delimiter. + * // Disable support by replacing the "interpolate" delimiter. + * var compiled = _.template('hello ${ user }!'); + * compiled({ 'user': 'pebbles' }); + * // => 'hello pebbles!' + * + * // Use backslashes to treat delimiters as plain text. + * var compiled = _.template('<%= "\\<%- value %\\>" %>'); + * compiled({ 'value': 'ignored' }); + * // => '<%- value %>' + * + * // Use the `imports` option to import `jQuery` as `jq`. + * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; + * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); + * compiled({ 'users': ['fred', 'barney'] }); + * // => '<li>fred</li><li>barney</li>' + * + * // Use the `sourceURL` option to specify a custom sourceURL for the template. + * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); + * compiled(data); + * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. + * + * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. + * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); + * compiled.source; + * // => function(data) { + * // var __t, __p = ''; + * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; + * // return __p; + * // } + * + * // Use custom template delimiters. + * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; + * var compiled = _.template('hello {{ user }}!'); + * compiled({ 'user': 'mustache' }); + * // => 'hello mustache!' + * + * // Use the `source` property to inline compiled templates for meaningful + * // line numbers in error messages and stack traces. + * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ + * var JST = {\ + * "main": ' + _.template(mainText).source + '\ + * };\ + * '); + */ + function template(string, options, guard) { + // Based on John Resig's `tmpl` implementation + // (http://ejohn.org/blog/javascript-micro-templating/) + // and Laura Doktorova's doT.js (https://github.com/olado/doT). + var settings = lodash.templateSettings; -module.exports = require("assert"); + if (guard && isIterateeCall(string, options, guard)) { + options = undefined; + } + string = toString(string); + options = assignInWith({}, options, settings, customDefaultsAssignIn); -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { + var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), + importsKeys = keys(imports), + importsValues = baseValues(imports, importsKeys); -"use strict"; + var isEscaping, + isEvaluating, + index = 0, + interpolate = options.interpolate || reNoMatch, + source = "__p += '"; + // Compile the regexp to match each delimiter. + var reDelimiters = RegExp( + (options.escape || reNoMatch).source + '|' + + interpolate.source + '|' + + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + + (options.evaluate || reNoMatch).source + '|$' + , 'g'); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.wrapLifecycle = exports.run = exports.install = exports.Install = undefined; + // Use a sourceURL for easier debugging. + var sourceURL = '//# sourceURL=' + + ('sourceURL' in options + ? options.sourceURL + : ('lodash.templateSources[' + (++templateCounter) + ']') + ) + '\n'; -var _asyncToGenerator2; + string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { + interpolateValue || (interpolateValue = esTemplateValue); -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + // Escape characters that can't be included in string literals. + source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); -let install = exports.install = (() => { - var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, lockfile) { - yield wrapLifecycle(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const install = new Install(flags, config, reporter, lockfile); - yield install.init(); - })); - }); + // Replace delimiters with snippets. + if (escapeValue) { + isEscaping = true; + source += "' +\n__e(" + escapeValue + ") +\n'"; + } + if (evaluateValue) { + isEvaluating = true; + source += "';\n" + evaluateValue + ";\n__p += '"; + } + if (interpolateValue) { + source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; + } + index = offset + match.length; - return function install(_x15, _x16, _x17, _x18) { - return _ref9.apply(this, arguments); - }; -})(); + // The JS engine embedded in Adobe products needs `match` returned in + // order to produce the correct `offset` value. + return match; + }); -let run = exports.run = (() => { - var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - let lockfile; - if (flags.lockfile === false) { - lockfile = new (_wrapper || _load_wrapper()).default(); - } else { - lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.lockfileFolder, reporter); - } + source += "';\n"; - if (args.length) { - const exampleArgs = args.slice(); - if (flags.saveDev) { - exampleArgs.push('--dev'); - } - if (flags.savePeer) { - exampleArgs.push('--peer'); - } - if (flags.saveOptional) { - exampleArgs.push('--optional'); - } - if (flags.saveExact) { - exampleArgs.push('--exact'); - } - if (flags.saveTilde) { - exampleArgs.push('--tilde'); - } - let command = 'add'; - if (flags.global) { - command = 'global add'; + // If `variable` is not specified wrap a with-statement around the generated + // code to add the data object to the top of the scope chain. + var variable = options.variable; + if (!variable) { + source = 'with (obj) {\n' + source + '\n}\n'; } - throw new (_errors || _load_errors()).MessageError(reporter.lang('installCommandRenamed', `yarn ${command} ${exampleArgs.join(' ')}`)); - } - - yield install(config, reporter, flags, lockfile); - }); - - return function run(_x19, _x20, _x21, _x22) { - return _ref11.apply(this, arguments); - }; -})(); - -let wrapLifecycle = exports.wrapLifecycle = (() => { - var _ref12 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags, factory) { - yield config.executeLifecycleScript('preinstall'); + // Cleanup code by stripping empty strings. + source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) + .replace(reEmptyStringMiddle, '$1') + .replace(reEmptyStringTrailing, '$1;'); - yield factory(); + // Frame code as the function body. + source = 'function(' + (variable || 'obj') + ') {\n' + + (variable + ? '' + : 'obj || (obj = {});\n' + ) + + "var __t, __p = ''" + + (isEscaping + ? ', __e = _.escape' + : '' + ) + + (isEvaluating + ? ', __j = Array.prototype.join;\n' + + "function print() { __p += __j.call(arguments, '') }\n" + : ';\n' + ) + + source + + 'return __p\n}'; - // npm behaviour, seems kinda funky but yay compatibility - yield config.executeLifecycleScript('install'); - yield config.executeLifecycleScript('postinstall'); + var result = attempt(function() { + return Function(importsKeys, sourceURL + 'return ' + source) + .apply(undefined, importsValues); + }); - if (!config.production) { - if (!config.disablePrepublish) { - yield config.executeLifecycleScript('prepublish'); + // Provide the compiled function's source by its `toString` method or + // the `source` property as a convenience for inlining compiled templates. + result.source = source; + if (isError(result)) { + throw result; } - yield config.executeLifecycleScript('prepare'); + return result; } - }); - - return function wrapLifecycle(_x23, _x24, _x25) { - return _ref12.apply(this, arguments); - }; -})(); - -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; - -var _index; - -function _load_index() { - return _index = _interopRequireDefault(__webpack_require__(129)); -} - -var _errors; -function _load_errors() { - return _errors = __webpack_require__(3); -} + /** + * Converts `string`, as a whole, to lower case just like + * [String#toLowerCase](https://mdn.io/toLowerCase). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.toLower('--Foo-Bar--'); + * // => '--foo-bar--' + * + * _.toLower('fooBar'); + * // => 'foobar' + * + * _.toLower('__FOO_BAR__'); + * // => '__foo_bar__' + */ + function toLower(value) { + return toString(value).toLowerCase(); + } -var _integrityChecker; + /** + * Converts `string`, as a whole, to upper case just like + * [String#toUpperCase](https://mdn.io/toUpperCase). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the upper cased string. + * @example + * + * _.toUpper('--foo-bar--'); + * // => '--FOO-BAR--' + * + * _.toUpper('fooBar'); + * // => 'FOOBAR' + * + * _.toUpper('__foo_bar__'); + * // => '__FOO_BAR__' + */ + function toUpper(value) { + return toString(value).toUpperCase(); + } -function _load_integrityChecker() { - return _integrityChecker = _interopRequireDefault(__webpack_require__(121)); -} + /** + * Removes leading and trailing whitespace or specified characters from `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trim(' abc '); + * // => 'abc' + * + * _.trim('-_-abc-_-', '_-'); + * // => 'abc' + * + * _.map([' foo ', ' bar '], _.trim); + * // => ['foo', 'bar'] + */ + function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim, ''); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), + chrSymbols = stringToArray(chars), + start = charsStartIndex(strSymbols, chrSymbols), + end = charsEndIndex(strSymbols, chrSymbols) + 1; -var _wrapper; + return castSlice(strSymbols, start, end).join(''); + } -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} + /** + * Removes trailing whitespace or specified characters from `string`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trimEnd(' abc '); + * // => ' abc' + * + * _.trimEnd('-_-abc-_-', '_-'); + * // => '-_-abc' + */ + function trimEnd(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrimEnd, ''); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), + end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; -var _stringify; + return castSlice(strSymbols, 0, end).join(''); + } -function _load_stringify() { - return _stringify = _interopRequireDefault(__webpack_require__(81)); -} + /** + * Removes leading whitespace or specified characters from `string`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trimStart(' abc '); + * // => 'abc ' + * + * _.trimStart('-_-abc-_-', '_-'); + * // => 'abc-_-' + */ + function trimStart(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrimStart, ''); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), + start = charsStartIndex(strSymbols, stringToArray(chars)); -var _packageFetcher; + return castSlice(strSymbols, start).join(''); + } -function _load_packageFetcher() { - return _packageFetcher = _interopRequireWildcard(__webpack_require__(200)); -} - -var _packageInstallScripts; + /** + * Truncates `string` if it's longer than the given maximum string length. + * The last characters of the truncated string are replaced with the omission + * string which defaults to "...". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to truncate. + * @param {Object} [options={}] The options object. + * @param {number} [options.length=30] The maximum string length. + * @param {string} [options.omission='...'] The string to indicate text is omitted. + * @param {RegExp|string} [options.separator] The separator pattern to truncate to. + * @returns {string} Returns the truncated string. + * @example + * + * _.truncate('hi-diddly-ho there, neighborino'); + * // => 'hi-diddly-ho there, neighbo...' + * + * _.truncate('hi-diddly-ho there, neighborino', { + * 'length': 24, + * 'separator': ' ' + * }); + * // => 'hi-diddly-ho there,...' + * + * _.truncate('hi-diddly-ho there, neighborino', { + * 'length': 24, + * 'separator': /,? +/ + * }); + * // => 'hi-diddly-ho there...' + * + * _.truncate('hi-diddly-ho there, neighborino', { + * 'omission': ' [...]' + * }); + * // => 'hi-diddly-ho there, neig [...]' + */ + function truncate(string, options) { + var length = DEFAULT_TRUNC_LENGTH, + omission = DEFAULT_TRUNC_OMISSION; -function _load_packageInstallScripts() { - return _packageInstallScripts = _interopRequireDefault(__webpack_require__(361)); -} + if (isObject(options)) { + var separator = 'separator' in options ? options.separator : separator; + length = 'length' in options ? toInteger(options.length) : length; + omission = 'omission' in options ? baseToString(options.omission) : omission; + } + string = toString(string); -var _packageCompatibility; + var strLength = string.length; + if (hasUnicode(string)) { + var strSymbols = stringToArray(string); + strLength = strSymbols.length; + } + if (length >= strLength) { + return string; + } + var end = length - stringSize(omission); + if (end < 1) { + return omission; + } + var result = strSymbols + ? castSlice(strSymbols, 0, end).join('') + : string.slice(0, end); -function _load_packageCompatibility() { - return _packageCompatibility = _interopRequireWildcard(__webpack_require__(199)); -} + if (separator === undefined) { + return result + omission; + } + if (strSymbols) { + end += (result.length - end); + } + if (isRegExp(separator)) { + if (string.slice(end).search(separator)) { + var match, + substring = result; -var _packageResolver; + if (!separator.global) { + separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); + } + separator.lastIndex = 0; + while ((match = separator.exec(substring))) { + var newEnd = match.index; + } + result = result.slice(0, newEnd === undefined ? end : newEnd); + } + } else if (string.indexOf(baseToString(separator), end) != end) { + var index = result.lastIndexOf(separator); + if (index > -1) { + result = result.slice(0, index); + } + } + return result + omission; + } -function _load_packageResolver() { - return _packageResolver = _interopRequireDefault(__webpack_require__(201)); -} + /** + * The inverse of `_.escape`; this method converts the HTML entities + * `&`, `<`, `>`, `"`, and `'` in `string` to + * their corresponding characters. + * + * **Note:** No other HTML entities are unescaped. To unescape additional + * HTML entities use a third-party library like [_he_](https://mths.be/he). + * + * @static + * @memberOf _ + * @since 0.6.0 + * @category String + * @param {string} [string=''] The string to unescape. + * @returns {string} Returns the unescaped string. + * @example + * + * _.unescape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ + function unescape(string) { + string = toString(string); + return (string && reHasEscapedHtml.test(string)) + ? string.replace(reEscapedHtml, unescapeHtmlChar) + : string; + } -var _packageLinker; + /** + * Converts `string`, as space separated words, to upper case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the upper cased string. + * @example + * + * _.upperCase('--foo-bar'); + * // => 'FOO BAR' + * + * _.upperCase('fooBar'); + * // => 'FOO BAR' + * + * _.upperCase('__foo_bar__'); + * // => 'FOO BAR' + */ + var upperCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toUpperCase(); + }); -function _load_packageLinker() { - return _packageLinker = _interopRequireDefault(__webpack_require__(122)); -} + /** + * Converts the first character of `string` to upper case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.upperFirst('fred'); + * // => 'Fred' + * + * _.upperFirst('FRED'); + * // => 'FRED' + */ + var upperFirst = createCaseFirst('toUpperCase'); -var _packageRequest; + /** + * Splits `string` into an array of its words. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {RegExp|string} [pattern] The pattern to match words. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the words of `string`. + * @example + * + * _.words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * _.words('fred, barney, & pebbles', /[^, ]+/g); + * // => ['fred', 'barney', '&', 'pebbles'] + */ + function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined : pattern; -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); -} + if (pattern === undefined) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; + } -var _index2; + /*------------------------------------------------------------------------*/ -function _load_index2() { - return _index2 = __webpack_require__(24); -} + /** + * Attempts to invoke `func`, returning either the result or the caught error + * object. Any additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Function} func The function to attempt. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {*} Returns the `func` result or error object. + * @example + * + * // Avoid throwing errors for invalid selectors. + * var elements = _.attempt(function(selector) { + * return document.querySelectorAll(selector); + * }, '>_>'); + * + * if (_.isError(elements)) { + * elements = []; + * } + */ + var attempt = baseRest(function(func, args) { + try { + return apply(func, undefined, args); + } catch (e) { + return isError(e) ? e : new Error(e); + } + }); -var _clean; + /** + * Binds methods of an object to the object itself, overwriting the existing + * method. + * + * **Note:** This method doesn't set the "length" property of bound functions. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} methodNames The object method names to bind. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'click': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view, ['click']); + * jQuery(element).on('click', view.click); + * // => Logs 'clicked docs' when clicked. + */ + var bindAll = flatRest(function(object, methodNames) { + arrayEach(methodNames, function(key) { + key = toKey(key); + baseAssignValue(object, key, bind(object[key], object)); + }); + return object; + }); -function _load_clean() { - return _clean = __webpack_require__(189); -} + /** + * Creates a function that iterates over `pairs` and invokes the corresponding + * function of the first predicate to return truthy. The predicate-function + * pairs are invoked with the `this` binding and arguments of the created + * function. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Array} pairs The predicate-function pairs. + * @returns {Function} Returns the new composite function. + * @example + * + * var func = _.cond([ + * [_.matches({ 'a': 1 }), _.constant('matches A')], + * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], + * [_.stubTrue, _.constant('no match')] + * ]); + * + * func({ 'a': 1, 'b': 2 }); + * // => 'matches A' + * + * func({ 'a': 0, 'b': 1 }); + * // => 'matches B' + * + * func({ 'a': '1', 'b': '2' }); + * // => 'no match' + */ + function cond(pairs) { + var length = pairs == null ? 0 : pairs.length, + toIteratee = getIteratee(); -var _constants; + pairs = !length ? [] : arrayMap(pairs, function(pair) { + if (typeof pair[1] != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return [toIteratee(pair[0]), pair[1]]; + }); -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + return baseRest(function(args) { + var index = -1; + while (++index < length) { + var pair = pairs[index]; + if (apply(pair[0], this, args)) { + return apply(pair[1], this, args); + } + } + }); + } -var _fs; + /** + * Creates a function that invokes the predicate properties of `source` with + * the corresponding property values of a given object, returning `true` if + * all predicates return truthy, else `false`. + * + * **Note:** The created function is equivalent to `_.conformsTo` with + * `source` partially applied. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 2, 'b': 1 }, + * { 'a': 1, 'b': 2 } + * ]; + * + * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); + * // => [{ 'a': 1, 'b': 2 }] + */ + function conforms(source) { + return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + /** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ + function constant(value) { + return function() { + return value; + }; + } -var _map; + /** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Util + * @param {*} value The value to check. + * @param {*} defaultValue The default value. + * @returns {*} Returns the resolved value. + * @example + * + * _.defaultTo(1, 10); + * // => 1 + * + * _.defaultTo(undefined, 10); + * // => 10 + */ + function defaultTo(value, defaultValue) { + return (value == null || value !== value) ? defaultValue : value; + } -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); -} + /** + * Creates a function that returns the result of invoking the given functions + * with the `this` binding of the created function, where each successive + * invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flowRight + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow([_.add, square]); + * addSquare(1, 2); + * // => 9 + */ + var flow = createFlow(); -var _yarnVersion; + /** + * This method is like `_.flow` except that it creates a function that + * invokes the given functions from right to left. + * + * @static + * @since 3.0.0 + * @memberOf _ + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flow + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight([square, _.add]); + * addSquare(1, 2); + * // => 9 + */ + var flowRight = createFlow(true); -function _load_yarnVersion() { - return _yarnVersion = __webpack_require__(65); -} + /** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ + function identity(value) { + return value; + } -var _workspaceLayout; + /** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ + function iteratee(func) { + return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); + } -function _load_workspaceLayout() { - return _workspaceLayout = _interopRequireDefault(__webpack_require__(66)); -} - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const emoji = __webpack_require__(246); -const invariant = __webpack_require__(5); -const isCI = __webpack_require__(153); -const path = __webpack_require__(1); -const semver = __webpack_require__(27); -const uuid = __webpack_require__(58); - -const ONE_DAY = 1000 * 60 * 60 * 24; - -/** - * Try and detect the installation method for Yarn and provide a command to update it with. - */ - -function getUpdateCommand(installationMethod) { - if (installationMethod === 'tar') { - return `curl -o- -L ${(_constants || _load_constants()).YARN_INSTALLER_SH} | bash`; - } - - if (installationMethod === 'homebrew') { - return 'brew upgrade yarn'; - } - - if (installationMethod === 'deb') { - return 'sudo apt-get update && sudo apt-get install yarn'; - } - - if (installationMethod === 'rpm') { - return 'sudo yum install yarn'; - } - - if (installationMethod === 'npm') { - return 'npm upgrade --global yarn'; - } - - if (installationMethod === 'chocolatey') { - return 'choco upgrade yarn'; - } - - if (installationMethod === 'apk') { - return 'apk update && apk add -u yarn'; - } - - return null; -} - -function getUpdateInstaller(installationMethod) { - // Windows - if (installationMethod === 'msi') { - return (_constants || _load_constants()).YARN_INSTALLER_MSI; - } - - return null; -} - -function normalizeFlags(config, rawFlags) { - const flags = { - // install - har: !!rawFlags.har, - ignorePlatform: !!rawFlags.ignorePlatform, - ignoreEngines: !!rawFlags.ignoreEngines, - ignoreScripts: !!rawFlags.ignoreScripts, - ignoreOptional: !!rawFlags.ignoreOptional, - force: !!rawFlags.force, - flat: !!rawFlags.flat, - lockfile: rawFlags.lockfile !== false, - pureLockfile: !!rawFlags.pureLockfile, - skipIntegrityCheck: !!rawFlags.skipIntegrityCheck, - frozenLockfile: !!rawFlags.frozenLockfile, - linkDuplicates: !!rawFlags.linkDuplicates, - checkFiles: !!rawFlags.checkFiles, - - // add - peer: !!rawFlags.peer, - dev: !!rawFlags.dev, - optional: !!rawFlags.optional, - exact: !!rawFlags.exact, - tilde: !!rawFlags.tilde - }; - - if (config.getOption('ignore-scripts')) { - flags.ignoreScripts = true; - } - - if (config.getOption('ignore-platform')) { - flags.ignorePlatform = true; - } - - if (config.getOption('ignore-engines')) { - flags.ignoreEngines = true; - } - - if (config.getOption('ignore-optional')) { - flags.ignoreOptional = true; - } - - if (config.getOption('force')) { - flags.force = true; - } - - return flags; -} - -class Install { - constructor(flags, config, reporter, lockfile) { - this.rootManifestRegistries = []; - this.rootPatternsToOrigin = (0, (_map || _load_map()).default)(); - this.resolutions = (0, (_map || _load_map()).default)(); - this.lockfile = lockfile; - this.reporter = reporter; - this.config = config; - this.flags = normalizeFlags(config, flags); - - this.resolver = new (_packageResolver || _load_packageResolver()).default(config, lockfile); - this.integrityChecker = new (_integrityChecker || _load_integrityChecker()).default(config); - this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver); - this.scripts = new (_packageInstallScripts || _load_packageInstallScripts()).default(config, this.resolver, this.flags.force); - } - - /** - * Create a list of dependency requests from the current directories manifests. - */ + /** + * Creates a function that performs a partial deep comparison between a given + * object and `source`, returning `true` if the given object has equivalent + * property values, else `false`. + * + * **Note:** The created function is equivalent to `_.isMatch` with `source` + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); + * // => [{ 'a': 4, 'b': 5, 'c': 6 }] + */ + function matches(source) { + return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); + } - fetchRequestFromCwd() { - var _this = this; + /** + * Creates a function that performs a partial deep comparison between the + * value at `path` of a given object to `srcValue`, returning `true` if the + * object value is equivalent, else `false`. + * + * **Note:** Partial comparisons will match empty array and empty object + * `srcValue` values against any array or object value, respectively. See + * `_.isEqual` for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.find(objects, _.matchesProperty('a', 4)); + * // => { 'a': 4, 'b': 5, 'c': 6 } + */ + function matchesProperty(path, srcValue) { + return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); + } - let excludePatterns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - let ignoreUnusedPatterns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const patterns = []; - const deps = []; - const manifest = {}; + /** + * Creates a function that invokes the method at `path` of a given object. + * Any additional arguments are provided to the invoked method. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Util + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Function} Returns the new invoker function. + * @example + * + * var objects = [ + * { 'a': { 'b': _.constant(2) } }, + * { 'a': { 'b': _.constant(1) } } + * ]; + * + * _.map(objects, _.method('a.b')); + * // => [2, 1] + * + * _.map(objects, _.method(['a', 'b'])); + * // => [2, 1] + */ + var method = baseRest(function(path, args) { + return function(object) { + return baseInvoke(object, path, args); + }; + }); - const ignorePatterns = []; - const usedPatterns = []; - let workspaceLayout; + /** + * The opposite of `_.method`; this method creates a function that invokes + * the method at a given path of `object`. Any additional arguments are + * provided to the invoked method. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Util + * @param {Object} object The object to query. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Function} Returns the new invoker function. + * @example + * + * var array = _.times(3, _.constant), + * object = { 'a': array, 'b': array, 'c': array }; + * + * _.map(['a[2]', 'c[0]'], _.methodOf(object)); + * // => [2, 0] + * + * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); + * // => [2, 0] + */ + var methodOf = baseRest(function(object, args) { + return function(path) { + return baseInvoke(object, path, args); + }; + }); - // exclude package names that are in install args - const excludeNames = []; - for (const pattern of excludePatterns) { - // can't extract a package name from this - if ((_packageRequest || _load_packageRequest()).default.getExoticResolver(pattern)) { - continue; - } + /** + * Adds all own enumerable string keyed function properties of a source + * object to the destination object. If `object` is a function, then methods + * are added to its prototype as well. + * + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Function|Object} [object=lodash] The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.chain=true] Specify whether mixins are chainable. + * @returns {Function|Object} Returns `object`. + * @example + * + * function vowels(string) { + * return _.filter(string, function(v) { + * return /[aeiou]/i.test(v); + * }); + * } + * + * _.mixin({ 'vowels': vowels }); + * _.vowels('fred'); + * // => ['e'] + * + * _('fred').vowels().value(); + * // => ['e'] + * + * _.mixin({ 'vowels': vowels }, { 'chain': false }); + * _('fred').vowels(); + * // => ['e'] + */ + function mixin(object, source, options) { + var props = keys(source), + methodNames = baseFunctions(source, props); - // extract the name - const parts = (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern); - excludeNames.push(parts.name); + if (options == null && + !(isObject(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys(source)); } + var chain = !(isObject(options) && 'chain' in options) || !!options.chain, + isFunc = isFunction(object); - for (const registry of Object.keys((_index2 || _load_index2()).registries)) { - const filename = (_index2 || _load_index2()).registries[registry].filename; - - const loc = path.join(_this.config.cwd, filename); - if (!(yield (_fs || _load_fs()).exists(loc))) { - continue; - } - - _this.rootManifestRegistries.push(registry); - const projectManifestJson = yield _this.config.readJson(loc); - yield (0, (_index || _load_index()).default)(projectManifestJson, _this.config.cwd, _this.config, true); - - Object.assign(_this.resolutions, projectManifestJson.resolutions); - Object.assign(manifest, projectManifestJson); - - const pushDeps = function (depType, manifest, _ref, isUsed) { - let hint = _ref.hint, - optional = _ref.optional; - - if (ignoreUnusedPatterns && !isUsed) { - return; - } - // We only take unused dependencies into consideration to get deterministic hoisting. - // Since flat mode doesn't care about hoisting and everything is top level and specified then we can safely - // leave these out. - if (_this.flags.flat && !isUsed) { - return; - } - const depMap = manifest[depType]; - for (const name in depMap) { - if (excludeNames.indexOf(name) >= 0) { - continue; - } - - let pattern = name; - if (!_this.lockfile.getLocked(pattern)) { - // when we use --save we save the dependency to the lockfile with just the name rather than the - // version combo - pattern += '@' + depMap[name]; - } + arrayEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), + actions = result.__actions__ = copyArray(this.__actions__); - // normalization made sure packages are mentioned only once - if (isUsed) { - usedPatterns.push(pattern); - } else { - ignorePatterns.push(pattern); + actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); + result.__chain__ = chainAll; + return result; } - - _this.rootPatternsToOrigin[pattern] = depType; - patterns.push(pattern); - deps.push({ pattern, registry, hint, optional }); - } - }; - - pushDeps('dependencies', projectManifestJson, { hint: null, optional: false }, true); - pushDeps('devDependencies', projectManifestJson, { hint: 'dev', optional: false }, !_this.config.production); - pushDeps('optionalDependencies', projectManifestJson, { hint: 'optional', optional: true }, !_this.flags.ignoreOptional); - - if (_this.config.workspacesEnabled) { - const workspaces = yield _this.config.resolveWorkspaces(path.dirname(loc), projectManifestJson); - workspaceLayout = new (_workspaceLayout || _load_workspaceLayout()).default(workspaces, _this.config); - // add virtual manifest that depends on all workspaces, this way package hoisters and resolvers will work fine - const virtualDependencyManifest = { - _uid: '', - name: `workspace-aggregator-${uuid.v4()}`, - version: '1.0.0', - _registry: 'npm', - _loc: '.', - dependencies: {} + return func.apply(object, arrayPush([this.value()], arguments)); }; - workspaceLayout.virtualManifestName = virtualDependencyManifest.name; - virtualDependencyManifest.dependencies = {}; - for (const workspaceName of Object.keys(workspaces)) { - virtualDependencyManifest.dependencies[workspaceName] = workspaces[workspaceName].manifest.version; - } - const virtualDep = {}; - virtualDep[virtualDependencyManifest.name] = virtualDependencyManifest.version; - workspaces[virtualDependencyManifest.name] = { loc: '', manifest: virtualDependencyManifest }; - - pushDeps('workspaces', { workspaces: virtualDep }, { hint: 'workspaces', optional: false }, true); } + }); - break; - } + return object; + } - // inherit root flat flag - if (manifest.flat) { - _this.flags.flat = true; + /** + * Reverts the `_` variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + if (root._ === this) { + root._ = oldDash; } + return this; + } - return { - requests: deps, - patterns, - manifest, - usedPatterns, - ignorePatterns, - workspaceLayout - }; - })(); - } + /** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ + function noop() { + // No operation performed. + } - /** - * TODO description - */ + /** + * Creates a function that gets the argument at index `n`. If `n` is negative, + * the nth argument from the end is returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {number} [n=0] The index of the argument to return. + * @returns {Function} Returns the new pass-thru function. + * @example + * + * var func = _.nthArg(1); + * func('a', 'b', 'c', 'd'); + * // => 'b' + * + * var func = _.nthArg(-2); + * func('a', 'b', 'c', 'd'); + * // => 'c' + */ + function nthArg(n) { + n = toInteger(n); + return baseRest(function(args) { + return baseNth(args, n); + }); + } - prepareRequests(requests) { - return requests; - } + /** + * Creates a function that invokes `iteratees` with the arguments it receives + * and returns their results. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to invoke. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.over([Math.max, Math.min]); + * + * func(1, 2, 3, 4); + * // => [4, 1] + */ + var over = createOver(arrayMap); - preparePatterns(patterns) { - return patterns; - } + /** + * Creates a function that checks if **all** of the `predicates` return + * truthy when invoked with the arguments it receives. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [predicates=[_.identity]] + * The predicates to check. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.overEvery([Boolean, isFinite]); + * + * func('1'); + * // => true + * + * func(null); + * // => false + * + * func(NaN); + * // => false + */ + var overEvery = createOver(arrayEvery); - bailout(patterns, workspaceLayout) { - var _this2 = this; + /** + * Creates a function that checks if **any** of the `predicates` return + * truthy when invoked with the arguments it receives. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [predicates=[_.identity]] + * The predicates to check. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.overSome([Boolean, isFinite]); + * + * func('1'); + * // => true + * + * func(null); + * // => true + * + * func(NaN); + * // => false + */ + var overSome = createOver(arraySome); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (_this2.flags.skipIntegrityCheck || _this2.flags.force) { - return false; - } - const lockfileCache = _this2.lockfile.cache; - if (!lockfileCache) { - return false; - } - const match = yield _this2.integrityChecker.check(patterns, lockfileCache, _this2.flags, workspaceLayout); - if (_this2.flags.frozenLockfile && match.missingPatterns.length > 0) { - throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('frozenLockfileError')); - } + /** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } - const haveLockfile = yield (_fs || _load_fs()).exists(path.join(_this2.config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME)); + /** + * The opposite of `_.property`; this method creates a function that returns + * the value at a given path of `object`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + * @example + * + * var array = [0, 1, 2], + * object = { 'a': array, 'b': array, 'c': array }; + * + * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); + * // => [2, 0] + * + * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); + * // => [2, 0] + */ + function propertyOf(object) { + return function(path) { + return object == null ? undefined : baseGet(object, path); + }; + } - if (match.integrityMatches && haveLockfile) { - _this2.reporter.success(_this2.reporter.lang('upToDate')); - return true; - } + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to, but not including, `end`. A step of `-1` is used if a negative + * `start` is specified without an `end` or `step`. If `end` is not specified, + * it's set to `start` with `start` then set to `0`. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns the range of numbers. + * @see _.inRange, _.rangeRight + * @example + * + * _.range(4); + * // => [0, 1, 2, 3] + * + * _.range(-4); + * // => [0, -1, -2, -3] + * + * _.range(1, 5); + * // => [1, 2, 3, 4] + * + * _.range(0, 20, 5); + * // => [0, 5, 10, 15] + * + * _.range(0, -4, -1); + * // => [0, -1, -2, -3] + * + * _.range(1, 4, 0); + * // => [1, 1, 1] + * + * _.range(0); + * // => [] + */ + var range = createRange(); - if (!patterns.length && !match.integrityFileMissing) { - _this2.reporter.success(_this2.reporter.lang('nothingToInstall')); - yield _this2.createEmptyManifestFolders(); - yield _this2.saveLockfileAndIntegrity(patterns); - return true; - } + /** + * This method is like `_.range` except that it populates values in + * descending order. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns the range of numbers. + * @see _.inRange, _.range + * @example + * + * _.rangeRight(4); + * // => [3, 2, 1, 0] + * + * _.rangeRight(-4); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 5); + * // => [4, 3, 2, 1] + * + * _.rangeRight(0, 20, 5); + * // => [15, 10, 5, 0] + * + * _.rangeRight(0, -4, -1); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 4, 0); + * // => [1, 1, 1] + * + * _.rangeRight(0); + * // => [] + */ + var rangeRight = createRange(true); - return false; - })(); - } + /** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ + function stubArray() { + return []; + } - /** - * Produce empty folders for all used root manifests. - */ + /** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ + function stubFalse() { + return false; + } - createEmptyManifestFolders() { - var _this3 = this; + /** + * This method returns a new empty object. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Object} Returns the new empty object. + * @example + * + * var objects = _.times(2, _.stubObject); + * + * console.log(objects); + * // => [{}, {}] + * + * console.log(objects[0] === objects[1]); + * // => false + */ + function stubObject() { + return {}; + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (_this3.config.modulesFolder) { - // already created - return; - } + /** + * This method returns an empty string. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {string} Returns the empty string. + * @example + * + * _.times(2, _.stubString); + * // => ['', ''] + */ + function stubString() { + return ''; + } - for (const registryName of _this3.rootManifestRegistries) { - const folder = _this3.config.registries[registryName].folder; + /** + * This method returns `true`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `true`. + * @example + * + * _.times(2, _.stubTrue); + * // => [true, true] + */ + function stubTrue() { + return true; + } - yield (_fs || _load_fs()).mkdirp(path.join(_this3.config.cwd, folder)); + /** + * Invokes the iteratee `n` times, returning an array of the results of + * each invocation. The iteratee is invoked with one argument; (index). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of results. + * @example + * + * _.times(3, String); + * // => ['0', '1', '2'] + * + * _.times(4, _.constant(0)); + * // => [0, 0, 0, 0] + */ + function times(n, iteratee) { + n = toInteger(n); + if (n < 1 || n > MAX_SAFE_INTEGER) { + return []; } - })(); - } - - /** - * TODO description - */ + var index = MAX_ARRAY_LENGTH, + length = nativeMin(n, MAX_ARRAY_LENGTH); - markIgnored(patterns) { - for (const pattern of patterns) { - const manifest = this.resolver.getStrictResolvedPattern(pattern); - const ref = manifest._reference; - invariant(ref, 'expected package reference'); + iteratee = getIteratee(iteratee); + n -= MAX_ARRAY_LENGTH; - // just mark the package as ignored. if the package is used by a required package, the hoister - // will take care of that. - ref.ignore = true; + var result = baseTimes(length, iteratee); + while (++index < n) { + iteratee(index); + } + return result; } - } - - /** - * TODO description - */ - - init() { - var _this4 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this4.checkUpdate(); - // warn if we have a shrinkwrap - if (yield (_fs || _load_fs()).exists(path.join(_this4.config.cwd, 'npm-shrinkwrap.json'))) { - _this4.reporter.warn(_this4.reporter.lang('shrinkwrapWarning')); + /** + * Converts `value` to a property path array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {*} value The value to convert. + * @returns {Array} Returns the new property path array. + * @example + * + * _.toPath('a.b.c'); + * // => ['a', 'b', 'c'] + * + * _.toPath('a[0].b.c'); + * // => ['a', '0', 'b', 'c'] + */ + function toPath(value) { + if (isArray(value)) { + return arrayMap(value, toKey); } + return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); + } - let flattenedTopLevelPatterns = []; - const steps = []; + /** + * Generates a unique ID. If `prefix` is given, the ID is appended to it. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {string} [prefix=''] The value to prefix the ID with. + * @returns {string} Returns the unique ID. + * @example + * + * _.uniqueId('contact_'); + * // => 'contact_104' + * + * _.uniqueId(); + * // => '105' + */ + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } - var _ref2 = yield _this4.fetchRequestFromCwd(); + /*------------------------------------------------------------------------*/ - const depRequests = _ref2.requests, - rawPatterns = _ref2.patterns, - ignorePatterns = _ref2.ignorePatterns, - workspaceLayout = _ref2.workspaceLayout; + /** + * Adds two numbers. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {number} augend The first number in an addition. + * @param {number} addend The second number in an addition. + * @returns {number} Returns the total. + * @example + * + * _.add(6, 4); + * // => 10 + */ + var add = createMathOperation(function(augend, addend) { + return augend + addend; + }, 0); - let topLevelPatterns = []; + /** + * Computes `number` rounded up to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round up. + * @param {number} [precision=0] The precision to round up to. + * @returns {number} Returns the rounded up number. + * @example + * + * _.ceil(4.006); + * // => 5 + * + * _.ceil(6.004, 2); + * // => 6.01 + * + * _.ceil(6040, -2); + * // => 6100 + */ + var ceil = createRound('ceil'); - const artifacts = yield _this4.integrityChecker.getArtifacts(); - if (artifacts) { - _this4.linker.setArtifacts(artifacts); - _this4.scripts.setArtifacts(artifacts); - } + /** + * Divide two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} dividend The first number in a division. + * @param {number} divisor The second number in a division. + * @returns {number} Returns the quotient. + * @example + * + * _.divide(6, 4); + * // => 1.5 + */ + var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; + }, 1); - steps.push((() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - _this4.reporter.step(curr, total, _this4.reporter.lang('resolvingPackages'), emoji.get('mag')); - yield _this4.resolver.init(_this4.prepareRequests(depRequests), { - isFlat: _this4.flags.flat, - isFrozen: _this4.flags.frozenLockfile, - workspaceLayout - }); - topLevelPatterns = _this4.preparePatterns(rawPatterns); - flattenedTopLevelPatterns = yield _this4.flatten(topLevelPatterns); - return { bailout: yield _this4.bailout(topLevelPatterns, workspaceLayout) }; - }); + /** + * Computes `number` rounded down to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round down. + * @param {number} [precision=0] The precision to round down to. + * @returns {number} Returns the rounded down number. + * @example + * + * _.floor(4.006); + * // => 4 + * + * _.floor(0.046, 2); + * // => 0.04 + * + * _.floor(4060, -2); + * // => 4000 + */ + var floor = createRound('floor'); - return function (_x3, _x4) { - return _ref3.apply(this, arguments); - }; - })()); + /** + * Computes the maximum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => undefined + */ + function max(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseGt) + : undefined; + } - steps.push((() => { - var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - _this4.markIgnored(ignorePatterns); - _this4.reporter.step(curr, total, _this4.reporter.lang('fetchingPackages'), emoji.get('truck')); - const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this4.resolver.getManifests(), _this4.config); - _this4.resolver.updateManifests(manifests); - yield (_packageCompatibility || _load_packageCompatibility()).check(_this4.resolver.getManifests(), _this4.config, _this4.flags.ignoreEngines); - }); - - return function (_x5, _x6) { - return _ref4.apply(this, arguments); - }; - })()); - - steps.push((() => { - var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - // remove integrity hash to make this operation atomic - yield _this4.integrityChecker.removeIntegrityFile(); - _this4.reporter.step(curr, total, _this4.reporter.lang('linkingDependencies'), emoji.get('link')); - yield _this4.linker.init(flattenedTopLevelPatterns, _this4.flags.linkDuplicates, workspaceLayout); - }); - - return function (_x7, _x8) { - return _ref5.apply(this, arguments); - }; - })()); - - steps.push((() => { - var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - _this4.reporter.step(curr, total, _this4.flags.force ? _this4.reporter.lang('rebuildingPackages') : _this4.reporter.lang('buildingFreshPackages'), emoji.get('page_with_curl')); - - if (_this4.flags.ignoreScripts) { - _this4.reporter.warn(_this4.reporter.lang('ignoredScripts')); - } else { - yield _this4.scripts.init(flattenedTopLevelPatterns); - } - }); - - return function (_x9, _x10) { - return _ref6.apply(this, arguments); - }; - })()); - - if (_this4.flags.har) { - steps.push((() => { - var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - const formattedDate = new Date().toISOString().replace(/:/g, '-'); - const filename = `yarn-install_${formattedDate}.har`; - _this4.reporter.step(curr, total, _this4.reporter.lang('savingHar', filename), emoji.get('black_circle_for_record')); - yield _this4.config.requestManager.saveHar(filename); - }); - - return function (_x11, _x12) { - return _ref7.apply(this, arguments); - }; - })()); - } - - if (yield _this4.shouldClean()) { - steps.push((() => { - var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { - _this4.reporter.step(curr, total, _this4.reporter.lang('cleaningModules'), emoji.get('recycle')); - yield (0, (_clean || _load_clean()).clean)(_this4.config, _this4.reporter); - }); - - return function (_x13, _x14) { - return _ref8.apply(this, arguments); - }; - })()); - } - - let currentStep = 0; - for (const step of steps) { - const stepResult = yield step(++currentStep, steps.length); - if (stepResult && stepResult.bailout) { - _this4.maybeOutputUpdate(); - return flattenedTopLevelPatterns; - } - } + /** + * This method is like `_.max` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {*} Returns the maximum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.maxBy(objects, function(o) { return o.n; }); + * // => { 'n': 2 } + * + * // The `_.property` iteratee shorthand. + * _.maxBy(objects, 'n'); + * // => { 'n': 2 } + */ + function maxBy(array, iteratee) { + return (array && array.length) + ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) + : undefined; + } - // fin! - yield _this4.saveLockfileAndIntegrity(topLevelPatterns, workspaceLayout); - _this4.maybeOutputUpdate(); - _this4.config.requestManager.clearCache(); - return flattenedTopLevelPatterns; - })(); - } + /** + * Computes the mean of the values in `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @returns {number} Returns the mean. + * @example + * + * _.mean([4, 2, 8, 6]); + * // => 5 + */ + function mean(array) { + return baseMean(array, identity); + } - /** - * Check if we should run the cleaning step. - */ + /** + * This method is like `_.mean` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the value to be averaged. + * The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the mean. + * @example + * + * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * + * _.meanBy(objects, function(o) { return o.n; }); + * // => 5 + * + * // The `_.property` iteratee shorthand. + * _.meanBy(objects, 'n'); + * // => 5 + */ + function meanBy(array, iteratee) { + return baseMean(array, getIteratee(iteratee, 2)); + } - shouldClean() { - return (_fs || _load_fs()).exists(path.join(this.config.cwd, (_constants || _load_constants()).CLEAN_FILENAME)); - } + /** + * Computes the minimum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => undefined + */ + function min(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseLt) + : undefined; + } - /** - * TODO - */ + /** + * This method is like `_.min` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {*} Returns the minimum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.minBy(objects, function(o) { return o.n; }); + * // => { 'n': 1 } + * + * // The `_.property` iteratee shorthand. + * _.minBy(objects, 'n'); + * // => { 'n': 1 } + */ + function minBy(array, iteratee) { + return (array && array.length) + ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) + : undefined; + } - flatten(patterns) { - var _this5 = this; + /** + * Multiply two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} multiplier The first number in a multiplication. + * @param {number} multiplicand The second number in a multiplication. + * @returns {number} Returns the product. + * @example + * + * _.multiply(6, 4); + * // => 24 + */ + var multiply = createMathOperation(function(multiplier, multiplicand) { + return multiplier * multiplicand; + }, 1); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (!_this5.flags.flat) { - return patterns; - } + /** + * Computes `number` rounded to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round. + * @param {number} [precision=0] The precision to round to. + * @returns {number} Returns the rounded number. + * @example + * + * _.round(4.006); + * // => 4 + * + * _.round(4.006, 2); + * // => 4.01 + * + * _.round(4060, -2); + * // => 4100 + */ + var round = createRound('round'); - const flattenedPatterns = []; + /** + * Subtract two numbers. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {number} minuend The first number in a subtraction. + * @param {number} subtrahend The second number in a subtraction. + * @returns {number} Returns the difference. + * @example + * + * _.subtract(6, 4); + * // => 2 + */ + var subtract = createMathOperation(function(minuend, subtrahend) { + return minuend - subtrahend; + }, 0); - for (const name of _this5.resolver.getAllDependencyNamesByLevelOrder(patterns)) { - const infos = _this5.resolver.getAllInfoForPackageName(name).filter(function (manifest) { - const ref = manifest._reference; - invariant(ref, 'expected package reference'); - return !ref.ignore; - }); + /** + * Computes the sum of the values in `array`. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {Array} array The array to iterate over. + * @returns {number} Returns the sum. + * @example + * + * _.sum([4, 2, 8, 6]); + * // => 20 + */ + function sum(array) { + return (array && array.length) + ? baseSum(array, identity) + : 0; + } - if (infos.length === 0) { - continue; - } + /** + * This method is like `_.sum` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the value to be summed. + * The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the sum. + * @example + * + * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * + * _.sumBy(objects, function(o) { return o.n; }); + * // => 20 + * + * // The `_.property` iteratee shorthand. + * _.sumBy(objects, 'n'); + * // => 20 + */ + function sumBy(array, iteratee) { + return (array && array.length) + ? baseSum(array, getIteratee(iteratee, 2)) + : 0; + } - if (infos.length === 1) { - // single version of this package - // take out a single pattern as multiple patterns may have resolved to this package - flattenedPatterns.push(_this5.resolver.patternsByPackage[name][0]); - continue; - } + /*------------------------------------------------------------------------*/ - const options = infos.map(function (info) { - const ref = info._reference; - invariant(ref, 'expected reference'); - return { - // TODO `and is required by {PARENT}`, - name: _this5.reporter.lang('manualVersionResolutionOption', ref.patterns.join(', '), info.version), + // Add methods that return wrapped values in chain sequences. + lodash.after = after; + lodash.ary = ary; + lodash.assign = assign; + lodash.assignIn = assignIn; + lodash.assignInWith = assignInWith; + lodash.assignWith = assignWith; + lodash.at = at; + lodash.before = before; + lodash.bind = bind; + lodash.bindAll = bindAll; + lodash.bindKey = bindKey; + lodash.castArray = castArray; + lodash.chain = chain; + lodash.chunk = chunk; + lodash.compact = compact; + lodash.concat = concat; + lodash.cond = cond; + lodash.conforms = conforms; + lodash.constant = constant; + lodash.countBy = countBy; + lodash.create = create; + lodash.curry = curry; + lodash.curryRight = curryRight; + lodash.debounce = debounce; + lodash.defaults = defaults; + lodash.defaultsDeep = defaultsDeep; + lodash.defer = defer; + lodash.delay = delay; + lodash.difference = difference; + lodash.differenceBy = differenceBy; + lodash.differenceWith = differenceWith; + lodash.drop = drop; + lodash.dropRight = dropRight; + lodash.dropRightWhile = dropRightWhile; + lodash.dropWhile = dropWhile; + lodash.fill = fill; + lodash.filter = filter; + lodash.flatMap = flatMap; + lodash.flatMapDeep = flatMapDeep; + lodash.flatMapDepth = flatMapDepth; + lodash.flatten = flatten; + lodash.flattenDeep = flattenDeep; + lodash.flattenDepth = flattenDepth; + lodash.flip = flip; + lodash.flow = flow; + lodash.flowRight = flowRight; + lodash.fromPairs = fromPairs; + lodash.functions = functions; + lodash.functionsIn = functionsIn; + lodash.groupBy = groupBy; + lodash.initial = initial; + lodash.intersection = intersection; + lodash.intersectionBy = intersectionBy; + lodash.intersectionWith = intersectionWith; + lodash.invert = invert; + lodash.invertBy = invertBy; + lodash.invokeMap = invokeMap; + lodash.iteratee = iteratee; + lodash.keyBy = keyBy; + lodash.keys = keys; + lodash.keysIn = keysIn; + lodash.map = map; + lodash.mapKeys = mapKeys; + lodash.mapValues = mapValues; + lodash.matches = matches; + lodash.matchesProperty = matchesProperty; + lodash.memoize = memoize; + lodash.merge = merge; + lodash.mergeWith = mergeWith; + lodash.method = method; + lodash.methodOf = methodOf; + lodash.mixin = mixin; + lodash.negate = negate; + lodash.nthArg = nthArg; + lodash.omit = omit; + lodash.omitBy = omitBy; + lodash.once = once; + lodash.orderBy = orderBy; + lodash.over = over; + lodash.overArgs = overArgs; + lodash.overEvery = overEvery; + lodash.overSome = overSome; + lodash.partial = partial; + lodash.partialRight = partialRight; + lodash.partition = partition; + lodash.pick = pick; + lodash.pickBy = pickBy; + lodash.property = property; + lodash.propertyOf = propertyOf; + lodash.pull = pull; + lodash.pullAll = pullAll; + lodash.pullAllBy = pullAllBy; + lodash.pullAllWith = pullAllWith; + lodash.pullAt = pullAt; + lodash.range = range; + lodash.rangeRight = rangeRight; + lodash.rearg = rearg; + lodash.reject = reject; + lodash.remove = remove; + lodash.rest = rest; + lodash.reverse = reverse; + lodash.sampleSize = sampleSize; + lodash.set = set; + lodash.setWith = setWith; + lodash.shuffle = shuffle; + lodash.slice = slice; + lodash.sortBy = sortBy; + lodash.sortedUniq = sortedUniq; + lodash.sortedUniqBy = sortedUniqBy; + lodash.split = split; + lodash.spread = spread; + lodash.tail = tail; + lodash.take = take; + lodash.takeRight = takeRight; + lodash.takeRightWhile = takeRightWhile; + lodash.takeWhile = takeWhile; + lodash.tap = tap; + lodash.throttle = throttle; + lodash.thru = thru; + lodash.toArray = toArray; + lodash.toPairs = toPairs; + lodash.toPairsIn = toPairsIn; + lodash.toPath = toPath; + lodash.toPlainObject = toPlainObject; + lodash.transform = transform; + lodash.unary = unary; + lodash.union = union; + lodash.unionBy = unionBy; + lodash.unionWith = unionWith; + lodash.uniq = uniq; + lodash.uniqBy = uniqBy; + lodash.uniqWith = uniqWith; + lodash.unset = unset; + lodash.unzip = unzip; + lodash.unzipWith = unzipWith; + lodash.update = update; + lodash.updateWith = updateWith; + lodash.values = values; + lodash.valuesIn = valuesIn; + lodash.without = without; + lodash.words = words; + lodash.wrap = wrap; + lodash.xor = xor; + lodash.xorBy = xorBy; + lodash.xorWith = xorWith; + lodash.zip = zip; + lodash.zipObject = zipObject; + lodash.zipObjectDeep = zipObjectDeep; + lodash.zipWith = zipWith; - value: info.version - }; - }); - const versions = infos.map(function (info) { - return info.version; - }); - let version; + // Add aliases. + lodash.entries = toPairs; + lodash.entriesIn = toPairsIn; + lodash.extend = assignIn; + lodash.extendWith = assignInWith; - const resolutionVersion = _this5.resolutions[name]; - if (resolutionVersion && versions.indexOf(resolutionVersion) >= 0) { - // use json `resolution` version - version = resolutionVersion; - } else { - version = yield _this5.reporter.select(_this5.reporter.lang('manualVersionResolution', name), _this5.reporter.lang('answer'), options); - _this5.resolutions[name] = version; - } + // Add methods to `lodash.prototype`. + mixin(lodash, lodash); - flattenedPatterns.push(_this5.resolver.collapseAllVersionsOfPackage(name, version)); - } + /*------------------------------------------------------------------------*/ - // save resolutions to their appropriate root manifest - if (Object.keys(_this5.resolutions).length) { - const manifests = yield _this5.config.getRootManifests(); + // Add methods that return unwrapped values in chain sequences. + lodash.add = add; + lodash.attempt = attempt; + lodash.camelCase = camelCase; + lodash.capitalize = capitalize; + lodash.ceil = ceil; + lodash.clamp = clamp; + lodash.clone = clone; + lodash.cloneDeep = cloneDeep; + lodash.cloneDeepWith = cloneDeepWith; + lodash.cloneWith = cloneWith; + lodash.conformsTo = conformsTo; + lodash.deburr = deburr; + lodash.defaultTo = defaultTo; + lodash.divide = divide; + lodash.endsWith = endsWith; + lodash.eq = eq; + lodash.escape = escape; + lodash.escapeRegExp = escapeRegExp; + lodash.every = every; + lodash.find = find; + lodash.findIndex = findIndex; + lodash.findKey = findKey; + lodash.findLast = findLast; + lodash.findLastIndex = findLastIndex; + lodash.findLastKey = findLastKey; + lodash.floor = floor; + lodash.forEach = forEach; + lodash.forEachRight = forEachRight; + lodash.forIn = forIn; + lodash.forInRight = forInRight; + lodash.forOwn = forOwn; + lodash.forOwnRight = forOwnRight; + lodash.get = get; + lodash.gt = gt; + lodash.gte = gte; + lodash.has = has; + lodash.hasIn = hasIn; + lodash.head = head; + lodash.identity = identity; + lodash.includes = includes; + lodash.indexOf = indexOf; + lodash.inRange = inRange; + lodash.invoke = invoke; + lodash.isArguments = isArguments; + lodash.isArray = isArray; + lodash.isArrayBuffer = isArrayBuffer; + lodash.isArrayLike = isArrayLike; + lodash.isArrayLikeObject = isArrayLikeObject; + lodash.isBoolean = isBoolean; + lodash.isBuffer = isBuffer; + lodash.isDate = isDate; + lodash.isElement = isElement; + lodash.isEmpty = isEmpty; + lodash.isEqual = isEqual; + lodash.isEqualWith = isEqualWith; + lodash.isError = isError; + lodash.isFinite = isFinite; + lodash.isFunction = isFunction; + lodash.isInteger = isInteger; + lodash.isLength = isLength; + lodash.isMap = isMap; + lodash.isMatch = isMatch; + lodash.isMatchWith = isMatchWith; + lodash.isNaN = isNaN; + lodash.isNative = isNative; + lodash.isNil = isNil; + lodash.isNull = isNull; + lodash.isNumber = isNumber; + lodash.isObject = isObject; + lodash.isObjectLike = isObjectLike; + lodash.isPlainObject = isPlainObject; + lodash.isRegExp = isRegExp; + lodash.isSafeInteger = isSafeInteger; + lodash.isSet = isSet; + lodash.isString = isString; + lodash.isSymbol = isSymbol; + lodash.isTypedArray = isTypedArray; + lodash.isUndefined = isUndefined; + lodash.isWeakMap = isWeakMap; + lodash.isWeakSet = isWeakSet; + lodash.join = join; + lodash.kebabCase = kebabCase; + lodash.last = last; + lodash.lastIndexOf = lastIndexOf; + lodash.lowerCase = lowerCase; + lodash.lowerFirst = lowerFirst; + lodash.lt = lt; + lodash.lte = lte; + lodash.max = max; + lodash.maxBy = maxBy; + lodash.mean = mean; + lodash.meanBy = meanBy; + lodash.min = min; + lodash.minBy = minBy; + lodash.stubArray = stubArray; + lodash.stubFalse = stubFalse; + lodash.stubObject = stubObject; + lodash.stubString = stubString; + lodash.stubTrue = stubTrue; + lodash.multiply = multiply; + lodash.nth = nth; + lodash.noConflict = noConflict; + lodash.noop = noop; + lodash.now = now; + lodash.pad = pad; + lodash.padEnd = padEnd; + lodash.padStart = padStart; + lodash.parseInt = parseInt; + lodash.random = random; + lodash.reduce = reduce; + lodash.reduceRight = reduceRight; + lodash.repeat = repeat; + lodash.replace = replace; + lodash.result = result; + lodash.round = round; + lodash.runInContext = runInContext; + lodash.sample = sample; + lodash.size = size; + lodash.snakeCase = snakeCase; + lodash.some = some; + lodash.sortedIndex = sortedIndex; + lodash.sortedIndexBy = sortedIndexBy; + lodash.sortedIndexOf = sortedIndexOf; + lodash.sortedLastIndex = sortedLastIndex; + lodash.sortedLastIndexBy = sortedLastIndexBy; + lodash.sortedLastIndexOf = sortedLastIndexOf; + lodash.startCase = startCase; + lodash.startsWith = startsWith; + lodash.subtract = subtract; + lodash.sum = sum; + lodash.sumBy = sumBy; + lodash.template = template; + lodash.times = times; + lodash.toFinite = toFinite; + lodash.toInteger = toInteger; + lodash.toLength = toLength; + lodash.toLower = toLower; + lodash.toNumber = toNumber; + lodash.toSafeInteger = toSafeInteger; + lodash.toString = toString; + lodash.toUpper = toUpper; + lodash.trim = trim; + lodash.trimEnd = trimEnd; + lodash.trimStart = trimStart; + lodash.truncate = truncate; + lodash.unescape = unescape; + lodash.uniqueId = uniqueId; + lodash.upperCase = upperCase; + lodash.upperFirst = upperFirst; - for (const name in _this5.resolutions) { - const version = _this5.resolutions[name]; + // Add aliases. + lodash.each = forEach; + lodash.eachRight = forEachRight; + lodash.first = head; - const patterns = _this5.resolver.patternsByPackage[name]; - if (!patterns) { - continue; - } + mixin(lodash, (function() { + var source = {}; + baseForOwn(lodash, function(func, methodName) { + if (!hasOwnProperty.call(lodash.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }()), { 'chain': false }); - let manifest; - for (const pattern of patterns) { - manifest = _this5.resolver.getResolvedPattern(pattern); - if (manifest) { - break; - } - } - invariant(manifest, 'expected manifest'); + /*------------------------------------------------------------------------*/ - const ref = manifest._reference; - invariant(ref, 'expected reference'); + /** + * The semantic version number. + * + * @static + * @memberOf _ + * @type {string} + */ + lodash.VERSION = VERSION; - const object = manifests[ref.registry].object; - object.resolutions = object.resolutions || {}; - object.resolutions[name] = version; - } + // Assign default placeholders. + arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { + lodash[methodName].placeholder = lodash; + }); - yield _this5.config.saveRootManifests(manifests); - } + // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. + arrayEach(['drop', 'take'], function(methodName, index) { + LazyWrapper.prototype[methodName] = function(n) { + n = n === undefined ? 1 : nativeMax(toInteger(n), 0); - return flattenedPatterns; - })(); - } + var result = (this.__filtered__ && !index) + ? new LazyWrapper(this) + : this.clone(); - /** - * Remove offline tarballs that are no longer required - */ + if (result.__filtered__) { + result.__takeCount__ = nativeMin(n, result.__takeCount__); + } else { + result.__views__.push({ + 'size': nativeMin(n, MAX_ARRAY_LENGTH), + 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') + }); + } + return result; + }; - pruneOfflineMirror(lockfile) { - var _this6 = this; + LazyWrapper.prototype[methodName + 'Right'] = function(n) { + return this.reverse()[methodName](n).reverse(); + }; + }); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const mirror = _this6.config.getOfflineMirrorPath(); - if (!mirror) { - return; - } + // Add `LazyWrapper` methods that accept an `iteratee` value. + arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { + var type = index + 1, + isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; - const requiredTarballs = new Set(); - for (const dependency in lockfile) { - const resolved = lockfile[dependency].resolved; - const basename = path.basename(resolved.split('#')[0]); - if (resolved) { - if (dependency[0] === '@' && basename[0] !== '@') { - requiredTarballs.add(`${dependency.split('/')[0]}-${basename}`); - } - requiredTarballs.add(basename); - } - } + LazyWrapper.prototype[methodName] = function(iteratee) { + var result = this.clone(); + result.__iteratees__.push({ + 'iteratee': getIteratee(iteratee, 3), + 'type': type + }); + result.__filtered__ = result.__filtered__ || isFilter; + return result; + }; + }); - const mirrorFiles = yield (_fs || _load_fs()).walk(mirror); - for (const file of mirrorFiles) { - const isTarball = path.extname(file.basename) === '.tgz'; - if (isTarball && !requiredTarballs.has(file.basename)) { - yield (_fs || _load_fs()).unlink(file.absolute); - } - } - })(); - } + // Add `LazyWrapper` methods for `_.head` and `_.last`. + arrayEach(['head', 'last'], function(methodName, index) { + var takeName = 'take' + (index ? 'Right' : ''); - /** - * Save updated integrity and lockfiles. - */ + LazyWrapper.prototype[methodName] = function() { + return this[takeName](1).value()[0]; + }; + }); - saveLockfileAndIntegrity(patterns, workspaceLayout) { - var _this7 = this; + // Add `LazyWrapper` methods for `_.initial` and `_.tail`. + arrayEach(['initial', 'tail'], function(methodName, index) { + var dropName = 'drop' + (index ? '' : 'Right'); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const resolvedPatterns = {}; - Object.keys(_this7.resolver.patterns).forEach(function (pattern) { - if (!workspaceLayout || !workspaceLayout.getManifestByPattern(pattern)) { - resolvedPatterns[pattern] = _this7.resolver.patterns[pattern]; - } - }); + LazyWrapper.prototype[methodName] = function() { + return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); + }; + }); - // TODO this code is duplicated in a few places, need a common way to filter out workspace patterns from lockfile - patterns = patterns.filter(function (p) { - return !workspaceLayout || !workspaceLayout.getManifestByPattern(p); - }); + LazyWrapper.prototype.compact = function() { + return this.filter(identity); + }; - const lockfileBasedOnResolver = _this7.lockfile.getLockfile(resolvedPatterns); + LazyWrapper.prototype.find = function(predicate) { + return this.filter(predicate).head(); + }; - if (_this7.config.pruneOfflineMirror) { - yield _this7.pruneOfflineMirror(lockfileBasedOnResolver); + LazyWrapper.prototype.findLast = function(predicate) { + return this.reverse().find(predicate); + }; + + LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { + if (typeof path == 'function') { + return new LazyWrapper(this); } + return this.map(function(value) { + return baseInvoke(value, path, args); + }); + }); - // write integrity hash - yield _this7.integrityChecker.save(patterns, lockfileBasedOnResolver, _this7.flags, _this7.resolver.usedRegistries, _this7.scripts.getArtifacts()); + LazyWrapper.prototype.reject = function(predicate) { + return this.filter(negate(getIteratee(predicate))); + }; - // --no-lockfile or --pure-lockfile flag - if (_this7.flags.lockfile === false || _this7.flags.pureLockfile) { - return; - } + LazyWrapper.prototype.slice = function(start, end) { + start = toInteger(start); - const lockFileHasAllPatterns = patterns.every(function (p) { - return _this7.lockfile.getLocked(p); - }); - const resolverPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { - const manifest = _this7.lockfile.getLocked(pattern); - return manifest && manifest.resolved === lockfileBasedOnResolver[pattern].resolved; - }); - // remove command is followed by install with force, lockfile will be rewritten in any case then - if (lockFileHasAllPatterns && resolverPatternsAreSameAsInLockfile && patterns.length && !_this7.flags.force) { - return; + var result = this; + if (result.__filtered__ && (start > 0 || end < 0)) { + return new LazyWrapper(result); + } + if (start < 0) { + result = result.takeRight(-start); + } else if (start) { + result = result.drop(start); + } + if (end !== undefined) { + end = toInteger(end); + result = end < 0 ? result.dropRight(-end) : result.take(end - start); } + return result; + }; - // build lockfile location - const loc = path.join(_this7.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME); + LazyWrapper.prototype.takeRightWhile = function(predicate) { + return this.reverse().takeWhile(predicate).reverse(); + }; - // write lockfile - const lockSource = (0, (_stringify || _load_stringify()).default)(lockfileBasedOnResolver, false, _this7.config.enableLockfileVersions); - yield (_fs || _load_fs()).writeFilePreservingEol(loc, lockSource); + LazyWrapper.prototype.toArray = function() { + return this.take(MAX_ARRAY_LENGTH); + }; - _this7._logSuccessSaveLockfile(); - })(); - } + // Add `LazyWrapper` methods to `lodash.prototype`. + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), + isTaker = /^(?:head|last)$/.test(methodName), + lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], + retUnwrapped = isTaker || /^find/.test(methodName); - _logSuccessSaveLockfile() { - this.reporter.success(this.reporter.lang('savedLockfile')); - } + if (!lodashFunc) { + return; + } + lodash.prototype[methodName] = function() { + var value = this.__wrapped__, + args = isTaker ? [1] : arguments, + isLazy = value instanceof LazyWrapper, + iteratee = args[0], + useLazy = isLazy || isArray(value); - /** - * Load the dependency graph of the current install. Only does package resolving and wont write to the cwd. - */ - hydrate(ignoreUnusedPatterns) { - var _this8 = this; + var interceptor = function(value) { + var result = lodashFunc.apply(lodash, arrayPush([value], args)); + return (isTaker && chainAll) ? result[0] : result; + }; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const request = yield _this8.fetchRequestFromCwd([], ignoreUnusedPatterns); - const depRequests = request.requests, - rawPatterns = request.patterns, - ignorePatterns = request.ignorePatterns, - workspaceLayout = request.workspaceLayout; + if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { + // Avoid lazy use if the iteratee has a "length" value other than `1`. + isLazy = useLazy = false; + } + var chainAll = this.__chain__, + isHybrid = !!this.__actions__.length, + isUnwrapped = retUnwrapped && !chainAll, + onlyLazy = isLazy && !isHybrid; + if (!retUnwrapped && useLazy) { + value = onlyLazy ? value : new LazyWrapper(this); + var result = func.apply(value, args); + result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); + return new LodashWrapper(result, chainAll); + } + if (isUnwrapped && onlyLazy) { + return func.apply(this, args); + } + result = this.thru(interceptor); + return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; + }; + }); - yield _this8.resolver.init(depRequests, { - isFlat: _this8.flags.flat, - isFrozen: _this8.flags.frozenLockfile, - workspaceLayout - }); - yield _this8.flatten(rawPatterns); - _this8.markIgnored(ignorePatterns); + // Add `Array` methods to `lodash.prototype`. + arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { + var func = arrayProto[methodName], + chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', + retUnwrapped = /^(?:pop|shift)$/.test(methodName); - // fetch packages, should hit cache most of the time - const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this8.resolver.getManifests(), _this8.config); - _this8.resolver.updateManifests(manifests); - yield (_packageCompatibility || _load_packageCompatibility()).check(_this8.resolver.getManifests(), _this8.config, _this8.flags.ignoreEngines); + lodash.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value = this.value(); + return func.apply(isArray(value) ? value : [], args); + } + return this[chainName](function(value) { + return func.apply(isArray(value) ? value : [], args); + }); + }; + }); - // expand minimal manifests - for (const manifest of _this8.resolver.getManifests()) { - const ref = manifest._reference; - invariant(ref, 'expected reference'); - const type = ref.remote.type; - // link specifier won't ever hit cache + // Map minified method names to their real names. + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var lodashFunc = lodash[methodName]; + if (lodashFunc) { + var key = (lodashFunc.name + ''), + names = realNames[key] || (realNames[key] = []); - let loc = ''; - if (type === 'link') { - continue; - } else if (type === 'workspace') { - if (!ref.remote.reference) { - continue; - } - loc = ref.remote.reference; - } else { - loc = _this8.config.generateHardModulePath(ref); - } - const newPkg = yield _this8.config.readManifest(loc); - yield _this8.resolver.updateManifest(ref, newPkg); + names.push({ 'name': methodName, 'func': lodashFunc }); } + }); - return request; - })(); - } + realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ + 'name': 'wrapper', + 'func': undefined + }]; - /** - * Check for updates every day and output a nag message if there's a newer version. - */ + // Add methods to `LazyWrapper`. + LazyWrapper.prototype.clone = lazyClone; + LazyWrapper.prototype.reverse = lazyReverse; + LazyWrapper.prototype.value = lazyValue; - checkUpdate() { - if (!process.stdout.isTTY || isCI) { - // don't show upgrade dialog on CI or non-TTY terminals - return; - } + // Add chain sequence methods to the `lodash` wrapper. + lodash.prototype.at = wrapperAt; + lodash.prototype.chain = wrapperChain; + lodash.prototype.commit = wrapperCommit; + lodash.prototype.next = wrapperNext; + lodash.prototype.plant = wrapperPlant; + lodash.prototype.reverse = wrapperReverse; + lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; - // don't check if disabled - if (this.config.getOption('disable-self-update-check')) { - return; - } + // Add lazy aliases. + lodash.prototype.first = lodash.prototype.head; - // only check for updates once a day - const lastUpdateCheck = Number(this.config.getOption('lastUpdateCheck')) || 0; - if (lastUpdateCheck && Date.now() - lastUpdateCheck < ONE_DAY) { - return; + if (symIterator) { + lodash.prototype[symIterator] = wrapperToIterator; } + return lodash; + }); - // don't bug for updates on tagged releases - if ((_yarnVersion || _load_yarnVersion()).version.indexOf('-') >= 0) { - return; - } - - this._checkUpdate().catch(() => { - // swallow errors - }); - } - - _checkUpdate() { - var _this9 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let latestVersion = yield _this9.config.requestManager.request({ - url: (_constants || _load_constants()).SELF_UPDATE_VERSION_URL - }); - invariant(typeof latestVersion === 'string', 'expected string'); - latestVersion = latestVersion.trim(); - if (!semver.valid(latestVersion)) { - return; - } + /*--------------------------------------------------------------------------*/ - // ensure we only check for updates periodically - _this9.config.registries.yarn.saveHomeConfig({ - lastUpdateCheck: Date.now() - }); + // Export lodash. + var _ = runInContext(); - if (semver.gt(latestVersion, (_yarnVersion || _load_yarnVersion()).version)) { - const installationMethod = yield (0, (_yarnVersion || _load_yarnVersion()).getInstallationMethod)(); - _this9.maybeOutputUpdate = function () { - _this9.reporter.warn(_this9.reporter.lang('yarnOutdated', latestVersion, (_yarnVersion || _load_yarnVersion()).version)); + // Some AMD build optimizers, like r.js, check for condition patterns like: + if (true) { + // Expose Lodash on the global object to prevent errors when Lodash is + // loaded by a script tag in the presence of an AMD loader. + // See http://requirejs.org/docs/errors.html#mismatch for more details. + // Use `_.noConflict` to remove Lodash from the global object. + root._ = _; - const command = getUpdateCommand(installationMethod); - if (command) { - _this9.reporter.info(_this9.reporter.lang('yarnOutdatedCommand')); - _this9.reporter.command(command); - } else { - const installer = getUpdateInstaller(installationMethod); - if (installer) { - _this9.reporter.info(_this9.reporter.lang('yarnOutdatedInstaller', installer)); - } - } - }; - } - })(); + // Define as an anonymous module so, through path mapping, it can be + // referenced as the "underscore" module. + !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { + return _; + }.call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } + // Check for `exports` after `define` in case a build optimizer adds it. + else if (freeModule) { + // Export for Node.js. + (freeModule.exports = _)._ = _; + // Export for CommonJS support. + freeExports._ = _; + } + else { + // Export to the global object. + root._ = _; + } +}.call(this)); - /** - * Method to override with a possible upgrade message. - */ - - maybeOutputUpdate() {} -} +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) -exports.Install = Install; -function hasWrapper(commander, args) { - return true; -} +/***/ }), +/* 29 */ +/***/ (function(module, exports, __webpack_require__) { -function setFlags(commander) { - commander.usage('install [flags]'); - commander.option('-g, --global', 'DEPRECATED'); - commander.option('-S, --save', 'DEPRECATED - save package to your `dependencies`'); - commander.option('-D, --save-dev', 'DEPRECATED - save package to your `devDependencies`'); - commander.option('-P, --save-peer', 'DEPRECATED - save package to your `peerDependencies`'); - commander.option('-O, --save-optional', 'DEPRECATED - save package to your `optionalDependencies`'); - commander.option('-E, --save-exact', 'DEPRECATED'); - commander.option('-T, --save-tilde', 'DEPRECATED'); -} +var dP = __webpack_require__(38) + , createDesc = __webpack_require__(83); +module.exports = __webpack_require__(33) ? function(object, key, value){ + return dP.f(object, key, createDesc(1, value)); +} : function(object, key, value){ + object[key] = value; + return object; +}; /***/ }), -/* 24 */ +/* 30 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -21115,31 +21618,47 @@ function setFlags(commander) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.registryNames = exports.registries = undefined; +exports.normalizePattern = normalizePattern; -var _yarnRegistry; +/** + * Explode and normalize a pattern into its name and range. + */ -function _load_yarnRegistry() { - return _yarnRegistry = _interopRequireDefault(__webpack_require__(366)); -} +function normalizePattern(pattern) { + let hasVersion = false; + let range = 'latest'; + let name = pattern; -var _npmRegistry; + // if we're a scope then remove the @ and add it back later + let isScoped = false; + if (name[0] === '@') { + isScoped = true; + name = name.slice(1); + } -function _load_npmRegistry() { - return _npmRegistry = _interopRequireDefault(__webpack_require__(43)); -} + // take first part as the name + const parts = name.split('@'); + if (parts.length > 1) { + name = parts.shift(); + range = parts.join('@'); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (range) { + hasVersion = true; + } else { + range = '*'; + } + } -const registries = exports.registries = { - npm: (_npmRegistry || _load_npmRegistry()).default, - yarn: (_yarnRegistry || _load_yarnRegistry()).default -}; + // add back @ scope suffix + if (isScoped) { + name = `@${name}`; + } -const registryNames = exports.registryNames = Object.keys(registries); + return { name, range, hasVersion }; +} /***/ }), -/* 25 */ +/* 31 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -21148,1255 +21667,1146 @@ const registryNames = exports.registryNames = Object.keys(registries); Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = nullify; -function nullify() { - let obj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; +exports.wrapLifecycle = exports.run = exports.install = exports.Install = undefined; - if (Array.isArray(obj)) { - for (const item of obj) { - nullify(item); - } - } else if (obj !== null && typeof obj === 'object' || typeof obj === 'function') { - Object.setPrototypeOf(obj, null); +var _extends2; - // for..in can only be applied to 'object', not 'function' - if (typeof obj === 'object') { - for (const key in obj) { - nullify(obj[key]); - } - } - } +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); +} - return obj; +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -/***/ }), -/* 26 */ -/***/ (function(module, exports, __webpack_require__) { +let install = exports.install = (() => { + var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, lockfile) { + yield wrapLifecycle(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const install = new Install(flags, config, reporter, lockfile); + yield install.init(); + })); + }); -var store = __webpack_require__(223)('wks') - , uid = __webpack_require__(225) - , Symbol = __webpack_require__(29).Symbol - , USE_SYMBOL = typeof Symbol == 'function'; + return function install(_x17, _x18, _x19, _x20) { + return _ref11.apply(this, arguments); + }; +})(); -var $exports = module.exports = function(name){ - return store[name] || (store[name] = - USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); -}; +let run = exports.run = (() => { + var _ref13 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + let lockfile; + let error = 'installCommandRenamed'; + if (flags.lockfile === false) { + lockfile = new (_lockfile || _load_lockfile()).default(); + } else { + lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder, reporter); + } -$exports.store = store; + if (args.length) { + const exampleArgs = args.slice(); -/***/ }), -/* 27 */ -/***/ (function(module, exports) { + if (flags.saveDev) { + exampleArgs.push('--dev'); + } + if (flags.savePeer) { + exampleArgs.push('--peer'); + } + if (flags.saveOptional) { + exampleArgs.push('--optional'); + } + if (flags.saveExact) { + exampleArgs.push('--exact'); + } + if (flags.saveTilde) { + exampleArgs.push('--tilde'); + } + let command = 'add'; + if (flags.global) { + error = 'globalFlagRemoved'; + command = 'global'; + } + throw new (_errors || _load_errors()).MessageError(reporter.lang(error, `yarn ${command} ${exampleArgs.join(' ')}`)); + } -exports = module.exports = SemVer; + yield install(config, reporter, flags, lockfile); + }); -// The debug function is excluded entirely from the minified version. -/* nomin */ var debug; -/* nomin */ if (typeof process === 'object' && - /* nomin */ process.env && - /* nomin */ process.env.NODE_DEBUG && - /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) - /* nomin */ debug = function() { - /* nomin */ var args = Array.prototype.slice.call(arguments, 0); - /* nomin */ args.unshift('SEMVER'); - /* nomin */ console.log.apply(console, args); - /* nomin */ }; -/* nomin */ else - /* nomin */ debug = function() {}; + return function run(_x21, _x22, _x23, _x24) { + return _ref13.apply(this, arguments); + }; +})(); -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0'; +let wrapLifecycle = exports.wrapLifecycle = (() => { + var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags, factory) { + yield config.executeLifecycleScript('preinstall'); -var MAX_LENGTH = 256; -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; + yield factory(); -// The actual regexps go on exports.re -var re = exports.re = []; -var src = exports.src = []; -var R = 0; + // npm behaviour, seems kinda funky but yay compatibility + yield config.executeLifecycleScript('install'); + yield config.executeLifecycleScript('postinstall'); -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. + if (!config.production) { + if (!config.disablePrepublish) { + yield config.executeLifecycleScript('prepublish'); + } + yield config.executeLifecycleScript('prepare'); + } + }); -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. + return function wrapLifecycle(_x25, _x26, _x27) { + return _ref14.apply(this, arguments); + }; +})(); -var NUMERICIDENTIFIER = R++; -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; -var NUMERICIDENTIFIERLOOSE = R++; -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; +var _index; -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. +function _load_index() { + return _index = _interopRequireDefault(__webpack_require__(167)); +} -var NONNUMERICIDENTIFIER = R++; -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; +var _errors; +function _load_errors() { + return _errors = __webpack_require__(3); +} -// ## Main Version -// Three dot-separated numeric identifiers. +var _integrityChecker; -var MAINVERSION = R++; -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')'; +function _load_integrityChecker() { + return _integrityChecker = _interopRequireDefault(__webpack_require__(158)); +} -var MAINVERSIONLOOSE = R++; -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; +var _lockfile; -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} -var PRERELEASEIDENTIFIER = R++; -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; +var _lockfile2; -var PRERELEASEIDENTIFIERLOOSE = R++; -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; +function _load_lockfile2() { + return _lockfile2 = __webpack_require__(12); +} +var _packageFetcher; -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. +function _load_packageFetcher() { + return _packageFetcher = _interopRequireWildcard(__webpack_require__(263)); +} -var PRERELEASE = R++; -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; +var _packageInstallScripts; -var PRERELEASELOOSE = R++; -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; +function _load_packageInstallScripts() { + return _packageInstallScripts = _interopRequireDefault(__webpack_require__(416)); +} -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. +var _packageCompatibility; -var BUILDIDENTIFIER = R++; -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; +function _load_packageCompatibility() { + return _packageCompatibility = _interopRequireWildcard(__webpack_require__(262)); +} -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. +var _packageResolver; -var BUILD = R++; -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; +function _load_packageResolver() { + return _packageResolver = _interopRequireDefault(__webpack_require__(264)); +} +var _packageLinker; -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. +function _load_packageLinker() { + return _packageLinker = _interopRequireDefault(__webpack_require__(159)); +} -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. +var _index2; -var FULL = R++; -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?'; +function _load_index2() { + return _index2 = __webpack_require__(34); +} -src[FULL] = '^' + FULLPLAIN + '$'; +var _index3; -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?'; +function _load_index3() { + return _index3 = __webpack_require__(35); +} -var LOOSE = R++; -src[LOOSE] = '^' + LOOSEPLAIN + '$'; +var _autoclean; -var GTLT = R++; -src[GTLT] = '((?:<|>)?=?)'; +function _load_autoclean() { + return _autoclean = __webpack_require__(253); +} -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++; -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; -var XRANGEIDENTIFIER = R++; -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; +var _constants; -var XRANGEPLAIN = R++; -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?'; +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} -var XRANGEPLAINLOOSE = R++; -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?'; +var _normalizePattern; -var XRANGE = R++; -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; -var XRANGELOOSE = R++; -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; +function _load_normalizePattern() { + return _normalizePattern = __webpack_require__(30); +} -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++; -src[LONETILDE] = '(?:~>?)'; +var _fs; -var TILDETRIM = R++; -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); -var tildeTrimReplace = '$1~'; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} -var TILDE = R++; -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; -var TILDELOOSE = R++; -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; +var _map; -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++; -src[LONECARET] = '(?:\\^)'; +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); +} -var CARETTRIM = R++; -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); -var caretTrimReplace = '$1^'; +var _yarnVersion; -var CARET = R++; -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; -var CARETLOOSE = R++; -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; +function _load_yarnVersion() { + return _yarnVersion = __webpack_require__(91); +} -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++; -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; -var COMPARATOR = R++; -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; +var _workspaceLayout; +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(80)); +} -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++; -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; +var _resolutionMap; -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); -var comparatorTrimReplace = '$1$2$3'; +function _load_resolutionMap() { + return _resolutionMap = _interopRequireDefault(__webpack_require__(267)); +} +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++; -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$'; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var HYPHENRANGELOOSE = R++; -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$'; +const emoji = __webpack_require__(298); -// Star ranges basically just allow anything at all. -var STAR = R++; -src[STAR] = '(<|>)?=?\\s*\\*'; +const invariant = __webpack_require__(7); +const path = __webpack_require__(0); +const semver = __webpack_require__(22); +const uuid = __webpack_require__(88); -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]); - if (!re[i]) - re[i] = new RegExp(src[i]); -} +const ONE_DAY = 1000 * 60 * 60 * 24; -exports.parse = parse; -function parse(version, loose) { - if (version instanceof SemVer) - return version; +/** + * Try and detect the installation method for Yarn and provide a command to update it with. + */ - if (typeof version !== 'string') - return null; +function getUpdateCommand(installationMethod) { + if (installationMethod === 'tar') { + return `curl -o- -L ${(_constants || _load_constants()).YARN_INSTALLER_SH} | bash`; + } - if (version.length > MAX_LENGTH) - return null; + if (installationMethod === 'homebrew') { + return 'brew upgrade yarn'; + } - var r = loose ? re[LOOSE] : re[FULL]; - if (!r.test(version)) - return null; + if (installationMethod === 'deb') { + return 'sudo apt-get update && sudo apt-get install yarn'; + } - try { - return new SemVer(version, loose); - } catch (er) { - return null; + if (installationMethod === 'rpm') { + return 'sudo yum install yarn'; } -} -exports.valid = valid; -function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; -} + if (installationMethod === 'npm') { + return 'npm update --global yarn'; + } + + if (installationMethod === 'chocolatey') { + return 'choco upgrade yarn'; + } + if (installationMethod === 'apk') { + return 'apk update && apk add -u yarn'; + } -exports.clean = clean; -function clean(version, loose) { - var s = parse(version.trim().replace(/^[=v]+/, ''), loose); - return s ? s.version : null; + return null; } -exports.SemVer = SemVer; +function getUpdateInstaller(installationMethod) { + // Windows + if (installationMethod === 'msi') { + return (_constants || _load_constants()).YARN_INSTALLER_MSI; + } -function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) - return version; - else - version = version.version; - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version); + return null; +} + +function normalizeFlags(config, rawFlags) { + const flags = { + // install + har: !!rawFlags.har, + ignorePlatform: !!rawFlags.ignorePlatform, + ignoreEngines: !!rawFlags.ignoreEngines, + ignoreScripts: !!rawFlags.ignoreScripts, + ignoreOptional: !!rawFlags.ignoreOptional, + force: !!rawFlags.force, + flat: !!rawFlags.flat, + lockfile: rawFlags.lockfile !== false, + pureLockfile: !!rawFlags.pureLockfile, + skipIntegrityCheck: !!rawFlags.skipIntegrityCheck, + frozenLockfile: !!rawFlags.frozenLockfile, + linkDuplicates: !!rawFlags.linkDuplicates, + checkFiles: !!rawFlags.checkFiles, + + // add + peer: !!rawFlags.peer, + dev: !!rawFlags.dev, + optional: !!rawFlags.optional, + exact: !!rawFlags.exact, + tilde: !!rawFlags.tilde + }; + + if (config.getOption('ignore-scripts')) { + flags.ignoreScripts = true; } - if (version.length > MAX_LENGTH) - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + if (config.getOption('ignore-platform')) { + flags.ignorePlatform = true; + } - if (!(this instanceof SemVer)) - return new SemVer(version, loose); + if (config.getOption('ignore-engines')) { + flags.ignoreEngines = true; + } - debug('SemVer', version, loose); - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); + if (config.getOption('ignore-optional')) { + flags.ignoreOptional = true; + } - if (!m) - throw new TypeError('Invalid Version: ' + version); + if (config.getOption('force')) { + flags.force = true; + } - this.raw = version; + return flags; +} - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; +class Install { + constructor(flags, config, reporter, lockfile) { + this.rootManifestRegistries = []; + this.rootPatternsToOrigin = (0, (_map || _load_map()).default)(); + this.lockfile = lockfile; + this.reporter = reporter; + this.config = config; + this.flags = normalizeFlags(config, flags); + this.resolutions = (0, (_map || _load_map()).default)(); // Legacy resolutions field used for flat install mode + this.resolutionMap = new (_resolutionMap || _load_resolutionMap()).default(config); // Selective resolutions for nested dependencies + this.resolver = new (_packageResolver || _load_packageResolver()).default(config, lockfile, this.resolutionMap); + this.integrityChecker = new (_integrityChecker || _load_integrityChecker()).default(config); + this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver); + this.scripts = new (_packageInstallScripts || _load_packageInstallScripts()).default(config, this.resolver, this.flags.force); + this.ignoreWorkspaces = false; + } - if (this.major > MAX_SAFE_INTEGER || this.major < 0) - throw new TypeError('Invalid major version') + /** + * Create a list of dependency requests from the current directories manifests. + */ - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) - throw new TypeError('Invalid minor version') + fetchRequestFromCwd() { + var _this = this; - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) - throw new TypeError('Invalid patch version') + let excludePatterns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + let ignoreUnusedPatterns = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const patterns = []; + const deps = []; + let resolutionDeps = []; + const manifest = {}; - // numberify any prerelease numeric ids - if (!m[4]) - this.prerelease = []; - else - this.prerelease = m[4].split('.').map(function(id) { - if (/^[0-9]+$/.test(id)) { - var num = +id; - if (num >= 0 && num < MAX_SAFE_INTEGER) - return num; + const ignorePatterns = []; + const usedPatterns = []; + let workspaceLayout; + + // exclude package names that are in install args + const excludeNames = []; + for (const pattern of excludePatterns) { + // can't extract a package name from this + if ((0, (_index3 || _load_index3()).getExoticResolver)(pattern)) { + continue; + } + + // extract the name + const parts = (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(pattern); + excludeNames.push(parts.name); } - return id; - }); - this.build = m[5] ? m[5].split('.') : []; - this.format(); -} + for (const registry of Object.keys((_index2 || _load_index2()).registries)) { + const filename = (_index2 || _load_index2()).registries[registry].filename; -SemVer.prototype.format = function() { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) - this.version += '-' + this.prerelease.join('.'); - return this.version; -}; + const loc = path.join(_this.config.lockfileFolder, filename); + if (!(yield (_fs || _load_fs()).exists(loc))) { + continue; + } -SemVer.prototype.toString = function() { - return this.version; -}; + _this.rootManifestRegistries.push(registry); -SemVer.prototype.compare = function(other) { - debug('SemVer.compare', this.version, this.loose, other); - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); + const projectManifestJson = yield _this.config.readJson(loc); + yield (0, (_index || _load_index()).default)(projectManifestJson, _this.config.lockfileFolder, _this.config, true); - return this.compareMain(other) || this.comparePre(other); -}; + Object.assign(_this.resolutions, projectManifestJson.resolutions); + Object.assign(manifest, projectManifestJson); -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); + _this.resolutionMap.init(_this.resolutions); + for (const packageName of Object.keys(_this.resolutionMap.resolutionsByPackage)) { + for (const _ref of _this.resolutionMap.resolutionsByPackage[packageName]) { + const pattern = _ref.pattern; - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch); -}; + resolutionDeps = [...resolutionDeps, { registry, pattern, optional: false, hint: 'resolution' }]; + } + } -SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); + const pushDeps = function (depType, manifest, _ref2, isUsed) { + let hint = _ref2.hint, + optional = _ref2.optional; - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) - return -1; - else if (!this.prerelease.length && other.prerelease.length) - return 1; - else if (!this.prerelease.length && !other.prerelease.length) - return 0; + if (ignoreUnusedPatterns && !isUsed) { + return; + } + // We only take unused dependencies into consideration to get deterministic hoisting. + // Since flat mode doesn't care about hoisting and everything is top level and specified then we can safely + // leave these out. + if (_this.flags.flat && !isUsed) { + return; + } + const depMap = manifest[depType]; + for (const name in depMap) { + if (excludeNames.indexOf(name) >= 0) { + continue; + } - var i = 0; - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - debug('prerelease compare', i, a, b); - if (a === undefined && b === undefined) - return 0; - else if (b === undefined) - return 1; - else if (a === undefined) - return -1; - else if (a === b) - continue; - else - return compareIdentifiers(a, b); - } while (++i); -}; + let pattern = name; + if (!_this.lockfile.getLocked(pattern)) { + // when we use --save we save the dependency to the lockfile with just the name rather than the + // version combo + pattern += '@' + depMap[name]; + } -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function(release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0; - this.patch = 0; - this.minor = 0; - this.major++; - this.inc('pre', identifier); - break; - case 'preminor': - this.prerelease.length = 0; - this.patch = 0; - this.minor++; - this.inc('pre', identifier); - break; - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0; - this.inc('patch', identifier); - this.inc('pre', identifier); - break; - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) - this.inc('patch', identifier); - this.inc('pre', identifier); - break; + // normalization made sure packages are mentioned only once + if (isUsed) { + usedPatterns.push(pattern); + } else { + ignorePatterns.push(pattern); + } - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) - this.major++; - this.minor = 0; - this.patch = 0; - this.prerelease = []; - break; - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) - this.minor++; - this.patch = 0; - this.prerelease = []; - break; - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) - this.patch++; - this.prerelease = []; - break; - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) - this.prerelease = [0]; - else { - var i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; + _this.rootPatternsToOrigin[pattern] = depType; + patterns.push(pattern); + deps.push({ pattern, registry, hint, optional }); + } + }; + + pushDeps('dependencies', projectManifestJson, { hint: null, optional: false }, true); + pushDeps('devDependencies', projectManifestJson, { hint: 'dev', optional: false }, !_this.config.production); + pushDeps('optionalDependencies', projectManifestJson, { hint: 'optional', optional: true }, true); + + if (_this.config.workspaceRootFolder && !_this.ignoreWorkspaces) { + const workspacesRoot = path.dirname(loc); + const workspaces = yield _this.config.resolveWorkspaces(workspacesRoot, projectManifestJson); + workspaceLayout = new (_workspaceLayout || _load_workspaceLayout()).default(workspaces, _this.config); + // add virtual manifest that depends on all workspaces, this way package hoisters and resolvers will work fine + const virtualDependencyManifest = { + _uid: '', + name: `workspace-aggregator-${uuid.v4()}`, + version: '1.0.0', + _registry: 'npm', + _loc: workspacesRoot, + dependencies: {} + }; + workspaceLayout.virtualManifestName = virtualDependencyManifest.name; + virtualDependencyManifest.dependencies = {}; + for (const workspaceName of Object.keys(workspaces)) { + virtualDependencyManifest.dependencies[workspaceName] = workspaces[workspaceName].manifest.version; } + const virtualDep = {}; + virtualDep[virtualDependencyManifest.name] = virtualDependencyManifest.version; + workspaces[virtualDependencyManifest.name] = { loc: workspacesRoot, manifest: virtualDependencyManifest }; + + pushDeps('workspaces', { workspaces: virtualDep }, { hint: 'workspaces', optional: false }, true); } - if (i === -1) // didn't increment anything - this.prerelease.push(0); + + break; } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) - this.prerelease = [identifier, 0]; - } else - this.prerelease = [identifier, 0]; + + // inherit root flat flag + if (manifest.flat) { + _this.flags.flat = true; } - break; - default: - throw new Error('invalid increment argument: ' + release); + return { + requests: [...resolutionDeps, ...deps], + patterns, + manifest, + usedPatterns, + ignorePatterns, + workspaceLayout + }; + })(); } - this.format(); - this.raw = this.version; - return this; -}; -exports.inc = inc; -function inc(version, release, loose, identifier) { - if (typeof(loose) === 'string') { - identifier = loose; - loose = undefined; + /** + * Sets the value of `ignoreWorkspaces` for install commands that should skip workspaces + */ + setIgnoreWorkspaces(ignoreWorkspaces) { + this.ignoreWorkspaces = ignoreWorkspaces; } - try { - return new SemVer(version, loose).inc(release, identifier).version; - } catch (er) { - return null; + /** + * TODO description + */ + + prepareRequests(requests) { + return requests; } -} -exports.diff = diff; -function diff(version1, version2) { - if (eq(version1, version2)) { - return null; - } else { - var v1 = parse(version1); - var v2 = parse(version2); - if (v1.prerelease.length || v2.prerelease.length) { - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return 'pre'+key; - } - } + preparePatterns(patterns) { + return patterns; + } + + bailout(patterns, workspaceLayout) { + var _this2 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (_this2.flags.skipIntegrityCheck || _this2.flags.force) { + return false; } - return 'prerelease'; - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return key; - } + const lockfileCache = _this2.lockfile.cache; + if (!lockfileCache) { + return false; + } + const lockfileClean = _this2.lockfile.parseResultType === 'success'; + const match = yield _this2.integrityChecker.check(patterns, lockfileCache, _this2.flags, workspaceLayout); + if (_this2.flags.frozenLockfile && (!lockfileClean || match.missingPatterns.length > 0)) { + throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('frozenLockfileError')); } - } - } -} -exports.compareIdentifiers = compareIdentifiers; + const haveLockfile = yield (_fs || _load_fs()).exists(path.join(_this2.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME)); -var numeric = /^[0-9]+$/; -function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); + if (match.integrityMatches && haveLockfile && lockfileClean) { + _this2.reporter.success(_this2.reporter.lang('upToDate')); + return true; + } - if (anum && bnum) { - a = +a; - b = +b; - } + if (match.integrityFileMissing && haveLockfile) { + // Integrity file missing, force script installations + _this2.scripts.setForce(true); + return false; + } - return (anum && !bnum) ? -1 : - (bnum && !anum) ? 1 : - a < b ? -1 : - a > b ? 1 : - 0; -} + if (!patterns.length && !match.integrityFileMissing) { + _this2.reporter.success(_this2.reporter.lang('nothingToInstall')); + yield _this2.createEmptyManifestFolders(); + yield _this2.saveLockfileAndIntegrity(patterns, workspaceLayout); + return true; + } -exports.rcompareIdentifiers = rcompareIdentifiers; -function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); -} + return false; + })(); + } -exports.major = major; -function major(a, loose) { - return new SemVer(a, loose).major; -} + /** + * Produce empty folders for all used root manifests. + */ -exports.minor = minor; -function minor(a, loose) { - return new SemVer(a, loose).minor; -} + createEmptyManifestFolders() { + var _this3 = this; -exports.patch = patch; -function patch(a, loose) { - return new SemVer(a, loose).patch; -} + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (_this3.config.modulesFolder) { + // already created + return; + } -exports.compare = compare; -function compare(a, b, loose) { - return new SemVer(a, loose).compare(b); -} + for (const registryName of _this3.rootManifestRegistries) { + const folder = _this3.config.registries[registryName].folder; -exports.compareLoose = compareLoose; -function compareLoose(a, b) { - return compare(a, b, true); -} + yield (_fs || _load_fs()).mkdirp(path.join(_this3.config.lockfileFolder, folder)); + } + })(); + } -exports.rcompare = rcompare; -function rcompare(a, b, loose) { - return compare(b, a, loose); -} + /** + * TODO description + */ -exports.sort = sort; -function sort(list, loose) { - return list.sort(function(a, b) { - return exports.compare(a, b, loose); - }); -} + markIgnored(patterns) { + for (const pattern of patterns) { + const manifest = this.resolver.getStrictResolvedPattern(pattern); + const ref = manifest._reference; + invariant(ref, 'expected package reference'); -exports.rsort = rsort; -function rsort(list, loose) { - return list.sort(function(a, b) { - return exports.rcompare(a, b, loose); - }); -} + // just mark the package as ignored. if the package is used by a required package, the hoister + // will take care of that. + ref.ignore = true; + } + } -exports.gt = gt; -function gt(a, b, loose) { - return compare(a, b, loose) > 0; -} + /** + * TODO description + */ -exports.lt = lt; -function lt(a, b, loose) { - return compare(a, b, loose) < 0; -} + init() { + var _this4 = this; -exports.eq = eq; -function eq(a, b, loose) { - return compare(a, b, loose) === 0; -} + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this4.checkUpdate(); -exports.neq = neq; -function neq(a, b, loose) { - return compare(a, b, loose) !== 0; -} - -exports.gte = gte; -function gte(a, b, loose) { - return compare(a, b, loose) >= 0; -} + // warn if we have a shrinkwrap + if (yield (_fs || _load_fs()).exists(path.join(_this4.config.lockfileFolder, 'npm-shrinkwrap.json'))) { + _this4.reporter.warn(_this4.reporter.lang('shrinkwrapWarning')); + } -exports.lte = lte; -function lte(a, b, loose) { - return compare(a, b, loose) <= 0; -} + let flattenedTopLevelPatterns = []; + const steps = []; -exports.cmp = cmp; -function cmp(a, op, b, loose) { - var ret; - switch (op) { - case '===': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a === b; - break; - case '!==': - if (typeof a === 'object') a = a.version; - if (typeof b === 'object') b = b.version; - ret = a !== b; - break; - case '': case '=': case '==': ret = eq(a, b, loose); break; - case '!=': ret = neq(a, b, loose); break; - case '>': ret = gt(a, b, loose); break; - case '>=': ret = gte(a, b, loose); break; - case '<': ret = lt(a, b, loose); break; - case '<=': ret = lte(a, b, loose); break; - default: throw new TypeError('Invalid operator: ' + op); - } - return ret; -} + var _ref3 = yield _this4.fetchRequestFromCwd(); -exports.Comparator = Comparator; -function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) - return comp; - else - comp = comp.value; - } + const depRequests = _ref3.requests, + rawPatterns = _ref3.patterns, + ignorePatterns = _ref3.ignorePatterns, + workspaceLayout = _ref3.workspaceLayout, + manifest = _ref3.manifest; - if (!(this instanceof Comparator)) - return new Comparator(comp, loose); + let topLevelPatterns = []; - debug('comparator', comp, loose); - this.loose = loose; - this.parse(comp); + const artifacts = yield _this4.integrityChecker.getArtifacts(); + if (artifacts) { + _this4.linker.setArtifacts(artifacts); + _this4.scripts.setArtifacts(artifacts); + } - if (this.semver === ANY) - this.value = ''; - else - this.value = this.operator + this.semver.version; + if (!_this4.flags.ignoreEngines && typeof manifest.engines === 'object') { + steps.push((() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this4.reporter.step(curr, total, _this4.reporter.lang('checkingManifest'), emoji.get('mag')); + yield (_packageCompatibility || _load_packageCompatibility()).checkOne((0, (_extends2 || _load_extends()).default)({ _reference: {} }, manifest), _this4.config, _this4.flags.ignoreEngines); + }); - debug('comp', this); -} + return function (_x3, _x4) { + return _ref4.apply(this, arguments); + }; + })()); + } -var ANY = {}; -Comparator.prototype.parse = function(comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); + steps.push((() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this4.reporter.step(curr, total, _this4.reporter.lang('resolvingPackages'), emoji.get('mag')); + yield _this4.resolver.init(_this4.prepareRequests(depRequests), { + isFlat: _this4.flags.flat, + isFrozen: _this4.flags.frozenLockfile, + workspaceLayout + }); + topLevelPatterns = _this4.preparePatterns(rawPatterns); + flattenedTopLevelPatterns = yield _this4.flatten(topLevelPatterns); + return { bailout: yield _this4.bailout(topLevelPatterns, workspaceLayout) }; + }); - if (!m) - throw new TypeError('Invalid comparator: ' + comp); + return function (_x5, _x6) { + return _ref5.apply(this, arguments); + }; + })()); - this.operator = m[1]; - if (this.operator === '=') - this.operator = ''; + steps.push((() => { + var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this4.markIgnored(ignorePatterns); + _this4.reporter.step(curr, total, _this4.reporter.lang('fetchingPackages'), emoji.get('truck')); + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this4.resolver.getManifests(), _this4.config); + _this4.resolver.updateManifests(manifests); + yield (_packageCompatibility || _load_packageCompatibility()).check(_this4.resolver.getManifests(), _this4.config, _this4.flags.ignoreEngines); + }); - // if it literally is just '>' or '' then allow anything. - if (!m[2]) - this.semver = ANY; - else - this.semver = new SemVer(m[2], this.loose); -}; + return function (_x7, _x8) { + return _ref6.apply(this, arguments); + }; + })()); -Comparator.prototype.toString = function() { - return this.value; -}; + steps.push((() => { + var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + // remove integrity hash to make this operation atomic + yield _this4.integrityChecker.removeIntegrityFile(); + _this4.reporter.step(curr, total, _this4.reporter.lang('linkingDependencies'), emoji.get('link')); + yield _this4.linker.init(flattenedTopLevelPatterns, workspaceLayout, { + linkDuplicates: _this4.flags.linkDuplicates, + ignoreOptional: _this4.flags.ignoreOptional + }); + }); -Comparator.prototype.test = function(version) { - debug('Comparator.test', version, this.loose); + return function (_x9, _x10) { + return _ref7.apply(this, arguments); + }; + })()); - if (this.semver === ANY) - return true; + steps.push((() => { + var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this4.reporter.step(curr, total, _this4.flags.force ? _this4.reporter.lang('rebuildingPackages') : _this4.reporter.lang('buildingFreshPackages'), emoji.get('page_with_curl')); - if (typeof version === 'string') - version = new SemVer(version, this.loose); + if (_this4.flags.ignoreScripts) { + _this4.reporter.warn(_this4.reporter.lang('ignoredScripts')); + } else { + yield _this4.scripts.init(flattenedTopLevelPatterns); + } + }); - return cmp(version, this.operator, this.semver, this.loose); -}; + return function (_x11, _x12) { + return _ref8.apply(this, arguments); + }; + })()); + if (_this4.flags.har) { + steps.push((() => { + var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + const formattedDate = new Date().toISOString().replace(/:/g, '-'); + const filename = `yarn-install_${formattedDate}.har`; + _this4.reporter.step(curr, total, _this4.reporter.lang('savingHar', filename), emoji.get('black_circle_for_record')); + yield _this4.config.requestManager.saveHar(filename); + }); -exports.Range = Range; -function Range(range, loose) { - if ((range instanceof Range) && range.loose === loose) - return range; + return function (_x13, _x14) { + return _ref9.apply(this, arguments); + }; + })()); + } - if (!(this instanceof Range)) - return new Range(range, loose); + if (yield _this4.shouldClean()) { + steps.push((() => { + var _ref10 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (curr, total) { + _this4.reporter.step(curr, total, _this4.reporter.lang('cleaningModules'), emoji.get('recycle')); + yield (0, (_autoclean || _load_autoclean()).clean)(_this4.config, _this4.reporter); + }); - this.loose = loose; + return function (_x15, _x16) { + return _ref10.apply(this, arguments); + }; + })()); + } - // First, split based on boolean or || - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function(range) { - return this.parseRange(range.trim()); - }, this).filter(function(c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); + let currentStep = 0; + for (const step of steps) { + const stepResult = yield step(++currentStep, steps.length); + if (stepResult && stepResult.bailout) { + _this4.maybeOutputUpdate(); + return flattenedTopLevelPatterns; + } + } - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); + // fin! + // The second condition is to make sure lockfile can be updated when running `remove` command. + if (topLevelPatterns.length || (yield (_fs || _load_fs()).exists(path.join(_this4.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME)))) { + yield _this4.saveLockfileAndIntegrity(topLevelPatterns, workspaceLayout); + } else { + _this4.reporter.info(_this4.reporter.lang('notSavedLockfileNoDependencies')); + } + _this4.maybeOutputUpdate(); + _this4.config.requestManager.clearCache(); + return flattenedTopLevelPatterns; + })(); } - this.format(); -} - -Range.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; -}; + /** + * Check if we should run the cleaning step. + */ -Range.prototype.toString = function() { - return this.range; -}; + shouldClean() { + return (_fs || _load_fs()).exists(path.join(this.config.lockfileFolder, (_constants || _load_constants()).CLEAN_FILENAME)); + } -Range.prototype.parseRange = function(range) { - var loose = this.loose; - range = range.trim(); - debug('range', range, loose); - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - debug('comparator trim', range, re[COMPARATORTRIM]); + /** + * TODO + */ - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); + flatten(patterns) { + var _this5 = this; - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (!_this5.flags.flat) { + return patterns; + } - // normalize spaces - range = range.split(/\s+/).join(' '); + const flattenedPatterns = []; - // At this point, the range is completely trimmed and - // ready to be split into comparators. + for (const name of _this5.resolver.getAllDependencyNamesByLevelOrder(patterns)) { + const infos = _this5.resolver.getAllInfoForPackageName(name).filter(function (manifest) { + const ref = manifest._reference; + invariant(ref, 'expected package reference'); + return !ref.ignore; + }); - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function(comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function(comp) { - return !!comp.match(compRe); - }); - } - set = set.map(function(comp) { - return new Comparator(comp, loose); - }); + if (infos.length === 0) { + continue; + } - return set; -}; + if (infos.length === 1) { + // single version of this package + // take out a single pattern as multiple patterns may have resolved to this package + flattenedPatterns.push(_this5.resolver.patternsByPackage[name][0]); + continue; + } -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, loose) { - return new Range(range, loose).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(' ').trim().split(' '); - }); -} + const options = infos.map(function (info) { + const ref = info._reference; + invariant(ref, 'expected reference'); + return { + // TODO `and is required by {PARENT}`, + name: _this5.reporter.lang('manualVersionResolutionOption', ref.patterns.join(', '), info.version), -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator(comp, loose) { - debug('comp', comp); - comp = replaceCarets(comp, loose); - debug('caret', comp); - comp = replaceTildes(comp, loose); - debug('tildes', comp); - comp = replaceXRanges(comp, loose); - debug('xrange', comp); - comp = replaceStars(comp, loose); - debug('stars', comp); - return comp; -} + value: info.version + }; + }); + const versions = infos.map(function (info) { + return info.version; + }); + let version; -function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; -} + const resolutionVersion = _this5.resolutions[name]; + if (resolutionVersion && versions.indexOf(resolutionVersion) >= 0) { + // use json `resolution` version + version = resolutionVersion; + } else { + version = yield _this5.reporter.select(_this5.reporter.lang('manualVersionResolution', name), _this5.reporter.lang('answer'), options); + _this5.resolutions[name] = version; + } -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); -} + flattenedPatterns.push(_this5.resolver.collapseAllVersionsOfPackage(name, version)); + } -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; + // save resolutions to their appropriate root manifest + if (Object.keys(_this5.resolutions).length) { + const manifests = yield _this5.config.getRootManifests(); - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; + for (const name in _this5.resolutions) { + const version = _this5.resolutions[name]; - debug('tilde return', ret); - return ret; - }); -} + const patterns = _this5.resolver.patternsByPackage[name]; + if (!patterns) { + continue; + } -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} + let manifest; + for (const pattern of patterns) { + manifest = _this5.resolver.getResolvedPattern(pattern); + if (manifest) { + break; + } + } + invariant(manifest, 'expected manifest'); -function replaceCaret(comp, loose) { - debug('caret', comp, loose); - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; + const ref = manifest._reference; + invariant(ref, 'expected reference'); - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - else - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0'; - } else { - debug('no pr'); - if (M === '0') { - if (m === '0') - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1); - else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0'; - } else - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0'; - } + const object = manifests[ref.registry].object; + object.resolutions = object.resolutions || {}; + object.resolutions[name] = version; + } - debug('caret return', ret); - return ret; - }); -} + yield _this5.config.saveRootManifests(manifests); + } -function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} + return flattenedPatterns; + })(); + } -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; + /** + * Remove offline tarballs that are no longer required + */ - if (gtlt === '=' && anyX) - gtlt = ''; + pruneOfflineMirror(lockfile) { + var _this6 = this; - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0'; - } else { - // nothing is forbidden - ret = '*'; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const mirror = _this6.config.getOfflineMirrorPath(); + if (!mirror) { + return; } - } else if (gtlt && anyX) { - // replace X with 0 - if (xm) - m = 0; - if (xp) - p = 0; - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>='; - if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; + const requiredTarballs = new Set(); + for (const dependency in lockfile) { + const resolved = lockfile[dependency].resolved; + if (resolved) { + const basename = path.basename(resolved.split('#')[0]); + if (dependency[0] === '@' && basename[0] !== '@') { + requiredTarballs.add(`${dependency.split('/')[0]}-${basename}`); + } + requiredTarballs.add(basename); } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<'; - if (xm) - M = +M + 1; - else - m = +m + 1; } - ret = gtlt + M + '.' + m + '.' + p; - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; - } + const mirrorFiles = yield (_fs || _load_fs()).walk(mirror); + for (const file of mirrorFiles) { + const isTarball = path.extname(file.basename) === '.tgz'; + if (isTarball && !requiredTarballs.has(file.basename)) { + yield (_fs || _load_fs()).unlink(file.absolute); + } + } + })(); + } - debug('xRange return', ret); + /** + * Save updated integrity and lockfiles. + */ - return ret; - }); -} + saveLockfileAndIntegrity(patterns, workspaceLayout) { + var _this7 = this; -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const resolvedPatterns = {}; + Object.keys(_this7.resolver.patterns).forEach(function (pattern) { + if (!workspaceLayout || !workspaceLayout.getManifestByPattern(pattern)) { + resolvedPatterns[pattern] = _this7.resolver.patterns[pattern]; + } + }); -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { + // TODO this code is duplicated in a few places, need a common way to filter out workspace patterns from lockfile + patterns = patterns.filter(function (p) { + return !workspaceLayout || !workspaceLayout.getManifestByPattern(p); + }); - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0'; - else - from = '>=' + from; + const lockfileBasedOnResolver = _this7.lockfile.getLockfile(resolvedPatterns); - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; + if (_this7.config.pruneOfflineMirror) { + yield _this7.pruneOfflineMirror(lockfileBasedOnResolver); + } - return (from + ' ' + to).trim(); -} + // write integrity hash + yield _this7.integrityChecker.save(patterns, lockfileBasedOnResolver, _this7.flags, workspaceLayout, _this7.scripts.getArtifacts()); + // --no-lockfile or --pure-lockfile flag + if (_this7.flags.lockfile === false || _this7.flags.pureLockfile) { + return; + } -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; + const lockFileHasAllPatterns = patterns.every(function (p) { + return _this7.lockfile.getLocked(p); + }); + const lockfilePatternsMatch = Object.keys(_this7.lockfile.cache || {}).every(function (p) { + return lockfileBasedOnResolver[p]; + }); + const resolverPatternsAreSameAsInLockfile = Object.keys(lockfileBasedOnResolver).every(function (pattern) { + const manifest = _this7.lockfile.getLocked(pattern); + return manifest && manifest.resolved === lockfileBasedOnResolver[pattern].resolved; + }); - if (typeof version === 'string') - version = new SemVer(version, this.loose); + // remove command is followed by install with force, lockfile will be rewritten in any case then + if (!_this7.flags.force && _this7.lockfile.parseResultType === 'success' && lockFileHasAllPatterns && lockfilePatternsMatch && resolverPatternsAreSameAsInLockfile && patterns.length) { + return; + } - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; + // build lockfile location + const loc = path.join(_this7.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME); + + // write lockfile + const lockSource = (0, (_lockfile2 || _load_lockfile2()).stringify)(lockfileBasedOnResolver, false, _this7.config.enableLockfileVersions); + yield (_fs || _load_fs()).writeFilePreservingEol(loc, lockSource); + + _this7._logSuccessSaveLockfile(); + })(); } - return false; -}; -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; + _logSuccessSaveLockfile() { + this.reporter.success(this.reporter.lang('savedLockfile')); } - if (version.prerelease.length) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (var i = 0; i < set.length; i++) { - debug(set[i].semver); - if (set[i].semver === ANY) - continue; + /** + * Load the dependency graph of the current install. Only does package resolving and wont write to the cwd. + */ + hydrate(ignoreUnusedPatterns) { + var _this8 = this; - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver; - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) - return true; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const request = yield _this8.fetchRequestFromCwd([], ignoreUnusedPatterns); + const depRequests = request.requests, + rawPatterns = request.patterns, + ignorePatterns = request.ignorePatterns, + workspaceLayout = request.workspaceLayout; + + + yield _this8.resolver.init(depRequests, { + isFlat: _this8.flags.flat, + isFrozen: _this8.flags.frozenLockfile, + workspaceLayout + }); + yield _this8.flatten(rawPatterns); + _this8.markIgnored(ignorePatterns); + + // fetch packages, should hit cache most of the time + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this8.resolver.getManifests(), _this8.config); + _this8.resolver.updateManifests(manifests); + yield (_packageCompatibility || _load_packageCompatibility()).check(_this8.resolver.getManifests(), _this8.config, _this8.flags.ignoreEngines); + + // expand minimal manifests + for (const manifest of _this8.resolver.getManifests()) { + const ref = manifest._reference; + invariant(ref, 'expected reference'); + const type = ref.remote.type; + // link specifier won't ever hit cache + + let loc = ''; + if (type === 'link') { + continue; + } else if (type === 'workspace') { + if (!ref.remote.reference) { + continue; + } + loc = ref.remote.reference; + } else { + loc = _this8.config.generateHardModulePath(ref); + } + const newPkg = yield _this8.config.readManifest(loc); + yield _this8.resolver.updateManifest(ref, newPkg); } - } - // Version has a -pre, but it's not one of the ones we like. - return false; + return request; + })(); } - return true; -} + /** + * Check for updates every day and output a nag message if there's a newer version. + */ -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; + checkUpdate() { + if (this.config.nonInteractive) { + // don't show upgrade dialog on CI or non-TTY terminals + return; + } + + // don't check if disabled + if (this.config.getOption('disable-self-update-check')) { + return; + } + + // only check for updates once a day + const lastUpdateCheck = Number(this.config.getOption('lastUpdateCheck')) || 0; + if (lastUpdateCheck && Date.now() - lastUpdateCheck < ONE_DAY) { + return; + } + + // don't bug for updates on tagged releases + if ((_yarnVersion || _load_yarnVersion()).version.indexOf('-') >= 0) { + return; + } + + this._checkUpdate().catch(() => { + // swallow errors + }); } - return range.test(version); -} -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return rcompare(a, b, loose); - })[0] || null; -} + _checkUpdate() { + var _this9 = this; -exports.minSatisfying = minSatisfying; -function minSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return compare(a, b, loose); - })[0] || null; -} + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let latestVersion = yield _this9.config.requestManager.request({ + url: (_constants || _load_constants()).SELF_UPDATE_VERSION_URL + }); + invariant(typeof latestVersion === 'string', 'expected string'); + latestVersion = latestVersion.trim(); + if (!semver.valid(latestVersion)) { + return; + } -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; + // ensure we only check for updates periodically + _this9.config.registries.yarn.saveHomeConfig({ + lastUpdateCheck: Date.now() + }); + + if (semver.gt(latestVersion, (_yarnVersion || _load_yarnVersion()).version)) { + const installationMethod = yield (0, (_yarnVersion || _load_yarnVersion()).getInstallationMethod)(); + _this9.maybeOutputUpdate = function () { + _this9.reporter.warn(_this9.reporter.lang('yarnOutdated', latestVersion, (_yarnVersion || _load_yarnVersion()).version)); + + const command = getUpdateCommand(installationMethod); + if (command) { + _this9.reporter.info(_this9.reporter.lang('yarnOutdatedCommand')); + _this9.reporter.command(command); + } else { + const installer = getUpdateInstaller(installationMethod); + if (installer) { + _this9.reporter.info(_this9.reporter.lang('yarnOutdatedInstaller', installer)); + } + } + }; + } + })(); } + + /** + * Method to override with a possible upgrade message. + */ + + maybeOutputUpdate() {} } -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); +exports.Install = Install; +function hasWrapper(commander, args) { + return true; } -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); +function setFlags(commander) { + commander.usage('install [flags]'); + commander.option('-g, --global', 'DEPRECATED'); + commander.option('-S, --save', 'DEPRECATED - save package to your `dependencies`'); + commander.option('-D, --save-dev', 'DEPRECATED - save package to your `devDependencies`'); + commander.option('-P, --save-peer', 'DEPRECATED - save package to your `peerDependencies`'); + commander.option('-O, --save-optional', 'DEPRECATED - save package to your `optionalDependencies`'); + commander.option('-E, --save-exact', 'DEPRECATED'); + commander.option('-T, --save-tilde', 'DEPRECATED'); } -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); +/***/ }), +/* 32 */ +/***/ (function(module, exports) { - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } +module.exports = {}; - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; - } +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. +// Thank's IE8 for his funny defineProperty +module.exports = !__webpack_require__(82)(function(){ + return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; +}); - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; +/***/ }), +/* 34 */ +/***/ (function(module, exports, __webpack_require__) { - var high = null; - var low = null; +"use strict"; - comparators.forEach(function(comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.registryNames = exports.registries = undefined; - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; +var _yarnRegistry; + +function _load_yarnRegistry() { + return _yarnRegistry = _interopRequireDefault(__webpack_require__(419)); } -exports.prerelease = prerelease; -function prerelease(version, loose) { - var parsed = parse(version, loose); - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null; +var _npmRegistry; + +function _load_npmRegistry() { + return _npmRegistry = _interopRequireDefault(__webpack_require__(52)); } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const registries = exports.registries = { + npm: (_npmRegistry || _load_npmRegistry()).default, + yarn: (_yarnRegistry || _load_yarnRegistry()).default +}; + +const registryNames = exports.registryNames = Object.keys(registries); /***/ }), -/* 28 */ +/* 35 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -22405,545 +22815,227 @@ function prerelease(version, loose) { Object.defineProperty(exports, "__esModule", { value: true }); +exports.hostedGit = exports.registries = undefined; +exports.getExoticResolver = getExoticResolver; +exports.hostedGitFragmentToGitUrl = hostedGitFragmentToGitUrl; -var _asyncToGenerator2; +var _baseResolver; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function _load_baseResolver() { + return _baseResolver = _interopRequireDefault(__webpack_require__(95)); } -var _slicedToArray2; +var _npmResolver; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); +function _load_npmResolver() { + return _npmResolver = _interopRequireDefault(__webpack_require__(164)); } -var _validate; +var _yarnResolver; -function _load_validate() { - return _validate = __webpack_require__(63); +function _load_yarnResolver() { + return _yarnResolver = _interopRequireDefault(__webpack_require__(270)); } -var _wrapper; +var _gitResolver; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); +function _load_gitResolver() { + return _gitResolver = _interopRequireDefault(__webpack_require__(96)); } -var _packageReference; +var _tarballResolver; -function _load_packageReference() { - return _packageReference = _interopRequireDefault(__webpack_require__(362)); +function _load_tarballResolver() { + return _tarballResolver = _interopRequireDefault(__webpack_require__(432)); } -var _index; +var _githubResolver; -function _load_index() { - return _index = _interopRequireWildcard(__webpack_require__(53)); +function _load_githubResolver() { + return _githubResolver = _interopRequireDefault(__webpack_require__(268)); } -var _index2; +var _fileResolver; -function _load_index2() { - return _index2 = __webpack_require__(53); +function _load_fileResolver() { + return _fileResolver = _interopRequireDefault(__webpack_require__(162)); } -var _errors; +var _linkResolver; -function _load_errors() { - return _errors = __webpack_require__(3); +function _load_linkResolver() { + return _linkResolver = _interopRequireDefault(__webpack_require__(269)); } -var _misc; +var _gitlabResolver; -function _load_misc() { - return _misc = __webpack_require__(10); +function _load_gitlabResolver() { + return _gitlabResolver = _interopRequireDefault(__webpack_require__(430)); } -var _constants; +var _gistResolver; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); +function _load_gistResolver() { + return _gistResolver = _interopRequireDefault(__webpack_require__(163)); } -var _version; +var _bitbucketResolver; -function _load_version() { - return _version = _interopRequireWildcard(__webpack_require__(131)); +function _load_bitbucketResolver() { + return _bitbucketResolver = _interopRequireDefault(__webpack_require__(429)); } -var _workspaceResolver; +var _hostedGitResolver; -function _load_workspaceResolver() { - return _workspaceResolver = _interopRequireDefault(__webpack_require__(375)); +function _load_hostedGitResolver() { + return _hostedGitResolver = __webpack_require__(78); } -var _fs; +var _registryResolver; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); +function _load_registryResolver() { + return _registryResolver = _interopRequireDefault(__webpack_require__(431)); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const path = __webpack_require__(1); -const invariant = __webpack_require__(5); -const semver = __webpack_require__(27); +const registries = exports.registries = { + npm: (_npmResolver || _load_npmResolver()).default, + yarn: (_yarnResolver || _load_yarnResolver()).default +}; -class PackageRequest { - constructor(req, resolver) { - this.parentRequest = req.parentRequest; - this.lockfile = resolver.lockfile; - this.registry = req.registry; - this.reporter = resolver.reporter; - this.resolver = resolver; - this.optional = req.optional; - this.pattern = req.pattern; - this.config = resolver.config; - this.foundInfo = null; +// - resolver.usedRegistries.add(req.registry); +const exotics = new Set([(_gitResolver || _load_gitResolver()).default, (_tarballResolver || _load_tarballResolver()).default, (_githubResolver || _load_githubResolver()).default, (_fileResolver || _load_fileResolver()).default, (_linkResolver || _load_linkResolver()).default, (_gitlabResolver || _load_gitlabResolver()).default, (_gistResolver || _load_gistResolver()).default, (_bitbucketResolver || _load_bitbucketResolver()).default]); + +function getExoticResolver(pattern) { + for (const Resolver of exotics) { + if (Resolver.isVersion(pattern)) { + return Resolver; + } } + return null; +} - static getExoticResolver(pattern) { - // TODO make this type more refined - for (const _ref of (0, (_misc || _load_misc()).entries)((_index || _load_index()).exotics)) { - var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); +// - const Resolver = _ref2[1]; +const hostedGit = exports.hostedGit = { + github: (_githubResolver || _load_githubResolver()).default, + gitlab: (_gitlabResolver || _load_gitlabResolver()).default, + bitbucket: (_bitbucketResolver || _load_bitbucketResolver()).default +}; - if (Resolver.isVersion(pattern)) { - return Resolver; - } +function hostedGitFragmentToGitUrl(fragment, reporter) { + for (const key in hostedGit) { + const Resolver = hostedGit[key]; + if (Resolver.isVersion(fragment)) { + return Resolver.getGitHTTPUrl((0, (_hostedGitResolver || _load_hostedGitResolver()).explodeHostedGitFragment)(fragment, reporter)); } - return null; } - getParentNames() { - const chain = []; + return fragment; +} - let request = this.parentRequest; - while (request) { - const info = this.resolver.getStrictResolvedPattern(request.pattern); - chain.unshift(info.name); +// - request = request.parentRequest; - } +for (const key in registries) { + var _class, _temp; - return chain; - } + const RegistryResolver = registries[key]; - getLocked(remoteType) { - // always prioritise root lockfile - const shrunk = this.lockfile.getLocked(this.pattern); + exotics.add((_temp = _class = class extends (_registryResolver || _load_registryResolver()).default {}, _class.protocol = key, _class.factory = RegistryResolver, _temp)); +} - if (shrunk && shrunk.resolved) { - const resolvedParts = (_version || _load_version()).explodeHashedUrl(shrunk.resolved); - // If it's a private git url set remote to 'git'. - const preferredRemoteType = resolvedParts.url.startsWith('git+ssh://') ? 'git' : remoteType; +/***/ }), +/* 36 */ +/***/ (function(module, exports, __webpack_require__) { - return { - name: shrunk.name, - version: shrunk.version, - _uid: shrunk.uid, - _remote: { - resolved: shrunk.resolved, - type: preferredRemoteType, - reference: resolvedParts.url, - hash: resolvedParts.hash, - registry: shrunk.registry - }, - optionalDependencies: shrunk.optionalDependencies, - dependencies: shrunk.dependencies - }; - } else { - return null; - } - } - - /** - * If the input pattern matches a registry one then attempt to find it on the registry. - * Otherwise fork off to an exotic resolver if one matches. - */ - - findVersionOnRegistry(pattern) { - var _this = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - var _ref3 = yield _this.normalize(pattern); - - const range = _ref3.range, - name = _ref3.name; - - - const exoticResolver = PackageRequest.getExoticResolver(range); - - if (exoticResolver) { - let data = yield _this.findExoticVersionInfo(exoticResolver, range); - - // clone data as we're manipulating it in place and this could be resolved multiple - // times - data = Object.assign({}, data); - - // this is so the returned package response uses the overridden name. ie. if the - // package's actual name is `bar`, but it's been specified in the manifest like: - // "foo": "http://foo.com/bar.tar.gz" - // then we use the foo name - data.name = name; - - return data; - } - - const Resolver = _this.getRegistryResolver(); - const resolver = new Resolver(_this, name, range); - return resolver.resolve(); - })(); - } - - /** - * Get the registry resolver associated with this package request. - */ - - getRegistryResolver() { - const Resolver = (_index2 || _load_index2()).registries[this.registry]; - if (Resolver) { - return Resolver; - } else { - throw new (_errors || _load_errors()).MessageError(this.reporter.lang('unknownRegistryResolver', this.registry)); - } - } - - normalizeRange(pattern) { - var _this2 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (pattern.includes(':') || pattern.includes('@') || PackageRequest.getExoticResolver(pattern)) { - return Promise.resolve(pattern); - } - - if (yield (_fs || _load_fs()).exists(path.join(_this2.config.cwd, pattern))) { - return Promise.resolve(`file:${pattern}`); - } - - return Promise.resolve(pattern); - })(); - } - - normalize(pattern) { - var _this3 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - var _PackageRequest$norma = PackageRequest.normalizePattern(pattern); +"use strict"; - const name = _PackageRequest$norma.name, - range = _PackageRequest$norma.range, - hasVersion = _PackageRequest$norma.hasVersion; - const newRange = yield _this3.normalizeRange(range); - return { name, range: newRange, hasVersion }; - })(); - } +exports.__esModule = true; - /** - * Explode and normalize a pattern into it's name and range. - */ +var _assign = __webpack_require__(449); - static normalizePattern(pattern) { - let hasVersion = false; - let range = 'latest'; - let name = pattern; +var _assign2 = _interopRequireDefault(_assign); - // if we're a scope then remove the @ and add it back later - let isScoped = false; - if (name[0] === '@') { - isScoped = true; - name = name.slice(1); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // take first part as the name - const parts = name.split('@'); - if (parts.length > 1) { - name = parts.shift(); - range = parts.join('@'); +exports.default = _assign2.default || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - if (range) { - hasVersion = true; - } else { - range = '*'; + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; } } - - // add back @ scope suffix - if (isScoped) { - name = `@${name}`; - } - - return { name, range, hasVersion }; } - /** - * Construct an exotic resolver instance with the input `ExoticResolver` and `range`. - */ - - findExoticVersionInfo(ExoticResolver, range) { - const resolver = new ExoticResolver(this, range); - return resolver.resolve(); - } - - /** - * If the current pattern matches an exotic resolver then delegate to it or else try - * the registry. - */ - - findVersionInfo() { - const exoticResolver = PackageRequest.getExoticResolver(this.pattern); - - if (exoticResolver) { - return this.findExoticVersionInfo(exoticResolver, this.pattern); - } else if ((_workspaceResolver || _load_workspaceResolver()).default.isWorkspace(this.pattern, this.resolver.workspaceLayout)) { - invariant(this.resolver.workspaceLayout, 'expected workspaceLayout'); - const resolver = new (_workspaceResolver || _load_workspaceResolver()).default(this, this.pattern, this.resolver.workspaceLayout); - return resolver.resolve(); - } else { - return this.findVersionOnRegistry(this.pattern); - } - } - - reportResolvedRangeMatch(info, resolved) {} - - /** - * Do the final resolve of a package that had a match with an existing version. - * After all unique versions have been discovered, so the best available version - * is found. - */ - resolveToExistingVersion(info) { - // get final resolved version - var _PackageRequest$norma2 = PackageRequest.normalizePattern(this.pattern); - - const range = _PackageRequest$norma2.range, - name = _PackageRequest$norma2.name; - - const solvedRange = semver.validRange(range) ? info.version : range; - const resolved = this.resolver.getHighestRangeVersionMatch(name, solvedRange); - invariant(resolved, 'should have a resolved reference'); - - this.reportResolvedRangeMatch(info, resolved); - const ref = resolved._reference; - invariant(ref, 'Resolved package info has no package reference'); - ref.addRequest(this); - ref.addPattern(this.pattern, resolved); - } - - /** - * TODO description - */ - find(_ref4) { - var _this4 = this; - - let fresh = _ref4.fresh, - frozen = _ref4.frozen; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // find version info for this package pattern - const info = yield _this4.findVersionInfo(); - - info.fresh = fresh; - (0, (_validate || _load_validate()).cleanDependencies)(info, false, _this4.reporter, function () { - // swallow warnings - }); - - // check if while we were resolving this dep we've already resolved one that satisfies - // the same range - - var _PackageRequest$norma3 = PackageRequest.normalizePattern(_this4.pattern); - - const range = _PackageRequest$norma3.range, - name = _PackageRequest$norma3.name; - - const solvedRange = semver.validRange(range) ? info.version : range; - const resolved = !info.fresh || frozen ? _this4.resolver.getExactVersionMatch(name, solvedRange) : _this4.resolver.getHighestRangeVersionMatch(name, solvedRange); - if (resolved) { - _this4.resolver.reportPackageWithExistingVersion(_this4, info); - return; - } - - if (info.flat && !_this4.resolver.flat) { - throw new (_errors || _load_errors()).MessageError(_this4.reporter.lang('flatGlobalError')); - } - - // validate version info - PackageRequest.validateVersionInfo(info, _this4.reporter); - - // - const remote = info._remote; - invariant(remote, 'Missing remote'); - - // set package reference - const ref = new (_packageReference || _load_packageReference()).default(_this4, info, remote); - ref.addPattern(_this4.pattern, info); - ref.addOptional(_this4.optional); - ref.setFresh(fresh); - info._reference = ref; - info._remote = remote; - - // start installation of dependencies - const promises = []; - const deps = []; - - // normal deps - for (const depName in info.dependencies) { - const depPattern = depName + '@' + info.dependencies[depName]; - deps.push(depPattern); - promises.push(_this4.resolver.find({ - pattern: depPattern, - registry: remote.registry, - // dependencies of optional dependencies should themselves be optional - optional: _this4.optional, - parentRequest: _this4 - })); - } - - // optional deps - for (const depName in info.optionalDependencies) { - const depPattern = depName + '@' + info.optionalDependencies[depName]; - deps.push(depPattern); - promises.push(_this4.resolver.find({ - pattern: depPattern, - registry: remote.registry, - optional: true, - parentRequest: _this4 - })); - } - if (remote.type === 'workspace' && !_this4.config.production) { - // workspaces support dev dependencies - for (const depName in info.devDependencies) { - const depPattern = depName + '@' + info.devDependencies[depName]; - deps.push(depPattern); - promises.push(_this4.resolver.find({ - pattern: depPattern, - registry: remote.registry, - optional: false, - parentRequest: _this4 - })); - } - } - - yield Promise.all(promises); - ref.addDependencies(deps); - - // Now that we have all dependencies, it's safe to propagate optional - for (const otherRequest of ref.requests.slice(1)) { - ref.addOptional(otherRequest.optional); - } - })(); - } - - /** - * TODO description - */ - - static validateVersionInfo(info, reporter) { - // human readable name to use in errors - const human = `${info.name}@${info.version}`; - - info.version = PackageRequest.getPackageVersion(info); - - for (const key of (_constants || _load_constants()).REQUIRED_PACKAGE_KEYS) { - if (!info[key]) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('missingRequiredPackageKey', human, key)); - } - } - } + return target; +}; - /** - * Returns the package version if present, else defaults to the uid - */ +/***/ }), +/* 37 */ +/***/ (function(module, exports, __webpack_require__) { - static getPackageVersion(info) { - // TODO possibly reconsider this behaviour - return info.version === undefined ? info._uid : info.version; +// optional / simple context binding +var aFunction = __webpack_require__(63); +module.exports = function(fn, that, length){ + aFunction(fn); + if(that === undefined)return fn; + switch(length){ + case 1: return function(a){ + return fn.call(that, a); + }; + case 2: return function(a, b){ + return fn.call(that, a, b); + }; + case 3: return function(a, b, c){ + return fn.call(that, a, b, c); + }; } + return function(/* ...args */){ + return fn.apply(that, arguments); + }; +}; - /** - * Gets all of the outdated packages and sorts them appropriately - */ - - static getOutdatedPackages(lockfile, install, config, reporter) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - var _ref5 = yield install.fetchRequestFromCwd(); - - const depReqPatterns = _ref5.requests; - - - const deps = yield Promise.all(depReqPatterns.map((() => { - var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref7) { - let pattern = _ref7.pattern, - hint = _ref7.hint; - - const locked = lockfile.getLocked(pattern); - if (!locked) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('lockfileOutdated')); - } - - const name = locked.name, - current = locked.version; - - let latest = ''; - let wanted = ''; - let url = ''; - - const normalized = PackageRequest.normalizePattern(pattern); - - if (PackageRequest.getExoticResolver(pattern) || PackageRequest.getExoticResolver(normalized.range)) { - latest = wanted = 'exotic'; - url = normalized.range; - } else { - const registry = config.registries[locked.registry]; - - var _ref8 = yield registry.checkOutdated(config, name, normalized.range); - - latest = _ref8.latest; - wanted = _ref8.wanted; - url = _ref8.url; - } +/***/ }), +/* 38 */ +/***/ (function(module, exports, __webpack_require__) { - return { name, current, wanted, latest, url, hint }; - }); +var anObject = __webpack_require__(27) + , IE8_DOM_DEFINE = __webpack_require__(183) + , toPrimitive = __webpack_require__(198) + , dP = Object.defineProperty; - return function (_x) { - return _ref6.apply(this, arguments); - }; - })())); +exports.f = __webpack_require__(33) ? Object.defineProperty : function defineProperty(O, P, Attributes){ + anObject(O); + P = toPrimitive(P, true); + anObject(Attributes); + if(IE8_DOM_DEFINE)try { + return dP(O, P, Attributes); + } catch(e){ /* empty */ } + if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); + if('value' in Attributes)O[P] = Attributes.value; + return O; +}; - // Make sure to always output `exotic` versions to be compatible with npm - const isDepOld = function (_ref9) { - let current = _ref9.current, - latest = _ref9.latest, - wanted = _ref9.wanted; - return latest === 'exotic' || latest !== 'exotic' && (semver.lt(current, wanted) || semver.lt(current, latest)); - }; - const orderByName = function (depA, depB) { - return depA.name.localeCompare(depB.name); - }; +/***/ }), +/* 39 */ +/***/ (function(module, exports, __webpack_require__) { - return deps.filter(isDepOld).sort(orderByName); - })(); - } +try { + var util = __webpack_require__(2); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = __webpack_require__(211); } -exports.default = PackageRequest; -/***/ }), -/* 29 */ -/***/ (function(module, exports) { - -// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 -var global = module.exports = typeof window != 'undefined' && window.Math == Math - ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); -if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }), -/* 30 */ +/* 40 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -29134,19 +29226,39 @@ observableProto.flatMapLatest = observableProto.switchMap = function(selector, r /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 31 */ +/* 41 */ /***/ (function(module, exports) { -var core = module.exports = {version: '2.4.0'}; -if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef +var toString = {}.toString; + +module.exports = function(it){ + return toString.call(it).slice(8, -1); +}; /***/ }), -/* 32 */ +/* 42 */ +/***/ (function(module, exports) { + +var hasOwnProperty = {}.hasOwnProperty; +module.exports = function(it, key){ + return hasOwnProperty.call(it, key); +}; + +/***/ }), +/* 43 */ +/***/ (function(module, exports) { + +module.exports = function(it){ + return typeof it === 'object' ? it !== null : typeof it === 'function'; +}; + +/***/ }), +/* 44 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2015 Joyent, Inc. -var assert = __webpack_require__(9); +var assert = __webpack_require__(11); var util = __webpack_require__(2); function FingerprintFormatError(fp, format) { @@ -29231,20 +29343,20 @@ module.exports = { /***/ }), -/* 33 */ +/* 45 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2015 Joyent, Inc. module.exports = Signature; -var assert = __webpack_require__(9); -var algs = __webpack_require__(16); -var crypto = __webpack_require__(7); -var errs = __webpack_require__(32); -var utils = __webpack_require__(13); -var asn1 = __webpack_require__(34); -var SSHBuffer = __webpack_require__(108); +var assert = __webpack_require__(11); +var algs = __webpack_require__(23); +var crypto = __webpack_require__(8); +var errs = __webpack_require__(44); +var utils = __webpack_require__(17); +var asn1 = __webpack_require__(50); +var SSHBuffer = __webpack_require__(144); var InvalidAlgorithmError = errs.InvalidAlgorithmError; var SignatureParseError = errs.SignatureParseError; @@ -29550,7 +29662,191 @@ Signature._oldVersionDetect = function (obj) { /***/ }), -/* 34 */ +/* 46 */ +/***/ (function(module, exports) { + +module.exports = require("events"); + +/***/ }), +/* 47 */ +/***/ (function(module, exports) { + +module.exports = require("os"); + +/***/ }), +/* 48 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.exec = exports.queue = undefined; +exports.forkp = forkp; +exports.spawnp = spawnp; +exports.forwardSignalToSpawnedProcesses = forwardSignalToSpawnedProcesses; +exports.spawn = spawn; + +var _constants; + +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} + +var _blockingQueue; + +function _load_blockingQueue() { + return _blockingQueue = _interopRequireDefault(__webpack_require__(79)); +} + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); +} + +var _promise; + +function _load_promise() { + return _promise = __webpack_require__(53); +} + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +/* global child_process$spawnOpts */ + +const child = __webpack_require__(148); + +const queue = exports.queue = new (_blockingQueue || _load_blockingQueue()).default('child', (_constants || _load_constants()).CHILD_CONCURRENCY); + +// TODO: this uid check is kinda whack +let uid = 0; + +const exec = exports.exec = (0, (_promise || _load_promise()).promisify)(child.exec); + +function forkp(program, args, opts) { + return new Promise((resolve, reject) => { + const proc = child.fork(program, args, opts); + + proc.on('error', error => { + reject(error); + }); + + proc.on('close', exitCode => { + resolve(exitCode); + }); + }); +} + +function spawnp(program, args, opts) { + return new Promise((resolve, reject) => { + const proc = child.spawn(program, args, opts); + + proc.on('error', error => { + reject(error); + }); + + proc.on('close', exitCode => { + resolve(exitCode); + }); + }); +} + +const spawnedProcesses = {}; + +function forwardSignalToSpawnedProcesses(signal) { + for (const key of Object.keys(spawnedProcesses)) { + spawnedProcesses[key].kill(signal); + } +} + +function spawn(program, args) { + let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + let onData = arguments[3]; + + const key = opts.cwd || String(++uid); + return queue.push(key, () => new Promise((resolve, reject) => { + const proc = child.spawn(program, args, opts); + spawnedProcesses[key] = proc; + + let processingDone = false; + let processClosed = false; + let err = null; + + let stdout = ''; + + proc.on('error', err => { + if (err.code === 'ENOENT') { + reject(new (_errors || _load_errors()).ProcessSpawnError(`Couldn't find the binary ${program}`, err.code, program)); + } else { + reject(err); + } + }); + + function updateStdout(chunk) { + stdout += chunk; + if (onData) { + onData(chunk); + } + } + + function finish() { + delete spawnedProcesses[key]; + if (err) { + reject(err); + } else { + resolve(stdout.trim()); + } + } + + if (typeof opts.process === 'function') { + opts.process(proc, updateStdout, reject, function () { + if (processClosed) { + finish(); + } else { + processingDone = true; + } + }); + } else { + if (proc.stderr) { + proc.stderr.on('data', updateStdout); + } + + if (proc.stdout) { + proc.stdout.on('data', updateStdout); + } + + processingDone = true; + } + + proc.on('close', (code, signal) => { + if (signal || code >= 1) { + err = new (_errors || _load_errors()).ProcessTermError(['Command failed.', signal ? `Exit signal: ${signal}` : `Exit code: ${code}`, `Command: ${program}`, `Arguments: ${args.join(' ')}`, `Directory: ${opts.cwd || process.cwd()}`, `Output:\n${stdout.trim()}`].join('\n')); + err.EXIT_SIGNAL = signal; + err.EXIT_CODE = code; + } + + if (processingDone || err) { + finish(); + } else { + processClosed = true; + } + }); + })); +} + +/***/ }), +/* 49 */ +/***/ (function(module, exports) { + +module.exports = require("http"); + +/***/ }), +/* 50 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. @@ -29558,7 +29854,7 @@ Signature._oldVersionDetect = function (obj) { // If you have no idea what ASN.1 or BER is, see this: // ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc -var Ber = __webpack_require__(321); +var Ber = __webpack_require__(376); @@ -29576,7 +29872,7 @@ module.exports = { /***/ }), -/* 35 */ +/* 51 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -29589,7 +29885,7 @@ Object.defineProperty(exports, "__esModule", { var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } exports.default = function (rootCommandName, subCommands) { @@ -29652,291 +29948,767 @@ function _load_misc() { function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/* 36 */ +/* 52 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -exports.__esModule = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SCOPE_SEPARATOR = undefined; -var _assign = __webpack_require__(397); +var _slicedToArray2; -var _assign2 = _interopRequireDefault(_assign); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _asyncToGenerator2; -exports.default = _assign2.default || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } +var _constants; - return target; -}; +function _load_constants() { + return _constants = __webpack_require__(6); +} -/***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { +var _fs; -try { - var util = __webpack_require__(2); - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = __webpack_require__(515); +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } +var _npmResolver; -/***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_npmResolver() { + return _npmResolver = _interopRequireDefault(__webpack_require__(164)); +} -/** - * Base prompt implementation - * Should be extended by prompt types. - */ +var _envReplace; -var _ = __webpack_require__(21); -var chalk = __webpack_require__(15); -var runAsync = __webpack_require__(105); -var Choices = __webpack_require__(518); -var ScreenManager = __webpack_require__(529); +function _load_envReplace() { + return _envReplace = _interopRequireDefault(__webpack_require__(434)); +} -var Prompt = module.exports = function (question, rl, answers) { - // Setup instance defaults property - _.assign(this, { - answers: answers, - status: 'pending' - }); +var _baseRegistry; - // Set defaults prompt options - this.opt = _.defaults(_.clone(question), { - validate: function () { - return true; - }, - filter: function (val) { - return val; - }, - when: function () { - return true; - } - }); +function _load_baseRegistry() { + return _baseRegistry = _interopRequireDefault(__webpack_require__(418)); +} - // Check to make sure prompt requirements are there - if (!this.opt.message) { - this.throwParamError('message'); - } - if (!this.opt.name) { - this.throwParamError('name'); - } +var _misc; - // Normalize choices - if (Array.isArray(this.opt.choices)) { - this.opt.choices = new Choices(this.opt.choices, answers); - } +function _load_misc() { + return _misc = __webpack_require__(10); +} - this.rl = rl; - this.screen = new ScreenManager(this.rl); -}; +var _path; -/** - * Start the Inquiry session and manage output value filtering - * @return {Promise} - */ +function _load_path() { + return _path = __webpack_require__(276); +} -Prompt.prototype.run = function () { - return new Promise(function (resolve) { - this._run(function (value) { - resolve(value); - }); - }.bind(this)); -}; +var _normalizeUrl; -// default noop (this one should be overwritten in prompts) -Prompt.prototype._run = function (cb) { - cb(); -}; +function _load_normalizeUrl() { + return _normalizeUrl = _interopRequireDefault(__webpack_require__(577)); +} -/** - * Throw an error telling a required parameter is missing - * @param {String} name Name of the missing param - * @return {Throw Error} - */ +var _userHomeDir; -Prompt.prototype.throwParamError = function (name) { - throw new Error('You must provide a `' + name + '` parameter'); -}; +function _load_userHomeDir() { + return _userHomeDir = _interopRequireDefault(__webpack_require__(62)); +} -/** - * Called when the UI closes. Override to do any specific cleanup necessary - */ -Prompt.prototype.close = function () { - this.screen.releaseCursor(); -}; +var _userHomeDir2; -/** - * Run the provided validation method each time a submit event occur. - * @param {Rx.Observable} submit - submit event flow - * @return {Object} Object containing two observables: `success` and `error` - */ -Prompt.prototype.handleSubmitEvents = function (submit) { - var self = this; - var validate = runAsync(this.opt.validate); - var filter = runAsync(this.opt.filter); - var validation = submit.flatMap(function (value) { - return filter(value).then(function (filteredValue) { - return validate(filteredValue, self.answers).then(function (isValid) { - return {isValid: isValid, value: filteredValue}; - }, function (err) { - return {isValid: err}; - }); - }, function (err) { - return {isValid: err}; - }); - }).share(); +function _load_userHomeDir2() { + return _userHomeDir2 = __webpack_require__(62); +} - var success = validation - .filter(function (state) { - return state.isValid === true; - }) - .take(1); +var _path2; - var error = validation - .filter(function (state) { - return state.isValid !== true; - }) - .takeUntil(success); +function _load_path2() { + return _path2 = _interopRequireDefault(__webpack_require__(0)); +} - return { - success: success, - error: error - }; -}; +var _url; -/** - * Generate the prompt question string - * @return {String} prompt question string - */ +function _load_url() { + return _url = _interopRequireDefault(__webpack_require__(14)); +} -Prompt.prototype.getQuestion = function () { - var message = chalk.green('?') + ' ' + chalk.bold(this.opt.message) + ' '; +var _ini; - // Append the default if available, and if question isn't answered - if (this.opt.default != null && this.status !== 'answered') { - message += chalk.dim('(' + this.opt.default + ') '); - } +function _load_ini() { + return _ini = _interopRequireDefault(__webpack_require__(530)); +} - return message; -}; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { +const DEFAULT_REGISTRY = 'https://registry.npmjs.org/'; -"use strict"; +const REGEX_REGISTRY_PREFIX = /^https?:/; +const REGEX_REGISTRY_SUFFIX = /registry\/?$/; -var rx = __webpack_require__(106); +const SCOPE_SEPARATOR = exports.SCOPE_SEPARATOR = '%2f'; +// All scoped package names are of the format `@scope%2fpkg` from the use of NpmRegistry.escapeName +// `(?:^|\/)` Match either the start of the string or a `/` but don't capture +// `[^\/?]+?` Match any character that is not '/' or '?' and capture, up until the first occurance of: +// `%2f` Match SCOPE_SEPARATOR, the escaped '/', and don't capture +const SCOPED_PKG_REGEXP = /(?:^|\/)(@[^\/?]+?)(?=%2f)/; -function normalizeKeypressEvents(value, key) { - return {value: value, key: key || {}}; +// TODO: Use the method from src/cli/commands/global.js for this instead +function getGlobalPrefix() { + if (process.env.PREFIX) { + return process.env.PREFIX; + } else if (process.platform === 'win32') { + // c:\node\node.exe --> prefix=c:\node\ + return (_path2 || _load_path2()).default.dirname(process.execPath); + } else { + // /usr/local/bin/node --> prefix=/usr/local + let prefix = (_path2 || _load_path2()).default.dirname((_path2 || _load_path2()).default.dirname(process.execPath)); + + // destdir only is respected on Unix + if (process.env.DESTDIR) { + prefix = (_path2 || _load_path2()).default.join(process.env.DESTDIR, prefix); + } + + return prefix; + } } -module.exports = function (rl) { - var keypress = rx.Observable.fromEvent(rl.input, 'keypress', normalizeKeypressEvents) - .filter(function (e) { - // Ignore `enter` key. On the readline, we only care about the `line` event. - return e.key.name !== 'enter' && e.key.name !== 'return'; - }); +const PATH_CONFIG_OPTIONS = ['cache', 'cafile', 'prefix', 'userconfig']; - return { - line: rx.Observable.fromEvent(rl, 'line'), - keypress: keypress, +function isPathConfigOption(key) { + return PATH_CONFIG_OPTIONS.indexOf(key) >= 0; +} - normalizedUpKey: keypress.filter(function (e) { - return e.key.name === 'up' || e.key.name === 'k' || (e.key.name === 'p' && e.key.ctrl); - }).share(), +function normalizePath(val) { + if (val === undefined) { + return undefined; + } - normalizedDownKey: keypress.filter(function (e) { - return e.key.name === 'down' || e.key.name === 'j' || (e.key.name === 'n' && e.key.ctrl); - }).share(), + if (typeof val !== 'string') { + val = '' + val; + } - numberKey: keypress.filter(function (e) { - return e.value && '123456789'.indexOf(e.value) >= 0; - }).map(function (e) { - return Number(e.value); - }).share(), + return (0, (_path || _load_path()).resolveWithHome)(val); +} - spaceKey: keypress.filter(function (e) { - return e.key && e.key.name === 'space'; - }).share(), +class NpmRegistry extends (_baseRegistry || _load_baseRegistry()).default { + constructor(cwd, registries, requestManager, reporter) { + super(cwd, registries, requestManager, reporter); + this.folder = 'node_modules'; + } - aKey: keypress.filter(function (e) { - return e.key && e.key.name === 'a'; - }).share(), + static escapeName(name) { + // scoped packages contain slashes and the npm registry expects them to be escaped + return name.replace('/', SCOPE_SEPARATOR); + } - iKey: keypress.filter(function (e) { - return e.key && e.key.name === 'i'; - }).share() - }; -}; + isScopedPackage(packageIdent) { + return SCOPED_PKG_REGEXP.test(packageIdent); + } + getRequestUrl(registry, pathname) { + const isUrl = /^https?:/.test(pathname); -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { + if (isUrl) { + return pathname; + } else { + return (_url || _load_url()).default.resolve(registry, pathname); + } + } -(function(){ + isRequestToRegistry(requestUrl, registryUrl) { + const normalizedRequestUrl = (0, (_normalizeUrl || _load_normalizeUrl()).default)(requestUrl); + const normalizedRegistryUrl = (0, (_normalizeUrl || _load_normalizeUrl()).default)(registryUrl); + const requestParsed = (_url || _load_url()).default.parse(normalizedRequestUrl); + const registryParsed = (_url || _load_url()).default.parse(normalizedRegistryUrl); + const requestHost = requestParsed.host || ''; + const registryHost = registryParsed.host || ''; + const requestPath = requestParsed.path || ''; + const registryPath = registryParsed.path || ''; + const customHostSuffix = this.getRegistryOrGlobalOption(registryUrl, 'custom-host-suffix'); - // Copyright (c) 2005 Tom Wu - // All Rights Reserved. - // See "LICENSE" for details. + return requestHost === registryHost && (requestPath.startsWith(registryPath) || + // For some registries, the package path does not prefix with the registry path + typeof customHostSuffix === 'string' && requestHost.endsWith(customHostSuffix)); + } - // Basic JavaScript BN library - subset useful for RSA encryption. + request(pathname) { + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + let packageName = arguments[2]; - // Bits per digit - var dbits; + // packageName needs to be escaped when if it is passed + const packageIdent = packageName && NpmRegistry.escapeName(packageName) || pathname; + const registry = this.getRegistry(packageIdent); + const requestUrl = this.getRequestUrl(registry, pathname); - // JavaScript engine analysis - var canary = 0xdeadbeefcafe; - var j_lm = ((canary&0xffffff)==0xefcafe); + const alwaysAuth = this.getRegistryOrGlobalOption(registry, 'always-auth'); - // (public) Constructor - function BigInteger(a,b,c) { - if(a != null) - if("number" == typeof a) this.fromNumber(a,b,c); - else if(b == null && "string" != typeof a) this.fromString(a,256); - else this.fromString(a,b); + const headers = Object.assign({ + Accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' + }, opts.headers); + + const isToRegistry = this.isRequestToRegistry(requestUrl, registry); + + // this.token must be checked to account for publish requests on non-scopped packages + if (this.token || isToRegistry && (alwaysAuth || this.isScopedPackage(packageIdent))) { + const authorization = this.getAuth(packageIdent); + if (authorization) { + headers.authorization = authorization; + } } - // return new, unset BigInteger - function nbi() { return new BigInteger(null); } + return this.requestManager.request({ + url: requestUrl, + method: opts.method, + body: opts.body, + auth: opts.auth, + headers, + json: !opts.buffer, + buffer: opts.buffer, + process: opts.process, + gzip: true + }); + } - // am: Compute w_j += (x*this_i), propagate carries, - // c is initial carry, returns final carry. - // c < 3*dvalue, x < 2*dvalue, this_i < dvalue - // We need to select the fastest one that works in this environment. + checkOutdated(config, name, range) { + var _this = this; - // am1: use a single mult and divide to get the high bits, - // max digit bits should be 26 because - // max internal value = 2*dvalue^2-2*dvalue (< 2^53) - function am1(i,x,w,j,c,n) { - while(--n >= 0) { - var v = x*this[i++]+w[j]+c; - c = Math.floor(v/0x4000000); - w[j++] = v&0x3ffffff; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const req = yield _this.request(NpmRegistry.escapeName(name), { + headers: { Accept: 'application/json' } + }); + if (!req) { + throw new Error('couldnt find ' + name); } - return c; - } - // am2 avoids a big mult-and-extract completely. - // Max digit bits should be <= 30 because we do bitwise ops - // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) + + const repository = req.repository, + homepage = req.homepage; + + const url = homepage || repository && repository.url || ''; + + return { + latest: req['dist-tags'].latest, + wanted: (yield (_npmResolver || _load_npmResolver()).default.findVersionInRegistryResponse(config, range, req)).version, + url + }; + })(); + } + + getPossibleConfigLocations(filename, reporter) { + var _this2 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // npmrc --> ./.npmrc, ~/.npmrc, ${prefix}/etc/npmrc + const localfile = '.' + filename; + const possibles = [[false, (_path2 || _load_path2()).default.join(_this2.cwd, localfile)], [true, _this2.config.userconfig || (_path2 || _load_path2()).default.join((_userHomeDir || _load_userHomeDir()).default, localfile)], [false, (_path2 || _load_path2()).default.join(getGlobalPrefix(), 'etc', filename)]]; + + // When home directory for global install is different from where $HOME/npmrc is stored, + // E.g. /usr/local/share vs /root on linux machines, check the additional location + if ((_userHomeDir2 || _load_userHomeDir2()).home !== (_userHomeDir || _load_userHomeDir()).default) { + possibles.push([true, (_path2 || _load_path2()).default.join((_userHomeDir2 || _load_userHomeDir2()).home, localfile)]); + } + + // npmrc --> ../.npmrc, ../../.npmrc, etc. + const foldersFromRootToCwd = (0, (_path || _load_path()).getPosixPath)(_this2.cwd).split('/'); + while (foldersFromRootToCwd.length > 1) { + possibles.push([false, (_path2 || _load_path2()).default.join(foldersFromRootToCwd.join((_path2 || _load_path2()).default.sep), localfile)]); + foldersFromRootToCwd.pop(); + } + + const actuals = []; + for (const _ref of possibles) { + var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); + + const isHome = _ref2[0]; + const loc = _ref2[1]; + + reporter.verbose(reporter.lang('configPossibleFile', loc)); + if (yield (_fs || _load_fs()).exists(loc)) { + reporter.verbose(reporter.lang('configFileFound', loc)); + actuals.push([isHome, loc, yield (_fs || _load_fs()).readFile(loc)]); + } + } + return actuals; + })(); + } + + static normalizeConfig(config) { + config = (_baseRegistry || _load_baseRegistry()).default.normalizeConfig(config); + + for (const key in config) { + config[key] = (0, (_envReplace || _load_envReplace()).default)(config[key]); + if (isPathConfigOption(key)) { + config[key] = normalizePath(config[key]); + } + } + + return config; + } + + loadConfig() { + var _this3 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // docs: https://docs.npmjs.com/misc/config + _this3.mergeEnv('npm_config_'); + + for (const _ref3 of yield _this3.getPossibleConfigLocations('npmrc', _this3.reporter)) { + var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 3); + + const loc = _ref4[1]; + const file = _ref4[2]; + + const config = NpmRegistry.normalizeConfig((_ini || _load_ini()).default.parse(file)); + + // normalize offline mirror path relative to the current npmrc + const offlineLoc = config['yarn-offline-mirror']; + // don't normalize if we already have a mirror path + if (!_this3.config['yarn-offline-mirror'] && offlineLoc) { + const mirrorLoc = config['yarn-offline-mirror'] = (_path2 || _load_path2()).default.resolve((_path2 || _load_path2()).default.dirname(loc), offlineLoc); + yield (_fs || _load_fs()).mkdirp(mirrorLoc); + } + + _this3.config = Object.assign({}, config, _this3.config); + } + })(); + } + + getScope(packageIdent) { + const match = packageIdent.match(SCOPED_PKG_REGEXP); + return match && match[1] || ''; + } + + getRegistry(packageIdent) { + // Try extracting registry from the url, then scoped registry, and default registry + if (packageIdent.match(/^https?:/)) { + const availableRegistries = this.getAvailableRegistries(); + const registry = availableRegistries.find(registry => packageIdent.startsWith(registry)); + if (registry) { + return String(registry); + } + } + + for (const scope of [this.getScope(packageIdent), '']) { + const registry = this.getScopedOption(scope, 'registry') || this.registries.yarn.getScopedOption(scope, 'registry'); + if (registry) { + return String(registry); + } + } + + return DEFAULT_REGISTRY; + } + + getAuth(packageIdent) { + if (this.token) { + return this.token; + } + + const baseRegistry = this.getRegistry(packageIdent); + const registries = [baseRegistry]; + + // If sending a request to the Yarn registry, we must also send it the auth token for the npm registry + if (baseRegistry === (_constants || _load_constants()).YARN_REGISTRY) { + registries.push(DEFAULT_REGISTRY); + } + + for (const registry of registries) { + // Check for bearer token. + const authToken = this.getRegistryOrGlobalOption(registry, '_authToken'); + if (authToken) { + return `Bearer ${String(authToken)}`; + } + + // Check for basic auth token. + const auth = this.getRegistryOrGlobalOption(registry, '_auth'); + if (auth) { + return `Basic ${String(auth)}`; + } + + // Check for basic username/password auth. + const username = this.getRegistryOrGlobalOption(registry, 'username'); + const password = this.getRegistryOrGlobalOption(registry, '_password'); + if (username && password) { + const pw = new Buffer(String(password), 'base64').toString(); + return 'Basic ' + new Buffer(String(username) + ':' + pw).toString('base64'); + } + } + + return ''; + } + + getScopedOption(scope, option) { + return this.getOption(scope + (scope ? ':' : '') + option); + } + + getRegistryOption(registry, option) { + const pre = REGEX_REGISTRY_PREFIX; + const suf = REGEX_REGISTRY_SUFFIX; + + // When registry is used config scope, the trailing '/' is required + const reg = (0, (_misc || _load_misc()).addSuffix)(registry, '/'); + + // 1st attempt, try to get option for the given registry URL + // 2nd attempt, remove the 'https?:' prefix of the registry URL + // 3nd attempt, remove the 'registry/?' suffix of the registry URL + return this.getScopedOption(reg, option) || reg.match(pre) && this.getRegistryOption(reg.replace(pre, ''), option) || reg.match(suf) && this.getRegistryOption(reg.replace(suf, ''), option); + } + + getRegistryOrGlobalOption(registry, option) { + return this.getRegistryOption(registry, option) || this.getOption(option); + } +} +exports.default = NpmRegistry; +NpmRegistry.filename = 'package.json'; + +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.wait = wait; +exports.promisify = promisify; +exports.queue = queue; +function wait(delay) { + return new Promise(resolve => { + setTimeout(resolve, delay); + }); +} + +function promisify(fn, firstData) { + return function () { + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return new Promise(function (resolve, reject) { + args.push(function (err) { + for (var _len2 = arguments.length, result = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + result[_key2 - 1] = arguments[_key2]; + } + + let res = result; + + if (result.length <= 1) { + res = result[0]; + } + + if (firstData) { + res = err; + err = null; + } + + if (err) { + reject(err); + } else { + resolve(res); + } + }); + + fn.apply(null, args); + }); + }; +} + +function queue(arr, promiseProducer) { + let concurrency = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Infinity; + + concurrency = Math.min(concurrency, arr.length); + + // clone + arr = arr.slice(); + + const results = []; + let total = arr.length; + if (!total) { + return Promise.resolve(results); + } + + return new Promise((resolve, reject) => { + for (let i = 0; i < concurrency; i++) { + next(); + } + + function next() { + const item = arr.shift(); + const promise = promiseProducer(item); + + promise.then(function (result) { + results.push(result); + + total--; + if (total === 0) { + resolve(results); + } else { + if (arr.length) { + next(); + } + } + }, reject); + } + }); +} + +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Base prompt implementation + * Should be extended by prompt types. + */ + +var _ = __webpack_require__(28); +var chalk = __webpack_require__(20); +var runAsync = __webpack_require__(141); +var Choices = __webpack_require__(532); +var ScreenManager = __webpack_require__(543); + +var Prompt = module.exports = function (question, rl, answers) { + // Setup instance defaults property + _.assign(this, { + answers: answers, + status: 'pending' + }); + + // Set defaults prompt options + this.opt = _.defaults(_.clone(question), { + validate: function () { + return true; + }, + filter: function (val) { + return val; + }, + when: function () { + return true; + } + }); + + // Check to make sure prompt requirements are there + if (!this.opt.message) { + this.throwParamError('message'); + } + if (!this.opt.name) { + this.throwParamError('name'); + } + + // Normalize choices + if (Array.isArray(this.opt.choices)) { + this.opt.choices = new Choices(this.opt.choices, answers); + } + + this.rl = rl; + this.screen = new ScreenManager(this.rl); +}; + +/** + * Start the Inquiry session and manage output value filtering + * @return {Promise} + */ + +Prompt.prototype.run = function () { + return new Promise(function (resolve) { + this._run(function (value) { + resolve(value); + }); + }.bind(this)); +}; + +// default noop (this one should be overwritten in prompts) +Prompt.prototype._run = function (cb) { + cb(); +}; + +/** + * Throw an error telling a required parameter is missing + * @param {String} name Name of the missing param + * @return {Throw Error} + */ + +Prompt.prototype.throwParamError = function (name) { + throw new Error('You must provide a `' + name + '` parameter'); +}; + +/** + * Called when the UI closes. Override to do any specific cleanup necessary + */ +Prompt.prototype.close = function () { + this.screen.releaseCursor(); +}; + +/** + * Run the provided validation method each time a submit event occur. + * @param {Rx.Observable} submit - submit event flow + * @return {Object} Object containing two observables: `success` and `error` + */ +Prompt.prototype.handleSubmitEvents = function (submit) { + var self = this; + var validate = runAsync(this.opt.validate); + var filter = runAsync(this.opt.filter); + var validation = submit.flatMap(function (value) { + return filter(value).then(function (filteredValue) { + return validate(filteredValue, self.answers).then(function (isValid) { + return {isValid: isValid, value: filteredValue}; + }, function (err) { + return {isValid: err}; + }); + }, function (err) { + return {isValid: err}; + }); + }).share(); + + var success = validation + .filter(function (state) { + return state.isValid === true; + }) + .take(1); + + var error = validation + .filter(function (state) { + return state.isValid !== true; + }) + .takeUntil(success); + + return { + success: success, + error: error + }; +}; + +/** + * Generate the prompt question string + * @return {String} prompt question string + */ + +Prompt.prototype.getQuestion = function () { + var message = chalk.green('?') + ' ' + chalk.bold(this.opt.message) + ' '; + + // Append the default if available, and if question isn't answered + if (this.opt.default != null && this.status !== 'answered') { + message += chalk.dim('(' + this.opt.default + ') '); + } + + return message; +}; + + +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var rx = __webpack_require__(142); + +function normalizeKeypressEvents(value, key) { + return {value: value, key: key || {}}; +} + +module.exports = function (rl) { + var keypress = rx.Observable.fromEvent(rl.input, 'keypress', normalizeKeypressEvents) + .filter(function (e) { + // Ignore `enter` key. On the readline, we only care about the `line` event. + return e.key.name !== 'enter' && e.key.name !== 'return'; + }); + + return { + line: rx.Observable.fromEvent(rl, 'line'), + keypress: keypress, + + normalizedUpKey: keypress.filter(function (e) { + return e.key.name === 'up' || e.key.name === 'k' || (e.key.name === 'p' && e.key.ctrl); + }).share(), + + normalizedDownKey: keypress.filter(function (e) { + return e.key.name === 'down' || e.key.name === 'j' || (e.key.name === 'n' && e.key.ctrl); + }).share(), + + numberKey: keypress.filter(function (e) { + return e.value && '123456789'.indexOf(e.value) >= 0; + }).map(function (e) { + return Number(e.value); + }).share(), + + spaceKey: keypress.filter(function (e) { + return e.key && e.key.name === 'space'; + }).share(), + + aKey: keypress.filter(function (e) { + return e.key && e.key.name === 'a'; + }).share(), + + iKey: keypress.filter(function (e) { + return e.key && e.key.name === 'i'; + }).share() + }; +}; + + +/***/ }), +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { + +(function(){ + + // Copyright (c) 2005 Tom Wu + // All Rights Reserved. + // See "LICENSE" for details. + + // Basic JavaScript BN library - subset useful for RSA encryption. + + // Bits per digit + var dbits; + + // JavaScript engine analysis + var canary = 0xdeadbeefcafe; + var j_lm = ((canary&0xffffff)==0xefcafe); + + // (public) Constructor + function BigInteger(a,b,c) { + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); + } + + // return new, unset BigInteger + function nbi() { return new BigInteger(null); } + + // am: Compute w_j += (x*this_i), propagate carries, + // c is initial carry, returns final carry. + // c < 3*dvalue, x < 2*dvalue, this_i < dvalue + // We need to select the fastest one that works in this environment. + + // am1: use a single mult and divide to get the high bits, + // max digit bits should be 26 because + // max internal value = 2*dvalue^2-2*dvalue (< 2^53) + function am1(i,x,w,j,c,n) { + while(--n >= 0) { + var v = x*this[i++]+w[j]+c; + c = Math.floor(v/0x4000000); + w[j++] = v&0x3ffffff; + } + return c; + } + // am2 avoids a big mult-and-extract completely. + // Max digit bits should be <= 30 because we do bitwise ops + // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { @@ -31252,1130 +32024,1398 @@ module.exports = function (rl) { /***/ }), -/* 41 */ +/* 57 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright 2015 Joyent, Inc. - -module.exports = { - read: read, - write: write -}; +module.exports = minimatch +minimatch.Minimatch = Minimatch -var assert = __webpack_require__(9); -var asn1 = __webpack_require__(34); -var crypto = __webpack_require__(7); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); +var path = { sep: '/' } +try { + path = __webpack_require__(0) +} catch (er) {} -var pkcs1 = __webpack_require__(164); -var pkcs8 = __webpack_require__(74); -var sshpriv = __webpack_require__(107); -var rfc4253 = __webpack_require__(48); +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = __webpack_require__(173) -var errors = __webpack_require__(32); +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} -/* - * For reading we support both PKCS#1 and PKCS#8. If we find a private key, - * we just take the public component of it and use that. - */ -function read(buf, options, forceType) { - var input = buf; - if (typeof (buf) !== 'string') { - assert.buffer(buf, 'buf'); - buf = buf.toString('ascii'); - } +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' - var lines = buf.trim().split('\n'); +// * => any number of characters +var star = qmark + '*?' - var m = lines[0].match(/*JSSTYLED*/ - /[-]+[ ]*BEGIN ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); - assert.ok(m, 'invalid PEM header'); +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - var m2 = lines[lines.length - 1].match(/*JSSTYLED*/ - /[-]+[ ]*END ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); - assert.ok(m2, 'invalid PEM footer'); +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - /* Begin and end banners must match key type */ - assert.equal(m[2], m2[2]); - var type = m[2].toLowerCase(); +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') - var alg; - if (m[1]) { - /* They also must match algorithms, if given */ - assert.equal(m[1], m2[1], 'PEM header and footer mismatch'); - alg = m[1].trim(); - } +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} - var headers = {}; - while (true) { - lines = lines.slice(1); - m = lines[0].match(/*JSSTYLED*/ - /^([A-Za-z0-9-]+): (.+)$/); - if (!m) - break; - headers[m[1].toLowerCase()] = m[2]; - } +// normalizes slashes. +var slashSplit = /\/+/ - var cipher, key, iv; - if (headers['proc-type']) { - var parts = headers['proc-type'].split(','); - if (parts[0] === '4' && parts[1] === 'ENCRYPTED') { - if (typeof (options.passphrase) === 'string') { - options.passphrase = new Buffer( - options.passphrase, 'utf-8'); - } - if (!Buffer.isBuffer(options.passphrase)) { - throw (new errors.KeyEncryptedError( - options.filename, 'PEM')); - } else { - parts = headers['dek-info'].split(','); - assert.ok(parts.length === 2); - cipher = parts[0].toLowerCase(); - iv = new Buffer(parts[1], 'hex'); - key = utils.opensslKeyDeriv(cipher, iv, - options.passphrase, 1).key; - } - } - } +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} - /* Chop off the first and last lines */ - lines = lines.slice(0, -1).join(''); - buf = new Buffer(lines, 'base64'); +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} - if (cipher && key && iv) { - var cipherStream = crypto.createDecipheriv(cipher, key, iv); - var chunk, chunks = []; - cipherStream.once('error', function (e) { - if (e.toString().indexOf('bad decrypt') !== -1) { - throw (new Error('Incorrect passphrase ' + - 'supplied, could not decrypt key')); - } - throw (e); - }); - cipherStream.write(buf); - cipherStream.end(); - while ((chunk = cipherStream.read()) !== null) - chunks.push(chunk); - buf = Buffer.concat(chunks); - } +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch - /* The new OpenSSH internal format abuses PEM headers */ - if (alg && alg.toLowerCase() === 'openssh') - return (sshpriv.readSSHPrivate(type, buf, options)); - if (alg && alg.toLowerCase() === 'ssh2') - return (rfc4253.readType(type, buf, options)); + var orig = minimatch - var der = new asn1.BerReader(buf); - der.originalInput = input; + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } - /* - * All of the PEM file types start with a sequence tag, so chop it - * off here - */ - der.readSequence(); + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } - /* PKCS#1 type keys name an algorithm in the banner explicitly */ - if (alg) { - if (forceType) - assert.strictEqual(forceType, 'pkcs1'); - return (pkcs1.readPkcs1(alg, type, der)); - } else { - if (forceType) - assert.strictEqual(forceType, 'pkcs8'); - return (pkcs8.readPkcs8(alg, type, der)); - } + return m } -function write(key, options, type) { - assert.object(key); - - var alg = {'ecdsa': 'EC', 'rsa': 'RSA', 'dsa': 'DSA'}[key.type]; - var header; - - var der = new asn1.BerWriter(); +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} - if (PrivateKey.isPrivateKey(key)) { - if (type && type === 'pkcs8') { - header = 'PRIVATE KEY'; - pkcs8.writePkcs8(der, key); - } else { - if (type) - assert.strictEqual(type, 'pkcs1'); - header = alg + ' PRIVATE KEY'; - pkcs1.writePkcs1(der, key); - } +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } - } else if (Key.isKey(key)) { - if (type && type === 'pkcs1') { - header = alg + ' PUBLIC KEY'; - pkcs1.writePkcs1(der, key); - } else { - if (type) - assert.strictEqual(type, 'pkcs8'); - header = 'PUBLIC KEY'; - pkcs8.writePkcs8(der, key); - } + if (!options) options = {} - } else { - throw (new Error('key is not a Key or PrivateKey')); - } + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } - var tmp = der.buffer.toString('base64'); - var len = tmp.length + (tmp.length / 64) + - 18 + 16 + header.length*2 + 10; - var buf = new Buffer(len); - var o = 0; - o += buf.write('-----BEGIN ' + header + '-----\n', o); - for (var i = 0; i < tmp.length; ) { - var limit = i + 64; - if (limit > tmp.length) - limit = tmp.length; - o += buf.write(tmp.slice(i, limit), o); - buf[o++] = 10; - i = limit; - } - o += buf.write('-----END ' + header + '-----\n', o); + // "" only matches "" + if (pattern.trim() === '') return p === '' - return (buf.slice(0, o)); + return new Minimatch(pattern, options).match(p) } +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } -/***/ }), -/* 42 */ -/***/ (function(module, exports, __webpack_require__) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } -"use strict"; + if (!options) options = {} + pattern = pattern.trim() + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false -module.exports = { - copy: copy, - checkDataType: checkDataType, - checkDataTypes: checkDataTypes, - coerceToTypes: coerceToTypes, - toHash: toHash, - getProperty: getProperty, - escapeQuotes: escapeQuotes, - ucs2length: __webpack_require__(291), - varOccurences: varOccurences, - varReplace: varReplace, - cleanUpCode: cleanUpCode, - cleanUpVarErrors: cleanUpVarErrors, - schemaHasRules: schemaHasRules, - schemaHasRulesExcept: schemaHasRulesExcept, - stableStringify: __webpack_require__(156), - toQuotedString: toQuotedString, - getPathExpr: getPathExpr, - getPath: getPath, - getData: getData, - unescapeFragment: unescapeFragment, - escapeFragment: escapeFragment, - escapeJsonPointer: escapeJsonPointer -}; + // make the set of regexps etc. + this.make() +} +Minimatch.prototype.debug = function () {} -function copy(o, to) { - to = to || {}; - for (var key in o) to[key] = o[key]; - return to; -} +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + var pattern = this.pattern + var options = this.options -function checkDataType(dataType, data, negate) { - var EQUAL = negate ? ' !== ' : ' === ' - , AND = negate ? ' || ' : ' && ' - , OK = negate ? '!' : '' - , NOT = negate ? '' : '!'; - switch (dataType) { - case 'null': return data + EQUAL + 'null'; - case 'array': return OK + 'Array.isArray(' + data + ')'; - case 'object': return '(' + OK + data + AND + - 'typeof ' + data + EQUAL + '"object"' + AND + - NOT + 'Array.isArray(' + data + '))'; - case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + - NOT + '(' + data + ' % 1)' + - AND + data + EQUAL + data + ')'; - default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return } -} + // step 1: figure out negation, etc. + this.parseNegate() -function checkDataTypes(dataTypes, data) { - switch (dataTypes.length) { - case 1: return checkDataType(dataTypes[0], data, true); - default: - var code = ''; - var types = toHash(dataTypes); - if (types.array && types.object) { - code = types.null ? '(': '(!' + data + ' || '; - code += 'typeof ' + data + ' !== "object")'; - delete types.null; - delete types.array; - delete types.object; - } - if (types.number) delete types.integer; - for (var t in types) - code += (code ? ' && ' : '' ) + checkDataType(t, data, true); + // step 2: expand braces + var set = this.globSet = this.braceExpand() - return code; - } -} + if (options.debug) this.debug = console.error + this.debug(this.pattern, set) -var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); -function coerceToTypes(optionCoerceTypes, dataTypes) { - if (Array.isArray(dataTypes)) { - var types = []; - for (var i=0; i<dataTypes.length; i++) { - var t = dataTypes[i]; - if (COERCE_TO_TYPES[t]) types[types.length] = t; - else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t; - } - if (types.length) return types; - } else if (COERCE_TO_TYPES[dataTypes]) { - return [dataTypes]; - } else if (optionCoerceTypes === 'array' && dataTypes === 'array') { - return ['array']; - } -} + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + this.debug(this.pattern, set) -function toHash(arr) { - var hash = {}; - for (var i=0; i<arr.length; i++) hash[arr[i]] = true; - return hash; -} + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + this.debug(this.pattern, set) -var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; -var SINGLE_QUOTE = /'|\\/g; -function getProperty(key) { - return typeof key == 'number' - ? '[' + key + ']' - : IDENTIFIER.test(key) - ? '.' + key - : "['" + escapeQuotes(key) + "']"; -} + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + this.debug(this.pattern, set) -function escapeQuotes(str) { - return str.replace(SINGLE_QUOTE, '\\$&') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\f/g, '\\f') - .replace(/\t/g, '\\t'); + this.set = set } +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 -function varOccurences(str, dataVar) { - dataVar += '[^0-9]'; - var matches = str.match(new RegExp(dataVar, 'g')); - return matches ? matches.length : 0; -} + if (options.nonegate) return + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } -function varReplace(str, dataVar, expr) { - dataVar += '([^0-9])'; - expr = expr.replace(/\$/g, '$$$$'); - return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate } - -var EMPTY_ELSE = /else\s*{\s*}/g - , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g - , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g; -function cleanUpCode(out) { - return out.replace(EMPTY_ELSE, '') - .replace(EMPTY_IF_NO_ELSE, '') - .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))'); +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) } +Minimatch.prototype.braceExpand = braceExpand -var ERRORS_REGEXP = /[^v\.]errors/g - , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g - , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g - , RETURN_VALID = 'return errors === 0;' - , RETURN_TRUE = 'validate.errors = null; return true;' - , RETURN_ASYNC = /if \(errors === 0\) return true;\s*else throw new ValidationError\(vErrors\);/ - , RETURN_TRUE_ASYNC = 'return true;'; - -function cleanUpVarErrors(out, async) { - var matches = out.match(ERRORS_REGEXP); - if (!matches || matches.length !== 2) return out; - return async - ? out.replace(REMOVE_ERRORS_ASYNC, '') - .replace(RETURN_ASYNC, RETURN_TRUE_ASYNC) - : out.replace(REMOVE_ERRORS, '') - .replace(RETURN_VALID, RETURN_TRUE); -} +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern -function schemaHasRules(schema, rules) { - for (var key in schema) if (rules[key]) return true; -} + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } -function schemaHasRulesExcept(schema, rules, exceptKeyword) { - for (var key in schema) if (key != exceptKeyword && rules[key]) return true; + return expand(pattern) } +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } -function toQuotedString(str) { - return '\'' + escapeQuotes(str) + '\''; -} + var options = this.options + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' -function getPathExpr(currentPath, expr, jsonPointers, isNumber) { - var path = jsonPointers // false by default - ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') - : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''); - return joinPaths(currentPath, path); -} - - -function getPath(currentPath, prop, jsonPointers) { - var path = jsonPointers // false by default - ? toQuotedString('/' + escapeJsonPointer(prop)) - : toQuotedString(getProperty(prop)); - return joinPaths(currentPath, path); -} - - -var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; -var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; -function getData($data, lvl, paths) { - var up, jsonPointer, data, matches; - if ($data === '') return 'rootData'; - if ($data[0] == '/') { - if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); - jsonPointer = $data; - data = 'rootData'; - } else { - matches = $data.match(RELATIVE_JSON_POINTER); - if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); - up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer == '#') { - if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); - return paths[lvl - up]; - } - - if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); - data = 'data' + ((lvl - up) || ''); - if (!jsonPointer) return data; - } + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this - var expr = data; - var segments = jsonPointer.split('/'); - for (var i=0; i<segments.length; i++) { - var segment = segments[i]; - if (segment) { - data += getProperty(unescapeJsonPointer(segment)); - expr += ' && ' + data; + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false } } - return expr; -} + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) -function joinPaths (a, b) { - if (a == '""') return b; - return (a + ' + ' + b).replace(/' \+ '/g, ''); -} - + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } -function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); -} + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + case '\\': + clearStateChar() + escaping = true + continue -function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); -} + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -function escapeJsonPointer(str) { - return str.replace(/~/g, '~0').replace(/\//g, '~1'); -} + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + case '(': + if (inClass) { + re += '(' + continue + } -function unescapeJsonPointer(str) { - return str.replace(/~1/g, '/').replace(/~0/g, '~'); -} + if (!stateChar) { + re += '\\(' + continue + } + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } -"use strict"; + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:<pattern>)<type> + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + clearStateChar() + re += '|' + continue -var _slicedToArray2; + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} + if (inClass) { + re += '\\' + c + continue + } -var _asyncToGenerator2; + inClass = true + classStart = i + reClassStart = re.length + re += c + continue -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } -var _fs; + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + // finish up the class. + hasMagic = true + inClass = false + re += c + continue -var _npmResolver; + default: + // swallow any state char that wasn't consumed + clearStateChar() -function _load_npmResolver() { - return _npmResolver = _interopRequireDefault(__webpack_require__(126)); -} + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } -var _envReplace; + re += c -function _load_envReplace() { - return _envReplace = _interopRequireDefault(__webpack_require__(383)); -} + } // switch + } // for -var _baseRegistry; + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } -function _load_baseRegistry() { - return _baseRegistry = _interopRequireDefault(__webpack_require__(364)); -} + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } -var _misc; + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) -function _load_misc() { - return _misc = __webpack_require__(10); -} + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type -var _path; + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } -function _load_path() { - return _path = __webpack_require__(208); -} + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } -var _isRequestToRegistry; + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } -function _load_isRequestToRegistry() { - return _isRequestToRegistry = _interopRequireDefault(__webpack_require__(365)); -} + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + nlLast += nlAfter -const userHome = __webpack_require__(86).default; -const path = __webpack_require__(1); -const url = __webpack_require__(11); -const ini = __webpack_require__(516); + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter -const DEFAULT_REGISTRY = 'https://registry.npmjs.org/'; -const REGEX_REGISTRY_PREFIX = /^https?:/; -const REGEX_REGISTRY_SUFFIX = /registry\/?$/; + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } -function getGlobalPrefix() { - if (process.env.PREFIX) { - return process.env.PREFIX; - } else if (process.platform === 'win32') { - // c:\node\node.exe --> prefix=c:\node\ - return path.dirname(process.execPath); - } else { - // /usr/local/bin/node --> prefix=/usr/local - let prefix = path.dirname(path.dirname(process.execPath)); + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } - // destdir only is respected on Unix - if (process.env.DESTDIR) { - prefix = path.join(process.env.DESTDIR, prefix); - } + if (addPatternStart) { + re = patternStart + re + } - return prefix; + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] } -} -class NpmRegistry extends (_baseRegistry || _load_baseRegistry()).default { - constructor(cwd, registries, requestManager, reporter) { - super(cwd, registries, requestManager, reporter); - this.folder = 'node_modules'; + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) } - static escapeName(name) { - // scoped packages contain slashes and the npm registry expects them to be escaped - return name.replace('/', '%2f'); + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') } - request(pathname) { - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let packageName = arguments[2]; + regExp._glob = pattern + regExp._src = re - const registry = this.getRegistry(packageName || pathname); - const requestUrl = url.resolve(registry, pathname); - const alwaysAuth = this.getRegistryOrGlobalOption(registry, 'always-auth'); + return regExp +} - const headers = Object.assign({ - Accept: 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*' - }, opts.headers); +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} - const packageIdent = packageName || pathname; - const isScoppedPackage = packageIdent.match(/^@|\/@/); +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp - if (alwaysAuth || isScoppedPackage) { - const authorization = this.getAuth(packageName || pathname); - if (authorization) { - headers.authorization = authorization; - } - } + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set - return this.requestManager.request({ - url: requestUrl, - method: opts.method, - body: opts.body, - auth: opts.auth, - headers, - json: !opts.buffer, - buffer: opts.buffer, - process: opts.process, - gzip: true - }); + if (!set.length) { + this.regexp = false + return this.regexp } + var options = this.options - checkOutdated(config, name, range) { - var _this = this; + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const req = yield _this.request(NpmRegistry.escapeName(name), { - headers: { Accept: 'application/json' } - }); - if (!req) { - throw new Error('couldnt find ' + name); - } + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') - const repository = req.repository, - homepage = req.homepage; + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' - const url = homepage || repository && repository.url || ''; + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' - return { - latest: req['dist-tags'].latest, - wanted: (yield (_npmResolver || _load_npmResolver()).default.findVersionInRegistryResponse(config, range, req)).version, - url - }; - })(); + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false } + return this.regexp +} - getPossibleConfigLocations(filename, reporter) { - var _this2 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const possibles = [[false, path.join(_this2.cwd, filename)], [true, _this2.config.userconfig || path.join(userHome, filename)], [false, path.join(getGlobalPrefix(), filename)]]; - - const foldersFromRootToCwd = (0, (_path || _load_path()).getPosixPath)(_this2.cwd).split('/'); - while (foldersFromRootToCwd.length > 1) { - possibles.push([false, path.join(foldersFromRootToCwd.join(path.sep), filename)]); - foldersFromRootToCwd.pop(); - } - - const actuals = []; - for (const _ref of possibles) { - var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); - - const isHome = _ref2[0]; - const loc = _ref2[1]; - - reporter.verbose(reporter.lang('configPossibleFile', loc)); - if (yield (_fs || _load_fs()).exists(loc)) { - reporter.verbose(reporter.lang('configFileFound', loc)); - actuals.push([isHome, loc, yield (_fs || _load_fs()).readFile(loc)]); - } - } - return actuals; - })(); +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) } + return list +} - loadConfig() { - var _this3 = this; +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // docs: https://docs.npmjs.com/misc/config - _this3.mergeEnv('npm_config_'); + if (f === '/' && partial) return true - for (const _ref3 of yield _this3.getPossibleConfigLocations('.npmrc', _this3.reporter)) { - var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 3); + var options = this.options - const loc = _ref4[1]; - const file = _ref4[2]; + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } - const config = (_baseRegistry || _load_baseRegistry()).default.normalizeConfig(ini.parse(file)); - for (const key in config) { - config[key] = (0, (_envReplace || _load_envReplace()).default)(config[key]); - } + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - // normalize offline mirror path relative to the current npmrc - const offlineLoc = config['yarn-offline-mirror']; - // don't normalize if we already have a mirror path - if (!_this3.config['yarn-offline-mirror'] && offlineLoc) { - const mirrorLoc = config['yarn-offline-mirror'] = path.resolve(path.dirname(loc), offlineLoc); - yield (_fs || _load_fs()).mkdirp(mirrorLoc); - } + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - _this3.config = Object.assign({}, config, _this3.config); - } - })(); - } + var set = this.set + this.debug(this.pattern, 'set', set) - getScope(packageName) { - return !packageName || packageName[0] !== '@' ? '' : packageName.split(/\/|%2f/)[0]; + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break } - getRegistry(packageName) { - // Try extracting registry from the url, then scoped registry, and default registry - if (packageName.match(/^https?:/)) { - const availableRegistries = this.getAvailableRegistries(); - const registry = availableRegistries.find(registry => packageName.startsWith(registry)); - if (registry) { - return (0, (_misc || _load_misc()).addSuffix)(registry, '/'); - } + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] } - - for (const scope of [this.getScope(packageName), '']) { - const registry = this.getScopedOption(scope, 'registry') || this.registries.yarn.getScopedOption(scope, 'registry'); - if (registry) { - return (0, (_misc || _load_misc()).addSuffix)(String(registry), '/'); - } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate } - - return DEFAULT_REGISTRY; } - getAuth(packageName) { - if (this.token) { - return this.token; - } + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} - const baseRegistry = this.getRegistry(packageName); - const registries = [baseRegistry]; +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options - if (baseRegistry === `https://registry.yarnpkg.com/`) { - registries.push(`https://registry.npmjs.org/`); - } + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - for (const registry of registries) { - // Check for bearer token. - const authToken = this.getRegistryOrGlobalOption(registry, '_authToken'); - if (authToken) { - return `Bearer ${String(authToken)}`; + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true } - // Check for basic auth token. - const auth = this.getRegistryOrGlobalOption(registry, '_auth'); - if (auth) { - return `Basic ${String(auth)}`; + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } } - // Check for basic username/password auth. - const username = this.getRegistryOrGlobalOption(registry, 'username'); - const password = this.getRegistryOrGlobalOption(registry, '_password'); - if (username && password) { - const pw = new Buffer(String(password), 'base64').toString(); - return 'Basic ' + new Buffer(String(username) + ':' + pw).toString('base64'); + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true } + return false } - return ''; - } + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } - getScopedOption(scope, option) { - return this.getOption(scope + (scope ? ':' : '') + option); + if (!hit) return false } - getRegistryOption(registry, option) { - const pre = REGEX_REGISTRY_PREFIX; - const suf = REGEX_REGISTRY_SUFFIX; - - // When registry is used config scope, the trailing '/' is required - const reg = (0, (_misc || _load_misc()).addSuffix)(registry, '/'); + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* - // 1st attempt, try to get option for the given registry URL - // 2nd attempt, remove the 'https?:' prefix of the registry URL - // 3nd attempt, remove the 'registry/?' suffix of the registry URL - return this.getScopedOption(reg, option) || reg.match(pre) && this.getRegistryOption(reg.replace(pre, ''), option) || reg.match(suf) && this.getRegistryOption(reg.replace(suf, ''), option); + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd } - getRegistryOrGlobalOption(registry, option) { - return this.getRegistryOption(registry, option) || this.getOption(option); - } + // should be unreachable. + throw new Error('wtf?') } -exports.default = NpmRegistry; -NpmRegistry.filename = 'package.json'; + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} + /***/ }), -/* 44 */ +/* 58 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Copyright 2015 Joyent, Inc. +module.exports = { + read: read, + write: write +}; -Object.defineProperty(exports, "__esModule", { - value: true -}); +var assert = __webpack_require__(11); +var asn1 = __webpack_require__(50); +var crypto = __webpack_require__(8); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); -var _baseResolver; +var pkcs1 = __webpack_require__(225); +var pkcs8 = __webpack_require__(117); +var sshpriv = __webpack_require__(143); +var rfc4253 = __webpack_require__(75); -function _load_baseResolver() { - return _baseResolver = _interopRequireDefault(__webpack_require__(83)); -} +var errors = __webpack_require__(44); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/* + * For reading we support both PKCS#1 and PKCS#8. If we find a private key, + * we just take the public component of it and use that. + */ +function read(buf, options, forceType) { + var input = buf; + if (typeof (buf) !== 'string') { + assert.buffer(buf, 'buf'); + buf = buf.toString('ascii'); + } -class ExoticResolver extends (_baseResolver || _load_baseResolver()).default { + var lines = buf.trim().split('\n'); - static isVersion(pattern) { - const proto = this.protocol; - if (proto) { - return pattern.startsWith(`${proto}:`); - } else { - throw new Error('No protocol specified'); - } - } -} -exports.default = ExoticResolver; + var m = lines[0].match(/*JSSTYLED*/ + /[-]+[ ]*BEGIN ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); + assert.ok(m, 'invalid PEM header'); -/***/ }), -/* 45 */ -/***/ (function(module, exports, __webpack_require__) { + var m2 = lines[lines.length - 1].match(/*JSSTYLED*/ + /[-]+[ ]*END ([A-Z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/); + assert.ok(m2, 'invalid PEM footer'); -"use strict"; + /* Begin and end banners must match key type */ + assert.equal(m[2], m2[2]); + var type = m[2].toLowerCase(); + var alg; + if (m[1]) { + /* They also must match algorithms, if given */ + assert.equal(m[1], m2[1], 'PEM header and footer mismatch'); + alg = m[1].trim(); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.exec = exports.queue = undefined; -exports.spawn = spawn; + var headers = {}; + while (true) { + lines = lines.slice(1); + m = lines[0].match(/*JSSTYLED*/ + /^([A-Za-z0-9-]+): (.+)$/); + if (!m) + break; + headers[m[1].toLowerCase()] = m[2]; + } -var _constants; + var cipher, key, iv; + if (headers['proc-type']) { + var parts = headers['proc-type'].split(','); + if (parts[0] === '4' && parts[1] === 'ENCRYPTED') { + if (typeof (options.passphrase) === 'string') { + options.passphrase = new Buffer( + options.passphrase, 'utf-8'); + } + if (!Buffer.isBuffer(options.passphrase)) { + throw (new errors.KeyEncryptedError( + options.filename, 'PEM')); + } else { + parts = headers['dek-info'].split(','); + assert.ok(parts.length === 2); + cipher = parts[0].toLowerCase(); + iv = new Buffer(parts[1], 'hex'); + key = utils.opensslKeyDeriv(cipher, iv, + options.passphrase, 1).key; + } + } + } -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + /* Chop off the first and last lines */ + lines = lines.slice(0, -1).join(''); + buf = new Buffer(lines, 'base64'); -var _blockingQueue; + if (cipher && key && iv) { + var cipherStream = crypto.createDecipheriv(cipher, key, iv); + var chunk, chunks = []; + cipherStream.once('error', function (e) { + if (e.toString().indexOf('bad decrypt') !== -1) { + throw (new Error('Incorrect passphrase ' + + 'supplied, could not decrypt key')); + } + throw (e); + }); + cipherStream.write(buf); + cipherStream.end(); + while ((chunk = cipherStream.read()) !== null) + chunks.push(chunk); + buf = Buffer.concat(chunks); + } -function _load_blockingQueue() { - return _blockingQueue = _interopRequireDefault(__webpack_require__(84)); -} + /* The new OpenSSH internal format abuses PEM headers */ + if (alg && alg.toLowerCase() === 'openssh') + return (sshpriv.readSSHPrivate(type, buf, options)); + if (alg && alg.toLowerCase() === 'ssh2') + return (rfc4253.readType(type, buf, options)); -var _errors; + var der = new asn1.BerReader(buf); + der.originalInput = input; -function _load_errors() { - return _errors = __webpack_require__(3); + /* + * All of the PEM file types start with a sequence tag, so chop it + * off here + */ + der.readSequence(); + + /* PKCS#1 type keys name an algorithm in the banner explicitly */ + if (alg) { + if (forceType) + assert.strictEqual(forceType, 'pkcs1'); + return (pkcs1.readPkcs1(alg, type, der)); + } else { + if (forceType) + assert.strictEqual(forceType, 'pkcs8'); + return (pkcs8.readPkcs8(alg, type, der)); + } } -var _promise; +function write(key, options, type) { + assert.object(key); -function _load_promise() { - return _promise = __webpack_require__(64); -} + var alg = {'ecdsa': 'EC', 'rsa': 'RSA', 'dsa': 'DSA'}[key.type]; + var header; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var der = new asn1.BerWriter(); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (PrivateKey.isPrivateKey(key)) { + if (type && type === 'pkcs8') { + header = 'PRIVATE KEY'; + pkcs8.writePkcs8(der, key); + } else { + if (type) + assert.strictEqual(type, 'pkcs1'); + header = alg + ' PRIVATE KEY'; + pkcs1.writePkcs1(der, key); + } -/* global child_process$spawnOpts */ + } else if (Key.isKey(key)) { + if (type && type === 'pkcs1') { + header = alg + ' PUBLIC KEY'; + pkcs1.writePkcs1(der, key); + } else { + if (type) + assert.strictEqual(type, 'pkcs8'); + header = 'PUBLIC KEY'; + pkcs8.writePkcs8(der, key); + } -const child = __webpack_require__(111); + } else { + throw (new Error('key is not a Key or PrivateKey')); + } -const queue = exports.queue = new (_blockingQueue || _load_blockingQueue()).default('child', (_constants || _load_constants()).CHILD_CONCURRENCY); + var tmp = der.buffer.toString('base64'); + var len = tmp.length + (tmp.length / 64) + + 18 + 16 + header.length*2 + 10; + var buf = new Buffer(len); + var o = 0; + o += buf.write('-----BEGIN ' + header + '-----\n', o); + for (var i = 0; i < tmp.length; ) { + var limit = i + 64; + if (limit > tmp.length) + limit = tmp.length; + o += buf.write(tmp.slice(i, limit), o); + buf[o++] = 10; + i = limit; + } + o += buf.write('-----END ' + header + '-----\n', o); -// TODO: this uid check is kinda whack -let uid = 0; + return (buf.slice(0, o)); +} -const exec = exports.exec = (0, (_promise || _load_promise()).promisify)(child.exec); -function spawn(program, args) { - let opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - let onData = arguments[3]; +/***/ }), +/* 59 */ +/***/ (function(module, exports) { - return queue.push(opts.cwd || String(++uid), () => new Promise((resolve, reject) => { - const proc = child.spawn(program, args, opts); +module.exports = require("net"); - let processingDone = false; - let processClosed = false; - let err = null; +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { - let stdout = ''; +"use strict"; - proc.on('error', err => { - if (err.code === 'ENOENT') { - reject(new (_errors || _load_errors()).MessageError(`Couldn't find the binary ${program}`)); - } else { - reject(err); - } - }); - function updateStdout(chunk) { - stdout += chunk; - if (onData) { - onData(chunk); - } - } - function finish() { - if (err) { - reject(err); - } else { - resolve(stdout.trim()); - } - } +module.exports = { + copy: copy, + checkDataType: checkDataType, + checkDataTypes: checkDataTypes, + coerceToTypes: coerceToTypes, + toHash: toHash, + getProperty: getProperty, + escapeQuotes: escapeQuotes, + ucs2length: __webpack_require__(346), + varOccurences: varOccurences, + varReplace: varReplace, + cleanUpCode: cleanUpCode, + cleanUpVarErrors: cleanUpVarErrors, + schemaHasRules: schemaHasRules, + schemaHasRulesExcept: schemaHasRulesExcept, + stableStringify: __webpack_require__(217), + toQuotedString: toQuotedString, + getPathExpr: getPathExpr, + getPath: getPath, + getData: getData, + unescapeFragment: unescapeFragment, + escapeFragment: escapeFragment, + escapeJsonPointer: escapeJsonPointer +}; - if (typeof opts.process === 'function') { - opts.process(proc, updateStdout, reject, function () { - if (processClosed) { - finish(); - } else { - processingDone = true; - } - }); - } else { - if (proc.stderr) { - proc.stderr.on('data', updateStdout); - } - if (proc.stdout) { - proc.stdout.on('data', updateStdout); - } +function copy(o, to) { + to = to || {}; + for (var key in o) to[key] = o[key]; + return to; +} - processingDone = true; - } - proc.on('close', code => { - if (code >= 1) { - // TODO make this output nicer - err = new (_errors || _load_errors()).SpawnError(['Command failed.', `Exit code: ${code}`, `Command: ${program}`, `Arguments: ${args.join(' ')}`, `Directory: ${opts.cwd || process.cwd()}`, `Output:\n${stdout.trim()}`].join('\n')); - err.EXIT_CODE = code; - } +function checkDataType(dataType, data, negate) { + var EQUAL = negate ? ' !== ' : ' === ' + , AND = negate ? ' || ' : ' && ' + , OK = negate ? '!' : '' + , NOT = negate ? '' : '!'; + switch (dataType) { + case 'null': return data + EQUAL + 'null'; + case 'array': return OK + 'Array.isArray(' + data + ')'; + case 'object': return '(' + OK + data + AND + + 'typeof ' + data + EQUAL + '"object"' + AND + + NOT + 'Array.isArray(' + data + '))'; + case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + + NOT + '(' + data + ' % 1)' + + AND + data + EQUAL + data + ')'; + default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; + } +} - if (processingDone || err) { - finish(); - } else { - processClosed = true; + +function checkDataTypes(dataTypes, data) { + switch (dataTypes.length) { + case 1: return checkDataType(dataTypes[0], data, true); + default: + var code = ''; + var types = toHash(dataTypes); + if (types.array && types.object) { + code = types.null ? '(': '(!' + data + ' || '; + code += 'typeof ' + data + ' !== "object")'; + delete types.null; + delete types.array; + delete types.object; } - }); - })); + if (types.number) delete types.integer; + for (var t in types) + code += (code ? ' && ' : '' ) + checkDataType(t, data, true); + + return code; + } } -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { -var isObject = __webpack_require__(91); -module.exports = function(it){ - if(!isObject(it))throw TypeError(it + ' is not an object!'); - return it; -}; +var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); +function coerceToTypes(optionCoerceTypes, dataTypes) { + if (Array.isArray(dataTypes)) { + var types = []; + for (var i=0; i<dataTypes.length; i++) { + var t = dataTypes[i]; + if (COERCE_TO_TYPES[t]) types[types.length] = t; + else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t; + } + if (types.length) return types; + } else if (COERCE_TO_TYPES[dataTypes]) { + return [dataTypes]; + } else if (optionCoerceTypes === 'array' && dataTypes === 'array') { + return ['array']; + } +} -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(20); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __webpack_require__(252); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __webpack_require__(254); - exports.Duplex = __webpack_require__(56); - exports.Transform = __webpack_require__(253); - exports.PassThrough = __webpack_require__(580); +function toHash(arr) { + var hash = {}; + for (var i=0; i<arr.length; i++) hash[arr[i]] = true; + return hash; } -/***/ }), -/* 48 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright 2015 Joyent, Inc. +var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; +var SINGLE_QUOTE = /'|\\/g; +function getProperty(key) { + return typeof key == 'number' + ? '[' + key + ']' + : IDENTIFIER.test(key) + ? '.' + key + : "['" + escapeQuotes(key) + "']"; +} -module.exports = { - read: read.bind(undefined, false, undefined), - readType: read.bind(undefined, false), - write: write, - /* semi-private api, used by sshpk-agent */ - readPartial: read.bind(undefined, true), - /* shared with ssh format */ - readInternal: read, - keyTypeToAlg: keyTypeToAlg, - algToKeyType: algToKeyType -}; +function escapeQuotes(str) { + return str.replace(SINGLE_QUOTE, '\\$&') + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\f/g, '\\f') + .replace(/\t/g, '\\t'); +} -var assert = __webpack_require__(9); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var SSHBuffer = __webpack_require__(108); -function algToKeyType(alg) { - assert.string(alg); - if (alg === 'ssh-dss') - return ('dsa'); - else if (alg === 'ssh-rsa') - return ('rsa'); - else if (alg === 'ssh-ed25519') - return ('ed25519'); - else if (alg === 'ssh-curve25519') - return ('curve25519'); - else if (alg.match(/^ecdsa-sha2-/)) - return ('ecdsa'); - else - throw (new Error('Unknown algorithm ' + alg)); +function varOccurences(str, dataVar) { + dataVar += '[^0-9]'; + var matches = str.match(new RegExp(dataVar, 'g')); + return matches ? matches.length : 0; } -function keyTypeToAlg(key) { - assert.object(key); - if (key.type === 'dsa') - return ('ssh-dss'); - else if (key.type === 'rsa') - return ('ssh-rsa'); - else if (key.type === 'ed25519') - return ('ssh-ed25519'); - else if (key.type === 'curve25519') - return ('ssh-curve25519'); - else if (key.type === 'ecdsa') - return ('ecdsa-sha2-' + key.part.curve.data.toString()); - else - throw (new Error('Unknown key type ' + key.type)); + +function varReplace(str, dataVar, expr) { + dataVar += '([^0-9])'; + expr = expr.replace(/\$/g, '$$$$'); + return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); } -function read(partial, type, buf, options) { - if (typeof (buf) === 'string') - buf = new Buffer(buf); - assert.buffer(buf, 'buf'); - var key = {}; +var EMPTY_ELSE = /else\s*{\s*}/g + , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g + , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g; +function cleanUpCode(out) { + return out.replace(EMPTY_ELSE, '') + .replace(EMPTY_IF_NO_ELSE, '') + .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))'); +} - var parts = key.parts = []; - var sshbuf = new SSHBuffer({buffer: buf}); - var alg = sshbuf.readString(); - assert.ok(!sshbuf.atEnd(), 'key must have at least one part'); +var ERRORS_REGEXP = /[^v\.]errors/g + , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g + , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g + , RETURN_VALID = 'return errors === 0;' + , RETURN_TRUE = 'validate.errors = null; return true;' + , RETURN_ASYNC = /if \(errors === 0\) return true;\s*else throw new ValidationError\(vErrors\);/ + , RETURN_TRUE_ASYNC = 'return true;'; - key.type = algToKeyType(alg); +function cleanUpVarErrors(out, async) { + var matches = out.match(ERRORS_REGEXP); + if (!matches || matches.length !== 2) return out; + return async + ? out.replace(REMOVE_ERRORS_ASYNC, '') + .replace(RETURN_ASYNC, RETURN_TRUE_ASYNC) + : out.replace(REMOVE_ERRORS, '') + .replace(RETURN_VALID, RETURN_TRUE); +} - var partCount = algs.info[key.type].parts.length; - if (type && type === 'private') - partCount = algs.privInfo[key.type].parts.length; - while (!sshbuf.atEnd() && parts.length < partCount) - parts.push(sshbuf.readPart()); - while (!partial && !sshbuf.atEnd()) - parts.push(sshbuf.readPart()); +function schemaHasRules(schema, rules) { + for (var key in schema) if (rules[key]) return true; +} - assert.ok(parts.length >= 1, - 'key must have at least one part'); - assert.ok(partial || sshbuf.atEnd(), - 'leftover bytes at end of key'); - var Constructor = Key; - var algInfo = algs.info[key.type]; - if (type === 'private' || algInfo.parts.length !== parts.length) { - algInfo = algs.privInfo[key.type]; - Constructor = PrivateKey; - } - assert.strictEqual(algInfo.parts.length, parts.length); +function schemaHasRulesExcept(schema, rules, exceptKeyword) { + for (var key in schema) if (key != exceptKeyword && rules[key]) return true; +} - if (key.type === 'ecdsa') { - var res = /^ecdsa-sha2-(.+)$/.exec(alg); - assert.ok(res !== null); - assert.strictEqual(res[1], parts[0].data.toString()); - } - var normalized = true; - for (var i = 0; i < algInfo.parts.length; ++i) { - parts[i].name = algInfo.parts[i]; - if (parts[i].name !== 'curve' && - algInfo.normalize !== false) { - var p = parts[i]; - var nd = utils.mpNormalize(p.data); - if (nd !== p.data) { - p.data = nd; - normalized = false; - } - } - } +function toQuotedString(str) { + return '\'' + escapeQuotes(str) + '\''; +} - if (normalized) - key._rfc4253Cache = sshbuf.toBuffer(); - if (partial && typeof (partial) === 'object') { - partial.remainder = sshbuf.remainder(); - partial.consumed = sshbuf._offset; - } +function getPathExpr(currentPath, expr, jsonPointers, isNumber) { + var path = jsonPointers // false by default + ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') + : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''); + return joinPaths(currentPath, path); +} - return (new Constructor(key)); + +function getPath(currentPath, prop, jsonPointers) { + var path = jsonPointers // false by default + ? toQuotedString('/' + escapeJsonPointer(prop)) + : toQuotedString(getProperty(prop)); + return joinPaths(currentPath, path); } -function write(key, options) { - assert.object(key); - var alg = keyTypeToAlg(key); - var i; +var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; +var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; +function getData($data, lvl, paths) { + var up, jsonPointer, data, matches; + if ($data === '') return 'rootData'; + if ($data[0] == '/') { + if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); + jsonPointer = $data; + data = 'rootData'; + } else { + matches = $data.match(RELATIVE_JSON_POINTER); + if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); + up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer == '#') { + if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); + return paths[lvl - up]; + } - var algInfo = algs.info[key.type]; - if (PrivateKey.isPrivateKey(key)) - algInfo = algs.privInfo[key.type]; - var parts = algInfo.parts; + if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); + data = 'data' + ((lvl - up) || ''); + if (!jsonPointer) return data; + } - var buf = new SSHBuffer({}); + var expr = data; + var segments = jsonPointer.split('/'); + for (var i=0; i<segments.length; i++) { + var segment = segments[i]; + if (segment) { + data += getProperty(unescapeJsonPointer(segment)); + expr += ' && ' + data; + } + } + return expr; +} - buf.writeString(alg); - for (i = 0; i < parts.length; ++i) { - var data = key.part[parts[i]].data; - if (algInfo.normalize !== false) - data = utils.mpNormalize(data); - buf.writeBuffer(data); - } +function joinPaths (a, b) { + if (a == '""') return b; + return (a + ' + ' + b).replace(/' \+ '/g, ''); +} - return (buf.toBuffer()); + +function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); } -/***/ }), -/* 49 */ -/***/ (function(module, exports) { +function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); +} -module.exports = require("events"); -/***/ }), -/* 50 */ -/***/ (function(module, exports) { +function escapeJsonPointer(str) { + return str.replace(/~/g, '~0').replace(/\//g, '~1'); +} + + +function unescapeJsonPointer(str) { + return str.replace(/~1/g, '/').replace(/~0/g, '~'); +} -module.exports = require("http"); /***/ }), -/* 51 */ +/* 61 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -32385,1281 +33425,1668 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _asyncToGenerator2; +var _baseResolver; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function _load_baseResolver() { + return _baseResolver = _interopRequireDefault(__webpack_require__(95)); } -exports.stringifyLangArgs = stringifyLangArgs; - -var _format; - -function _load_format() { - return _format = __webpack_require__(202); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _index; +class ExoticResolver extends (_baseResolver || _load_baseResolver()).default { -function _load_index() { - return _index = _interopRequireWildcard(__webpack_require__(203)); + static isVersion(pattern) { + const proto = this.protocol; + if (proto) { + return pattern.startsWith(`${proto}:`); + } else { + throw new Error('No protocol specified'); + } + } } +exports.default = ExoticResolver; -var _isCi; - -function _load_isCi() { - return _isCi = _interopRequireDefault(__webpack_require__(153)); -} +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +"use strict"; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/* eslint no-unused-vars: 0 */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.home = undefined; -const util = __webpack_require__(2); -const EventEmitter = __webpack_require__(49).EventEmitter; +var _rootUser; -function stringifyLangArgs(args) { - return args.map(function (val) { - if (val != null && val.inspect) { - return val.inspect(); - } else { - try { - const str = JSON.stringify(val) || val + ''; - // should match all "u001b" that follow an odd number of backslashes and convert them to ESC - // we do this because the JSON.stringify process has escaped these characters - return str.replace(/((?:^|[^\\])(?:\\{2})*)\\u001[bB]/g, '$1\u001b'); - } catch (e) { - return util.inspect(val); - } - } - }); +function _load_rootUser() { + return _rootUser = _interopRequireDefault(__webpack_require__(169)); } -class BaseReporter { - constructor() { - let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - const lang = 'en'; - this.language = lang; +const path = __webpack_require__(0); - this.stdout = opts.stdout || process.stdout; - this.stderr = opts.stderr || process.stderr; - this.stdin = opts.stdin || this._getStandardInput(); - this.emoji = !!opts.emoji; - this.noProgress = !!opts.noProgress || (_isCi || _load_isCi()).default; - this.isVerbose = !!opts.verbose; +const home = exports.home = __webpack_require__(47).homedir(); - // $FlowFixMe: this is valid! - this.isTTY = this.stdout.isTTY; +const userHomeDir = (_rootUser || _load_rootUser()).default ? path.resolve('/usr/local/share') : home; - this.peakMemory = 0; - this.startTime = Date.now(); - this.format = (_format || _load_format()).defaultFormatter; - } +exports.default = userHomeDir; - lang(key) { - const msg = (_index || _load_index())[this.language][key] || (_index || _load_index()).en[key]; - if (!msg) { - throw new ReferenceError(`Unknown language key ${key}`); - } +/***/ }), +/* 63 */ +/***/ (function(module, exports) { - // stringify args +module.exports = function(it){ + if(typeof it != 'function')throw TypeError(it + ' is not a function!'); + return it; +}; - for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } +/***/ }), +/* 64 */ +/***/ (function(module, exports) { - const stringifiedArgs = stringifyLangArgs(args); +// 7.2.1 RequireObjectCoercible(argument) +module.exports = function(it){ + if(it == undefined)throw TypeError("Can't call method on " + it); + return it; +}; - // replace $0 placeholders with args - return msg.replace(/\$(\d+)/g, (str, i) => { - return stringifiedArgs[i]; - }); - } +/***/ }), +/* 65 */ +/***/ (function(module, exports, __webpack_require__) { - verbose(msg) { - if (this.isVerbose) { - this._verbose(msg); - } - } +var isObject = __webpack_require__(43) + , document = __webpack_require__(13).document + // in old IE typeof document.createElement is 'object' + , is = isObject(document) && isObject(document.createElement); +module.exports = function(it){ + return is ? document.createElement(it) : {}; +}; - verboseInspect(val) { - if (this.isVerbose) { - this._verboseInspect(val); - } - } +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { - _verbose(msg) {} - _verboseInspect(val) {} - - _getStandardInput() { - let standardInput; +var global = __webpack_require__(13) + , core = __webpack_require__(21) + , ctx = __webpack_require__(37) + , hide = __webpack_require__(29) + , PROTOTYPE = 'prototype'; - // Accessing stdin in a win32 headless process (e.g., Visual Studio) may throw an exception. - try { - standardInput = process.stdin; - } catch (e) { - console.warn(e.message); - delete process.stdin; - // $FlowFixMe: this is valid! - process.stdin = new EventEmitter(); - standardInput = process.stdin; +var $export = function(type, name, source){ + var IS_FORCED = type & $export.F + , IS_GLOBAL = type & $export.G + , IS_STATIC = type & $export.S + , IS_PROTO = type & $export.P + , IS_BIND = type & $export.B + , IS_WRAP = type & $export.W + , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) + , expProto = exports[PROTOTYPE] + , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] + , key, own, out; + if(IS_GLOBAL)source = name; + for(key in source){ + // contains in native + own = !IS_FORCED && target && target[key] !== undefined; + if(own && key in exports)continue; + // export native or passed + out = own ? target[key] : source[key]; + // prevent global pollution for namespaces + exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] + // bind timers to global for call from export context + : IS_BIND && own ? ctx(out, global) + // wrap global constructors for prevent change them in library + : IS_WRAP && target[key] == out ? (function(C){ + var F = function(a, b, c){ + if(this instanceof C){ + switch(arguments.length){ + case 0: return new C; + case 1: return new C(a); + case 2: return new C(a, b); + } return new C(a, b, c); + } return C.apply(this, arguments); + }; + F[PROTOTYPE] = C[PROTOTYPE]; + return F; + // make static versions for prototype methods + })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; + // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% + if(IS_PROTO){ + (exports.virtual || (exports.virtual = {}))[key] = out; + // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% + if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } - - return standardInput; } +}; +// type bitmap +$export.F = 1; // forced +$export.G = 2; // global +$export.S = 4; // static +$export.P = 8; // proto +$export.B = 16; // bind +$export.W = 32; // wrap +$export.U = 64; // safe +$export.R = 128; // real proto method for `library` +module.exports = $export; - initPeakMemoryCounter() { - this.checkPeakMemory(); - this.peakMemoryInterval = setInterval(() => { - this.checkPeakMemory(); - }, 1000); - } +/***/ }), +/* 67 */ +/***/ (function(module, exports, __webpack_require__) { - checkPeakMemory() { - var _process$memoryUsage = process.memoryUsage(); +var def = __webpack_require__(38).f + , has = __webpack_require__(42) + , TAG = __webpack_require__(9)('toStringTag'); - const heapTotal = _process$memoryUsage.heapTotal; +module.exports = function(it, tag, stat){ + if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); +}; - if (heapTotal > this.peakMemory) { - this.peakMemory = heapTotal; - } - } +/***/ }), +/* 68 */ +/***/ (function(module, exports, __webpack_require__) { - close() { - if (this.peakMemoryInterval) { - clearInterval(this.peakMemoryInterval); - this.peakMemoryInterval = null; - } - } +var shared = __webpack_require__(104)('keys') + , uid = __webpack_require__(107); +module.exports = function(key){ + return shared[key] || (shared[key] = uid(key)); +}; - getTotalTime() { - return Date.now() - this.startTime; - } +/***/ }), +/* 69 */ +/***/ (function(module, exports) { - // TODO - list(key, items, hints) {} +// 7.1.4 ToInteger +var ceil = Math.ceil + , floor = Math.floor; +module.exports = function(it){ + return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); +}; - // Outputs basic tree structure to console - tree(key, obj) {} +/***/ }), +/* 70 */ +/***/ (function(module, exports, __webpack_require__) { - // called whenever we begin a step in the CLI. - step(current, total, message, emoji) {} +// to indexed object, toObject with fallback for non-array-like ES3 strings +var IObject = __webpack_require__(125) + , defined = __webpack_require__(64); +module.exports = function(it){ + return IObject(defined(it)); +}; - // a error message has been triggered. this however does not always meant an abrupt - // program end. - error(message) {} +/***/ }), +/* 71 */ +/***/ (function(module, exports, __webpack_require__) { - // an info message has been triggered. this provides things like stats and diagnostics. - info(message) {} +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. - // a warning message has been triggered. - warn(message) {} +module.exports = glob - // a success message has been triggered. - success(message) {} +var fs = __webpack_require__(5) +var rp = __webpack_require__(112) +var minimatch = __webpack_require__(57) +var Minimatch = minimatch.Minimatch +var inherits = __webpack_require__(39) +var EE = __webpack_require__(46).EventEmitter +var path = __webpack_require__(0) +var assert = __webpack_require__(18) +var isAbsolute = __webpack_require__(73) +var globSync = __webpack_require__(208) +var common = __webpack_require__(113) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = __webpack_require__(210) +var util = __webpack_require__(2) +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored - // a simple log message - log(message) {} +var once = __webpack_require__(72) - // a shell command has been executed - command(command) {} +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} - // inspect and pretty-print any value - inspect(value) {} + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } - // the screen shown at the very start of the CLI - header(command, pkg) {} + return new Glob(pattern, options, cb) +} - // the screen shown at the very end of the CLI - footer(showPeakMemory) {} +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync - // - table(head, body) {} +// old api surface +glob.glob = glob - // render an activity spinner and return a function that will trigger an update - activity() { - return { - tick(name) {}, - end() {} - }; +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin } - // - activitySet(total, workers) { - return { - spinners: Array(workers).fill({ - clear() {}, - setPrefix() {}, - tick() {}, - end() {} - }), - end() {} - }; + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] } + return origin +} - // - question(question) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - return Promise.reject(new Error('Not implemented')); - } +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true - // - questionAffirm(question) { - var _this = this; + var g = new Glob(pattern, options) + var set = g.minimatch.set - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const condition = true; // trick eslint + if (!pattern) + return false - while (condition) { - let answer = yield _this.question(question); - answer = answer.toLowerCase(); + if (set.length > 1) + return true - if (answer === 'y' || answer === 'yes') { - return true; - } - if (answer === 'n' || answer === 'no') { - return false; - } + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } - _this.error('Invalid answer for question'); - } + return false +} - return false; - })(); +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null } - // prompt the user to select an option from an array - select(header, question, options) { - return Promise.reject(new Error('Not implemented')); + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) } - // render a progress bar and return a function which when called will trigger an update - progress(total) { - return function () {}; - } + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) - // utility function to disable progress bar - disableProgress() { - this.noProgress = true; - } + setopts(this, pattern, options) + this._didRealPath = false - // - prompt(message, choices) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + // process each pattern in the minimatch set + var n = this.minimatch.set.length - return Promise.reject(new Error('Not implemented')); + // The matches are stored as {<filename>: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) } -} -exports.default = BaseReporter; -/***/ }), -/* 52 */ -/***/ (function(module, exports, __webpack_require__) { + var self = this + this._processing = 0 -"use strict"; + this._emitQueue = [] + this._processQueue = [] + this.paused = false + if (this.noprocess) + return this -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (n === 0) + return done() -var _asyncToGenerator2; + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } } -exports.explodeHostedGitFragment = explodeHostedGitFragment; +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return -var _errors; + if (this.realpath && !this._didRealpath) + return this._realpath() -function _load_errors() { - return _errors = __webpack_require__(3); + common.finish(this) + this.emit('end', this.found) } -var _index; +Glob.prototype._realpath = function () { + if (this._didRealpath) + return -function _load_index() { - return _index = __webpack_require__(24); -} + this._didRealpath = true -var _gitResolver; + var n = this.matches.length + if (n === 0) + return this._finish() -function _load_gitResolver() { - return _gitResolver = _interopRequireDefault(__webpack_require__(61)); + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } } -var _exoticResolver; +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() -function _load_exoticResolver() { - return _exoticResolver = _interopRequireDefault(__webpack_require__(44)); -} + var found = Object.keys(matchset) + var self = this + var n = found.length -var _git; + if (n === 0) + return cb() -function _load_git() { - return _git = _interopRequireDefault(__webpack_require__(127)); + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) } -var _guessName; +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} -function _load_guessName() { - return _guessName = _interopRequireDefault(__webpack_require__(128)); +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} -function explodeHostedGitFragment(fragment, reporter) { - const preParts = fragment.split('@'); - if (preParts.length > 2) { - fragment = preParts[1] + '@' + preParts[2]; +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') } +} - const parts = fragment.split(':'); - - if (parts.length == 3) { - // protocol + host + folder - parts[1] = parts[1].indexOf('//') >= 0 ? parts[1].substr(2) : parts[1]; - fragment = parts[1] + '/' + parts[2]; - } else if (parts.length == 2) { - if (parts[0].indexOf('@') == -1) { - // protocol + host - fragment = parts[1]; - } else { - // host + folder - fragment = parts[0] + '/' + parts[1]; +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } } - } else if (parts.length == 1) { - fragment = parts[0]; - } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment)); } +} - const userParts = fragment.split('/'); - - if (userParts.length >= 2) { - if (userParts[0].indexOf('@') >= 0) { - userParts.shift(); - } +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') - const user = userParts.shift(); - const repoParts = userParts.join('/').split(/(?:[.]git)?#(.*)/); + if (this.aborted) + return - if (repoParts.length <= 3) { - return { - user, - repo: repoParts[0].replace('.git', ''), - hash: repoParts[1] || '' - }; - } + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return } - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment)); -} - -class HostedGitResolver extends (_exoticResolver || _load_exoticResolver()).default { - constructor(request, fragment) { - super(request, fragment); + //console.error('PROCESS %d', this._processing, pattern) - const exploded = this.exploded = explodeHostedGitFragment(fragment, this.reporter); - const user = exploded.user, - repo = exploded.repo, - hash = exploded.hash; - - this.user = user; - this.repo = repo; - this.hash = hash; + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ } + // now n is the index of the first one that is *not* a string. - static getTarballUrl(exploded, commit) { - exploded; - commit; - throw new Error('Not implemented'); - } + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return - static getGitHTTPUrl(exploded) { - exploded; - throw new Error('Not implemented'); - } + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break - static getGitHTTPBaseUrl(exploded) { - exploded; - throw new Error('Not implemented'); + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break } - static getGitSSHUrl(exploded) { - exploded; - throw new Error('Not implemented'); - } + var remain = pattern.slice(n) - static getHTTPFileUrl(exploded, filename, commit) { - exploded; - filename; - commit; - throw new Error('Not implemented'); - } + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix - getRefOverHTTP(url) { - var _this = this; + var abs = this._makeAbs(read) - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const gitUrl = (_git || _load_git()).default.npmUrlToGitUrl(url); - const client = new (_git || _load_git()).default(_this.config, gitUrl, _this.hash); + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() - let out = yield _this.config.requestManager.request({ - url: `${url}/info/refs?service=git-upload-pack`, - queue: _this.resolver.fetchingQueue - }); + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} - if (out) { - // clean up output - let lines = out.trim().split('\n'); +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} - // remove first two lines which contains compatibility info etc - lines = lines.slice(2); +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - // remove last line which contains the terminator "0000" - lines.pop(); + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() - // remove line lengths from start of each line - lines = lines.map(function (line) { - return line.slice(4); - }); + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' - out = lines.join('\n'); + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) } else { - throw new Error(_this.reporter.lang('hostedGitResolveError')); + m = e.match(pn) } - - const refs = (_git || _load_git()).default.parseRefs(out); - return client.setRef(refs); - })(); + if (m) + matchedEntries.push(e) + } } - resolveOverHTTP(url) { - var _this2 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const commit = yield _this2.getRefOverHTTP(url); - const config = _this2.config; - - - const tryRegistry = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (registry) { - const filename = (_index || _load_index()).registries[registry].filename; + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) - const href = _this2.constructor.getHTTPFileUrl(_this2.exploded, filename, commit); - const file = yield config.requestManager.request({ - url: href, - queue: _this2.resolver.fetchingQueue - }); - if (!file) { - return null; - } + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() - const tarballUrl = _this2.constructor.getTarballUrl(_this2.exploded, commit); - const json = yield config.readJson(href, function () { - return JSON.parse(file); - }); - json._uid = commit; - json._remote = { - resolved: tarballUrl, - type: 'tarball', - reference: tarballUrl, - registry - }; - return json; - }); + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. - return function tryRegistry(_x) { - return _ref.apply(this, arguments); - }; - })(); + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) - const file = yield tryRegistry(_this2.registry); - if (file) { - return file; + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e } - for (const registry in (_index || _load_index()).registries) { - if (registry === _this2.registry) { - continue; - } - - const file = yield tryRegistry(registry); - if (file) { - return file; - } + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } - return { - name: (0, (_guessName || _load_guessName()).default)(url), - version: '0.0.0', - _uid: commit, - _remote: { - hash: commit, - resolved: url, - type: 'tarball', - reference: url, - registry: 'npm' - } - }; - })(); + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) } + cb() +} - hasHTTPCapability(url) { - var _this3 = this; +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - return (yield _this3.config.requestManager.request({ - url, - method: 'HEAD', - queue: _this3.resolver.fetchingQueue, - followRedirect: false - })) !== false; - })(); - } + if (isIgnored(this, e)) + return - resolve() { - var _this4 = this; + if (this.paused) { + this._emitQueue.push([index, e]) + return + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // If we already have the tarball, just return it without having to make any HTTP requests. - const shrunk = _this4.request.getLocked('tarball'); - if (shrunk) { - return shrunk; - } + var abs = isAbsolute(e) ? e : this._makeAbs(e) - const httpUrl = _this4.constructor.getGitHTTPUrl(_this4.exploded); - const httpBaseUrl = _this4.constructor.getGitHTTPBaseUrl(_this4.exploded); - const sshUrl = _this4.constructor.getGitSSHUrl(_this4.exploded); + if (this.mark) + e = this._mark(e) - // If we can access the files over HTTP then we should as it's MUCH faster than git - // archive and tarball unarchiving. The HTTP API is only available for public repos - // though. - if (yield _this4.hasHTTPCapability(httpBaseUrl)) { - return _this4.resolveOverHTTP(httpUrl); - } + if (this.absolute) + e = abs - // If the url is accessible over git archive then we should immediately delegate to - // the git resolver. - // - // NOTE: Here we use a different url than when we delegate to the git resolver later on. - // This is because `git archive` requires access over ssh and github only allows that - // if you have write permissions - const sshGitUrl = (_git || _load_git()).default.npmUrlToGitUrl(sshUrl); - if (yield (_git || _load_git()).default.hasArchiveCapability(sshGitUrl)) { - const archiveClient = new (_git || _load_git()).default(_this4.config, sshGitUrl, _this4.hash); - const commit = yield archiveClient.init(); - return _this4.fork((_gitResolver || _load_gitResolver()).default, true, `${sshUrl}#${commit}`); - } + if (this.matches[index][e]) + return - // fallback to the plain git resolver - return _this4.fork((_gitResolver || _load_gitResolver()).default, true, sshUrl); - })(); + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return } -} -exports.default = HostedGitResolver; -/***/ }), -/* 53 */ -/***/ (function(module, exports, __webpack_require__) { + this.matches[index][e] = true -"use strict"; + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + this.emit('match', e) +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hostedGit = exports.exotics = exports.registries = undefined; -exports.hostedGitFragmentToGitUrl = hostedGitFragmentToGitUrl; +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return -var _npmResolver; + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) -function _load_npmResolver() { - return _npmResolver = _interopRequireDefault(__webpack_require__(126)); -} + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) -var _yarnResolver; + if (lstatcb) + fs.lstat(abs, lstatcb) -function _load_yarnResolver() { - return _yarnResolver = _interopRequireDefault(__webpack_require__(205)); -} + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() -var _gitResolver; + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym -function _load_gitResolver() { - return _gitResolver = _interopRequireDefault(__webpack_require__(61)); + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } } -var _tarballResolver; +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return -function _load_tarballResolver() { - return _tarballResolver = _interopRequireDefault(__webpack_require__(381)); -} + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return -var _githubResolver; + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) -function _load_githubResolver() { - return _githubResolver = _interopRequireDefault(__webpack_require__(377)); -} + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() -var _fileResolver; + if (Array.isArray(c)) + return cb(null, c) + } -function _load_fileResolver() { - return _fileResolver = _interopRequireDefault(__webpack_require__(204)); + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) } -var _linkResolver; - -function _load_linkResolver() { - return _linkResolver = _interopRequireDefault(__webpack_require__(379)); +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } } -var _gitlabResolver; +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return -function _load_gitlabResolver() { - return _gitlabResolver = _interopRequireDefault(__webpack_require__(378)); + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) } -var _gistResolver; +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return -function _load_gistResolver() { - return _gistResolver = _interopRequireDefault(__webpack_require__(125)); -} + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break -var _bitbucketResolver; + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break -function _load_bitbucketResolver() { - return _bitbucketResolver = _interopRequireDefault(__webpack_require__(376)); -} + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } -var _hostedGitResolver; + return cb() +} -function _load_hostedGitResolver() { - return _hostedGitResolver = __webpack_require__(52); +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) } -var _registryResolver; -function _load_registryResolver() { - return _registryResolver = _interopRequireDefault(__webpack_require__(380)); -} +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() -const registries = exports.registries = { - npm: (_npmResolver || _load_npmResolver()).default, - yarn: (_yarnResolver || _load_yarnResolver()).default -}; + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) -// + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) -const exotics = exports.exotics = { - git: (_gitResolver || _load_gitResolver()).default, - tarball: (_tarballResolver || _load_tarballResolver()).default, - github: (_githubResolver || _load_githubResolver()).default, - file: (_fileResolver || _load_fileResolver()).default, - link: (_linkResolver || _load_linkResolver()).default, - gitlab: (_gitlabResolver || _load_gitlabResolver()).default, - gist: (_gistResolver || _load_gistResolver()).default, - bitbucket: (_bitbucketResolver || _load_bitbucketResolver()).default -}; + var isSym = this.symlinks[abs] + var len = entries.length -// + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() -const hostedGit = exports.hostedGit = { - github: (_githubResolver || _load_githubResolver()).default, - gitlab: (_gitlabResolver || _load_gitlabResolver()).default, - bitbucket: (_bitbucketResolver || _load_bitbucketResolver()).default -}; + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue -function hostedGitFragmentToGitUrl(fragment, reporter) { - for (const key in hostedGit) { - const Resolver = hostedGit[key]; - if (Resolver.isVersion(fragment)) { - return Resolver.getGitHTTPUrl((0, (_hostedGitResolver || _load_hostedGitResolver()).explodeHostedGitFragment)(fragment, reporter)); - } + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) } - return fragment; + cb() } -// +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { -for (const key in registries) { - var _class, _temp; + //console.error('ps2', prefix, exists) - const RegistryResolver = registries[key]; - - exotics[key] = (_temp = _class = class extends (_registryResolver || _load_registryResolver()).default {}, _class.protocol = key, _class.factory = RegistryResolver, _temp); -} - -/***/ }), -/* 54 */ -/***/ (function(module, exports, __webpack_require__) { - -var dP = __webpack_require__(70) - , createDesc = __webpack_require__(139); -module.exports = __webpack_require__(69) ? function(object, key, value){ - return dP.f(object, key, createDesc(1, value)); -} : function(object, key, value){ - object[key] = value; - return object; -}; + if (!this.matches[index]) + this.matches[index] = Object.create(null) -/***/ }), -/* 55 */ -/***/ (function(module, exports) { + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() -module.exports = {}; + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } -/***/ }), -/* 56 */ -/***/ (function(module, exports, __webpack_require__) { + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') -"use strict"; -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + if (f.length > this.maxLength) + return cb() -/*<replacement>*/ + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/*</replacement>*/ + if (Array.isArray(c)) + c = 'DIR' -module.exports = Duplex; + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) -/*<replacement>*/ -var processNextTick = __webpack_require__(162); -/*</replacement>*/ + if (needDir && c === 'FILE') + return cb() -/*<replacement>*/ -var util = __webpack_require__(71); -util.inherits = __webpack_require__(37); -/*</replacement>*/ + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } -var Readable = __webpack_require__(252); -var Writable = __webpack_require__(254); + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } -util.inherits(Duplex, Readable); + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) -var keys = objectKeys(Writable.prototype); -for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } } -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat - this.once('end', onend); -} + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c - // no more data can be written. - // But allow more writes to happen in this tick. - processNextTick(onEndNT, this); -} + if (needDir && c === 'FILE') + return cb() -function onEndNT(self) { - self.end(); + return cb(null, c, stat) } -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} /***/ }), -/* 57 */ +/* 72 */ /***/ (function(module, exports, __webpack_require__) { -var buffer = __webpack_require__(76) +var wrappy = __webpack_require__(89) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - Object.keys(buffer).forEach(function (prop) { - exports[prop] = buffer[prop] +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true }) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} -// Copy static methods from Buffer -Object.keys(Buffer).forEach(function (prop) { - SafeBuffer[prop] = Buffer[prop] + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) }) -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) } - return Buffer(arg, encodingOrOffset, length) + f.called = false + return f } -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) } - return buf + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) + +/***/ }), +/* 73 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +function posix(path) { + return path.charAt(0) === '/'; } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); } +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; + /***/ }), -/* 58 */ +/* 74 */ /***/ (function(module, exports, __webpack_require__) { -var v1 = __webpack_require__(632); -var v4 = __webpack_require__(633); - -var uuid = v4; -uuid.v1 = v1; -uuid.v4 = v4; - -module.exports = uuid; +var Stream = __webpack_require__(26); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __webpack_require__(305); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __webpack_require__(307); + exports.Duplex = __webpack_require__(86); + exports.Transform = __webpack_require__(306); + exports.PassThrough = __webpack_require__(595); +} /***/ }), -/* 59 */ +/* 75 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Copyright 2015 Joyent, Inc. +module.exports = { + read: read.bind(undefined, false, undefined), + readType: read.bind(undefined, false), + write: write, + /* semi-private api, used by sshpk-agent */ + readPartial: read.bind(undefined, true), -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = undefined; + /* shared with ssh format */ + readInternal: read, + keyTypeToAlg: keyTypeToAlg, + algToKeyType: algToKeyType +}; -var _asyncToGenerator2; +var assert = __webpack_require__(11); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var SSHBuffer = __webpack_require__(144); -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function algToKeyType(alg) { + assert.string(alg); + if (alg === 'ssh-dss') + return ('dsa'); + else if (alg === 'ssh-rsa') + return ('rsa'); + else if (alg === 'ssh-ed25519') + return ('ed25519'); + else if (alg === 'ssh-curve25519') + return ('curve25519'); + else if (alg.match(/^ecdsa-sha2-/)) + return ('ecdsa'); + else + throw (new Error('Unknown algorithm ' + alg)); } -let updateCwd = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { - yield config.init({ - cwd: config.globalFolder, - binLinks: true, - globalFolder: config.globalFolder, - cacheFolder: config._cacheRootFolder, - linkFolder: config.linkFolder - }); - }); - - return function updateCwd(_x) { - return _ref.apply(this, arguments); - }; -})(); +function keyTypeToAlg(key) { + assert.object(key); + if (key.type === 'dsa') + return ('ssh-dss'); + else if (key.type === 'rsa') + return ('ssh-rsa'); + else if (key.type === 'ed25519') + return ('ssh-ed25519'); + else if (key.type === 'curve25519') + return ('ssh-curve25519'); + else if (key.type === 'ecdsa') + return ('ecdsa-sha2-' + key.part.curve.data.toString()); + else + throw (new Error('Unknown key type ' + key.type)); +} -let getBins = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { - // build up list of registry folders to search for binaries - const dirs = []; - for (const registryName of Object.keys((_index || _load_index()).registries)) { - const registry = config.registries[registryName]; - dirs.push(registry.loc); - } +function read(partial, type, buf, options) { + if (typeof (buf) === 'string') + buf = new Buffer(buf); + assert.buffer(buf, 'buf'); - // build up list of binary files - const paths = new Set(); - for (const dir of dirs) { - const binDir = path.join(dir, '.bin'); - if (!(yield (_fs || _load_fs()).exists(binDir))) { - continue; - } + var key = {}; - for (const name of yield (_fs || _load_fs()).readdir(binDir)) { - paths.add(path.join(binDir, name)); - } - } - return paths; - }); + var parts = key.parts = []; + var sshbuf = new SSHBuffer({buffer: buf}); - return function getBins(_x2) { - return _ref2.apply(this, arguments); - }; -})(); + var alg = sshbuf.readString(); + assert.ok(!sshbuf.atEnd(), 'key must have at least one part'); -let initUpdateBins = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags) { - const beforeBins = yield getBins(config); - const binFolder = getBinFolder(config, flags); + key.type = algToKeyType(alg); - function throwPermError(err, dest) { - if (err.code === 'EACCES') { - throw new (_errors || _load_errors()).MessageError(reporter.lang('noFilePermission', dest)); - } else { - throw err; - } - } + var partCount = algs.info[key.type].parts.length; + if (type && type === 'private') + partCount = algs.privInfo[key.type].parts.length; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const afterBins = yield getBins(config); + while (!sshbuf.atEnd() && parts.length < partCount) + parts.push(sshbuf.readPart()); + while (!partial && !sshbuf.atEnd()) + parts.push(sshbuf.readPart()); - // remove old bins - for (const src of beforeBins) { - if (afterBins.has(src)) { - // not old - continue; - } + assert.ok(parts.length >= 1, + 'key must have at least one part'); + assert.ok(partial || sshbuf.atEnd(), + 'leftover bytes at end of key'); - // remove old bin - const dest = path.join(binFolder, path.basename(src)); - try { - yield (_fs || _load_fs()).unlink(dest); - } catch (err) { - throwPermError(err, dest); - } - } + var Constructor = Key; + var algInfo = algs.info[key.type]; + if (type === 'private' || algInfo.parts.length !== parts.length) { + algInfo = algs.privInfo[key.type]; + Constructor = PrivateKey; + } + assert.strictEqual(algInfo.parts.length, parts.length); - // add new bins - for (const src of afterBins) { - if (beforeBins.has(src)) { - // already inserted - continue; - } + if (key.type === 'ecdsa') { + var res = /^ecdsa-sha2-(.+)$/.exec(alg); + assert.ok(res !== null); + assert.strictEqual(res[1], parts[0].data.toString()); + } - // insert new bin - const dest = path.join(binFolder, path.basename(src)); - try { - yield (_fs || _load_fs()).unlink(dest); - yield (0, (_packageLinker || _load_packageLinker()).linkBin)(src, dest); - if (process.platform === 'win32' && dest.indexOf('.cmd') !== -1) { - yield (_fs || _load_fs()).rename(dest + '.cmd', dest); - } - } catch (err) { - throwPermError(err, dest); - } - } - }); - }); + var normalized = true; + for (var i = 0; i < algInfo.parts.length; ++i) { + parts[i].name = algInfo.parts[i]; + if (parts[i].name !== 'curve' && + algInfo.normalize !== false) { + var p = parts[i]; + var nd = utils.mpNormalize(p.data); + if (nd !== p.data) { + p.data = nd; + normalized = false; + } + } + } - return function initUpdateBins(_x3, _x4, _x5) { - return _ref3.apply(this, arguments); - }; -})(); + if (normalized) + key._rfc4253Cache = sshbuf.toBuffer(); -let list = (() => { - var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - yield updateCwd(config); + if (partial && typeof (partial) === 'object') { + partial.remainder = sshbuf.remainder(); + partial.consumed = sshbuf._offset; + } - // install so we get hard file paths - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); - const install = new (_install || _load_install()).Install({ skipIntegrityCheck: true }, config, new (_baseReporter || _load_baseReporter()).default(), lockfile); - const patterns = yield install.init(); + return (new Constructor(key)); +} - // dump global modules - for (const pattern of patterns) { - const manifest = install.resolver.getStrictResolvedPattern(pattern); - ls(manifest, reporter, false); - } - }); +function write(key, options) { + assert.object(key); - return function list(_x6, _x7, _x8, _x9) { - return _ref5.apply(this, arguments); - }; -})(); + var alg = keyTypeToAlg(key); + var i; -exports.hasWrapper = hasWrapper; -exports.getBinFolder = getBinFolder; -exports.setFlags = setFlags; + var algInfo = algs.info[key.type]; + if (PrivateKey.isPrivateKey(key)) + algInfo = algs.privInfo[key.type]; + var parts = algInfo.parts; -var _errors; + var buf = new SSHBuffer({}); -function _load_errors() { - return _errors = __webpack_require__(3); -} + buf.writeString(alg); -var _index; + for (i = 0; i < parts.length; ++i) { + var data = key.part[parts[i]].data; + if (algInfo.normalize !== false) + data = utils.mpNormalize(data); + buf.writeBuffer(data); + } -function _load_index() { - return _index = __webpack_require__(24); + return (buf.toBuffer()); } -var _baseReporter; - -function _load_baseReporter() { - return _baseReporter = _interopRequireDefault(__webpack_require__(51)); -} -var _buildSubCommands2; +/***/ }), +/* 76 */ +/***/ (function(module, exports, __webpack_require__) { -function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); -} +"use strict"; -var _wrapper; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} +Object.defineProperty(exports, "__esModule", { + value: true +}); -var _install; +exports.default = function (str) { + let fileLoc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'lockfile'; -function _load_install() { - return _install = __webpack_require__(23); -} + str = stripBOM(str); + return hasMergeConflicts(str) ? parseWithConflict(str, fileLoc) : { type: 'success', object: parse(str, fileLoc) }; +}; -var _add; +var _constants; -function _load_add() { - return _add = __webpack_require__(78); +function _load_constants() { + return _constants = __webpack_require__(6); } -var _remove; +var _errors; -function _load_remove() { - return _remove = __webpack_require__(193); +function _load_errors() { + return _errors = __webpack_require__(3); } -var _upgrade; +var _map; -function _load_upgrade() { - return _upgrade = __webpack_require__(196); +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); } -var _upgradeInteractive; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _load_upgradeInteractive() { - return _upgradeInteractive = __webpack_require__(195); -} +const invariant = __webpack_require__(7); +/* eslint quotes: 0 */ -var _packageLinker; +const stripBOM = __webpack_require__(119); -function _load_packageLinker() { - return _packageLinker = __webpack_require__(122); -} +const VERSION_REGEX = /^yarn lockfile v(\d+)$/; -var _fs; +const TOKEN_TYPES = { + boolean: 'BOOLEAN', + string: 'STRING', + identifier: 'IDENTIFIER', + eof: 'EOF', + colon: 'COLON', + newline: 'NEWLINE', + comment: 'COMMENT', + indent: 'INDENT', + invalid: 'INVALID', + number: 'NUMBER', + comma: 'COMMA' +}; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); +const VALID_PROP_VALUE_TOKENS = [TOKEN_TYPES.boolean, TOKEN_TYPES.string, TOKEN_TYPES.number]; + +function isValidPropValueToken(token) { + return VALID_PROP_VALUE_TOKENS.indexOf(token.type) >= 0; } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function* tokenise(input) { + let lastNewline = false; + let line = 1; + let col = 0; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + function buildToken(type, value) { + return { line, col, type, value }; + } -class GlobalAdd extends (_add || _load_add()).Add { - maybeOutputSaveTree() { - for (const pattern of this.addedPatterns) { - const manifest = this.resolver.getStrictResolvedPattern(pattern); - ls(manifest, this.reporter, true); + while (input.length) { + let chop = 0; + + if (input[0] === '\n') { + chop++; + line++; + col = 0; + yield buildToken(TOKEN_TYPES.newline); + } else if (input[0] === '#') { + chop++; + + let val = ''; + while (input[chop] !== '\n') { + val += input[chop]; + chop++; + } + yield buildToken(TOKEN_TYPES.comment, val); + } else if (input[0] === ' ') { + if (lastNewline) { + let indent = ''; + for (let i = 0; input[i] === ' '; i++) { + indent += input[i]; + } + + if (indent.length % 2) { + throw new TypeError('Invalid number of spaces'); + } else { + chop = indent.length; + yield buildToken(TOKEN_TYPES.indent, indent.length / 2); + } + } else { + chop++; + } + } else if (input[0] === '"') { + let val = ''; + + for (let i = 0;; i++) { + const currentChar = input[i]; + val += currentChar; + + if (i > 0 && currentChar === '"') { + const isEscaped = input[i - 1] === '\\' && input[i - 2] !== '\\'; + if (!isEscaped) { + break; + } + } + } + + chop = val.length; + + try { + yield buildToken(TOKEN_TYPES.string, JSON.parse(val)); + } catch (err) { + if (err instanceof SyntaxError) { + yield buildToken(TOKEN_TYPES.invalid); + } else { + throw err; + } + } + } else if (/^[0-9]/.test(input)) { + let val = ''; + for (let i = 0; /^[0-9]$/.test(input[i]); i++) { + val += input[i]; + } + chop = val.length; + + yield buildToken(TOKEN_TYPES.number, +val); + } else if (/^true/.test(input)) { + yield buildToken(TOKEN_TYPES.boolean, true); + chop = 4; + } else if (/^false/.test(input)) { + yield buildToken(TOKEN_TYPES.boolean, false); + chop = 5; + } else if (input[0] === ':') { + yield buildToken(TOKEN_TYPES.colon); + chop++; + } else if (input[0] === ',') { + yield buildToken(TOKEN_TYPES.comma); + chop++; + } else if (/^[a-zA-Z\/-]/g.test(input)) { + let name = ''; + for (let i = 0; i < input.length; i++) { + const char = input[i]; + if (char === ':' || char === ' ' || char === '\n' || char === ',') { + break; + } else { + name += char; + } + } + chop = name.length; + + yield buildToken(TOKEN_TYPES.string, name); + } else { + yield buildToken(TOKEN_TYPES.invalid); } - return Promise.resolve(); - } - _logSuccessSaveLockfile() { - // noop + if (!chop) { + // will trigger infinite recursion + yield buildToken(TOKEN_TYPES.invalid); + } + + col += chop; + lastNewline = input[0] === '\n'; + input = input.slice(chop); } + + yield buildToken(TOKEN_TYPES.eof); } -const path = __webpack_require__(1); +class Parser { + constructor(input) { + let fileLoc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'lockfile'; -function hasWrapper(flags, args) { - return args[0] !== 'bin'; -} + this.comments = []; + this.tokens = tokenise(input); + this.fileLoc = fileLoc; + } -function getGlobalPrefix(config, flags) { - if (flags.prefix) { - return flags.prefix; - } else if (config.getOption('prefix')) { - return String(config.getOption('prefix')); - } else if (process.env.PREFIX) { - return process.env.PREFIX; - } else if (process.platform === 'win32') { - if (process.env.LOCALAPPDATA) { - return path.join(process.env.LOCALAPPDATA, 'Yarn', 'bin'); + onComment(token) { + const value = token.value; + invariant(typeof value === 'string', 'expected token value to be a string'); + + const comment = value.trim(); + + const versionMatch = comment.match(VERSION_REGEX); + if (versionMatch) { + const version = +versionMatch[1]; + if (version > (_constants || _load_constants()).LOCKFILE_VERSION) { + throw new (_errors || _load_errors()).MessageError(`Can't install from a lockfile of version ${version} as you're on an old yarn version that only supports ` + `versions up to ${(_constants || _load_constants()).LOCKFILE_VERSION}. Run \`$ yarn self-update\` to upgrade to the latest version.`); + } } - // c:\node\node.exe --> prefix=c:\node\ - return path.dirname(process.execPath); - } else { - // /usr/local/bin/node --> prefix=/usr/local - let prefix = path.dirname(path.dirname(process.execPath)); - // destdir only is respected on Unix - if (process.env.DESTDIR) { - prefix = path.join(process.env.DESTDIR, prefix); + this.comments.push(comment); + } + + next() { + const item = this.tokens.next(); + invariant(item, 'expected a token'); + + const done = item.done, + value = item.value; + + if (done || !value) { + throw new Error('No more tokens'); + } else if (value.type === TOKEN_TYPES.comment) { + this.onComment(value); + return this.next(); + } else { + return this.token = value; } + } - return prefix; + unexpected() { + let msg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Unexpected token'; + + throw new SyntaxError(`${msg} ${this.token.line}:${this.token.col} in ${this.fileLoc}`); } -} -function getBinFolder(config, flags) { - const prefix = getGlobalPrefix(config, flags); - if (process.platform === 'win32') { - return prefix; - } else { - return path.resolve(prefix, 'bin'); + expect(tokType) { + if (this.token.type === tokType) { + this.next(); + } else { + this.unexpected(); + } } -} -function ls(manifest, reporter, saved) { - const bins = manifest.bin ? Object.keys(manifest.bin) : []; - const human = `${manifest.name}@${manifest.version}`; - if (bins.length) { - if (saved) { - reporter.success(reporter.lang('packageInstalledWithBinaries', human)); + eat(tokType) { + if (this.token.type === tokType) { + this.next(); + return true; } else { - reporter.info(reporter.lang('packageHasBinaries', human)); + return false; } - reporter.list(`bins-${manifest.name}`, bins); - } else if (saved) { - reporter.warn(reporter.lang('packageHasNoBinaries', human)); } -} -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('global', { - add(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield updateCwd(config); + parse() { + let indent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - const updateBins = yield initUpdateBins(config, reporter, flags); - if (args.indexOf('yarn') !== -1) { - reporter.warn(reporter.lang('packageContainsYarnAsGlobal')); - } + const obj = (0, (_map || _load_map()).default)(); - // install module - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); - const install = new GlobalAdd(args, flags, config, reporter, lockfile); - yield install.init(); + while (true) { + const propToken = this.token; - // link binaries - yield updateBins(); - })(); - }, + if (propToken.type === TOKEN_TYPES.newline) { + const nextToken = this.next(); + if (!indent) { + // if we have 0 indentation then the next token doesn't matter + continue; + } - bin(config, reporter, flags, args) { - reporter.log(getBinFolder(config, flags)); - }, + if (nextToken.type !== TOKEN_TYPES.indent) { + // if we have no indentation after a newline then we've gone down a level + break; + } - ls(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - reporter.warn(`\`yarn global ls\` is deprecated. Please use \`yarn global list\`.`); - yield list(config, reporter, flags, args); - })(); - }, + if (nextToken.value === indent) { + // all is good, the indent is on our level + this.next(); + } else { + // the indentation is less than our level + break; + } + } else if (propToken.type === TOKEN_TYPES.indent) { + if (propToken.value === indent) { + this.next(); + } else { + break; + } + } else if (propToken.type === TOKEN_TYPES.eof) { + break; + } else if (propToken.type === TOKEN_TYPES.string) { + // property key + const key = propToken.value; + invariant(key, 'Expected a key'); - list(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield list(config, reporter, flags, args); - })(); - }, + const keys = [key]; + this.next(); - remove(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield updateCwd(config); + // support multiple keys + while (this.token.type === TOKEN_TYPES.comma) { + this.next(); // skip comma - const updateBins = yield initUpdateBins(config, reporter, flags); + const keyToken = this.token; + if (keyToken.type !== TOKEN_TYPES.string) { + this.unexpected('Expected string'); + } - // remove module - yield (0, (_remove || _load_remove()).run)(config, reporter, flags, args); + const key = keyToken.value; + invariant(key, 'Expected a key'); + keys.push(key); + this.next(); + } - // remove binaries - yield updateBins(); - })(); - }, + const valToken = this.token; - upgrade(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield updateCwd(config); + if (valToken.type === TOKEN_TYPES.colon) { + // object + this.next(); - const updateBins = yield initUpdateBins(config, reporter, flags); + // parse object + const val = this.parse(indent + 1); - // upgrade module - yield (0, (_upgrade || _load_upgrade()).run)(config, reporter, flags, args); + for (const key of keys) { + obj[key] = val; + } - // update binaries - yield updateBins(); - })(); - }, + if (indent && this.token.type !== TOKEN_TYPES.indent) { + break; + } + } else if (isValidPropValueToken(valToken)) { + // plain value + for (const key of keys) { + obj[key] = valToken.value; + } - upgradeInteractive(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield updateCwd(config); + this.next(); + } else { + this.unexpected('Invalid value type'); + } + } else { + this.unexpected('Unknown token'); + } + } - const updateBins = yield initUpdateBins(config, reporter, flags); + return obj; + } +} - // upgrade module - yield (0, (_upgradeInteractive || _load_upgradeInteractive()).run)(config, reporter, flags, args); +const MERGE_CONFLICT_ANCESTOR = '|||||||'; +const MERGE_CONFLICT_END = '>>>>>>>'; +const MERGE_CONFLICT_SEP = '======='; +const MERGE_CONFLICT_START = '<<<<<<<'; - // update binaries - yield updateBins(); - })(); +/** + * Extract the two versions of the lockfile from a merge conflict. + */ +function extractConflictVariants(str) { + const variants = [[], []]; + const lines = str.split(/\n/g); + let skip = false; + + while (lines.length) { + const line = lines.shift(); + if (line.startsWith(MERGE_CONFLICT_START)) { + // get the first variant + while (lines.length) { + const conflictLine = lines.shift(); + if (conflictLine === MERGE_CONFLICT_SEP) { + skip = false; + break; + } else if (skip || conflictLine.startsWith(MERGE_CONFLICT_ANCESTOR)) { + skip = true; + continue; + } else { + variants[0].push(conflictLine); + } + } + + // get the second variant + while (lines.length) { + const conflictLine = lines.shift(); + if (conflictLine.startsWith(MERGE_CONFLICT_END)) { + break; + } else { + variants[1].push(conflictLine); + } + } + } else { + variants[0].push(line); + variants[1].push(line); + } } -}); -const run = _buildSubCommands.run, - _setFlags = _buildSubCommands.setFlags; -exports.run = run; -function setFlags(commander) { - _setFlags(commander); - commander.option('--prefix <prefix>', 'bin prefix to use to install binaries'); + return [variants[0].join('\n'), variants[1].join('\n')]; +} + +/** + * Check if a lockfile has merge conflicts. + */ +function hasMergeConflicts(str) { + return str.includes(MERGE_CONFLICT_START) && str.includes(MERGE_CONFLICT_SEP) && str.includes(MERGE_CONFLICT_END); +} + +/** + * Parse the lockfile. + */ +function parse(str, fileLoc) { + const parser = new Parser(str, fileLoc); + parser.next(); + return parser.parse(); +} + +/** + * Parse and merge the two variants in a conflicted lockfile. + */ +function parseWithConflict(str, fileLoc) { + const variants = extractConflictVariants(str); + try { + return { type: 'merge', object: Object.assign({}, parse(variants[0], fileLoc), parse(variants[1], fileLoc)) }; + } catch (err) { + if (err instanceof SyntaxError) { + return { type: 'conflict', object: {} }; + } else { + throw err; + } + } } /***/ }), -/* 60 */ +/* 77 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -33668,166 +35095,301 @@ function setFlags(commander) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = exports.getToken = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -let getCredentials = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) { - var _config$registries$ya = config.registries.yarn.config; - let username = _config$registries$ya.username, - email = _config$registries$ya.email; - +exports.stringifyLangArgs = stringifyLangArgs; - if (username) { - reporter.info(`${reporter.lang('npmUsername')}: ${username}`); - } else { - username = yield reporter.question(reporter.lang('npmUsername')); - if (!username) { - return null; - } - } +var _format; - if (email) { - reporter.info(`${reporter.lang('npmEmail')}: ${email}`); - } else { - email = yield reporter.question(reporter.lang('npmEmail')); - if (!email) { - return null; - } - } +function _load_format() { + return _format = __webpack_require__(265); +} - yield config.registries.yarn.saveHomeConfig({ username, email }); +var _index; - return { username, email }; - }); +function _load_index() { + return _index = _interopRequireWildcard(__webpack_require__(266)); +} - return function getCredentials(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); +var _isCi; -let getToken = exports.getToken = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) { - let name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; +function _load_isCi() { + return _isCi = _interopRequireDefault(__webpack_require__(213)); +} - const auth = config.registries.npm.getAuth(name); - if (auth) { - config.registries.npm.setToken(auth); - return function revoke() { - reporter.info(reporter.lang('notRevokingConfigToken')); - return Promise.resolve(); - }; - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - const env = process.env.YARN_AUTH_TOKEN || process.env.NPM_AUTH_TOKEN; - if (env) { - config.registries.npm.setToken(`Bearer ${env}`); - return function revoke() { - reporter.info(reporter.lang('notRevokingEnvToken')); - return Promise.resolve(); - }; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // - const creds = yield getCredentials(config, reporter); - if (!creds) { - reporter.warn(reporter.lang('loginAsPublic')); - return function revoke() { - reporter.info(reporter.lang('noTokenToRevoke')); - return Promise.resolve(); - }; - } +/* eslint no-unused-vars: 0 */ - const username = creds.username, - email = creds.email; +const util = __webpack_require__(2); +const EventEmitter = __webpack_require__(46).EventEmitter; - const password = yield reporter.question(reporter.lang('npmPassword'), { - password: true, - required: true +function stringifyLangArgs(args) { + return args.map(function (val) { + if (val != null && val.inspect) { + return val.inspect(); + } else { + try { + const str = JSON.stringify(val) || val + ''; + // should match all "u001b" that follow an odd number of backslashes and convert them to ESC + // we do this because the JSON.stringify process has escaped these characters + return str.replace(/((?:^|[^\\])(?:\\{2})*)\\u001[bB]/g, '$1\u001b'); + } catch (e) { + return util.inspect(val); + } + } + }); +} + +class BaseReporter { + constructor() { + let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + const lang = 'en'; + this.language = lang; + + this.stdout = opts.stdout || process.stdout; + this.stderr = opts.stderr || process.stderr; + this.stdin = opts.stdin || this._getStandardInput(); + this.emoji = !!opts.emoji; + this.noProgress = !!opts.noProgress || (_isCi || _load_isCi()).default; + this.isVerbose = !!opts.verbose; + + // $FlowFixMe: this is valid! + this.isTTY = this.stdout.isTTY; + + this.peakMemory = 0; + this.startTime = Date.now(); + this.format = (_format || _load_format()).defaultFormatter; + } + + lang(key) { + const msg = (_index || _load_index())[this.language][key] || (_index || _load_index()).en[key]; + if (!msg) { + throw new ReferenceError(`Unknown language key ${key}`); + } + + // stringify args + + for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; + } + + const stringifiedArgs = stringifyLangArgs(args); + + // replace $0 placeholders with args + return msg.replace(/\$(\d+)/g, (str, i) => { + return stringifiedArgs[i]; }); + } - // - const userobj = { - _id: `org.couchdb.user:${username}`, - name: username, - password, - email, - type: 'user', - roles: [], - date: new Date().toISOString() + /** + * `stringifyLangArgs` run `JSON.stringify` on strings too causing + * them to appear quoted. This marks them as "raw" and prevents + * the quiating and escaping + */ + rawText(str) { + return { + inspect() { + return str; + } }; + } - // - const res = yield config.registries.npm.request(`-/user/org.couchdb.user:${encodeURIComponent(username)}`, { - method: 'PUT', - body: userobj, - auth: { username, password, email } - }); + verbose(msg) { + if (this.isVerbose) { + this._verbose(msg); + } + } - if (res && res.ok) { - reporter.success(reporter.lang('loggedIn')); + verboseInspect(val) { + if (this.isVerbose) { + this._verboseInspect(val); + } + } - const token = res.token; - config.registries.npm.setToken(`Bearer ${token}`); + _verbose(msg) {} + _verboseInspect(val) {} - return (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - reporter.success(reporter.lang('revokedToken')); - yield config.registries.npm.request(`-/user/token/${token}`, { - method: 'DELETE' - }); - }); + _getStandardInput() { + let standardInput; - function revoke() { - return _ref3.apply(this, arguments); - } + // Accessing stdin in a win32 headless process (e.g., Visual Studio) may throw an exception. + try { + standardInput = process.stdin; + } catch (e) { + console.warn(e.message); + delete process.stdin; + // $FlowFixMe: this is valid! + process.stdin = new EventEmitter(); + standardInput = process.stdin; + } - return revoke; - })(); - } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('incorrectCredentials')); + return standardInput; + } + + initPeakMemoryCounter() { + this.checkPeakMemory(); + this.peakMemoryInterval = setInterval(() => { + this.checkPeakMemory(); + }, 1000); + // $FlowFixMe: Node's setInterval returns a Timeout, not a Number + this.peakMemoryInterval.unref(); + } + + checkPeakMemory() { + var _process$memoryUsage = process.memoryUsage(); + + const heapTotal = _process$memoryUsage.heapTotal; + + if (heapTotal > this.peakMemory) { + this.peakMemory = heapTotal; } - }); + } - return function getToken(_x3, _x4) { - return _ref2.apply(this, arguments); - }; -})(); + close() { + if (this.peakMemoryInterval) { + clearInterval(this.peakMemoryInterval); + this.peakMemoryInterval = null; + } + } -let run = exports.run = (() => { - var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - yield getCredentials(config, reporter); - }); + getTotalTime() { + return Date.now() - this.startTime; + } - return function run(_x6, _x7, _x8, _x9) { - return _ref4.apply(this, arguments); - }; -})(); + // TODO + list(key, items, hints) {} -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; + // Outputs basic tree structure to console + tree(key, obj) {} -var _errors; + // called whenever we begin a step in the CLI. + step(current, total, message, emoji) {} -function _load_errors() { - return _errors = __webpack_require__(3); -} + // a error message has been triggered. this however does not always meant an abrupt + // program end. + error(message) {} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // an info message has been triggered. this provides things like stats and diagnostics. + info(message) {} -function hasWrapper(commander, args) { - return true; -} + // a warning message has been triggered. + warn(message) {} -function setFlags(commander) {} + // a success message has been triggered. + success(message) {} + + // a simple log message + // TODO: rethink the {force} parameter. In the meantime, please don't use it (cf comments in #4143). + log(message) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$force = _ref.force; + + let force = _ref$force === undefined ? false : _ref$force; + } + + // a shell command has been executed + command(command) {} + + // inspect and pretty-print any value + inspect(value) {} + + // the screen shown at the very start of the CLI + header(command, pkg) {} + + // the screen shown at the very end of the CLI + footer(showPeakMemory) {} + + // + table(head, body) {} + + // render an activity spinner and return a function that will trigger an update + activity() { + return { + tick(name) {}, + end() {} + }; + } + + // + activitySet(total, workers) { + return { + spinners: Array(workers).fill({ + clear() {}, + setPrefix() {}, + tick() {}, + end() {} + }), + end() {} + }; + } + + // + question(question) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + return Promise.reject(new Error('Not implemented')); + } + + // + questionAffirm(question) { + var _this = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const condition = true; // trick eslint + + while (condition) { + let answer = yield _this.question(question); + answer = answer.toLowerCase(); + + if (answer === 'y' || answer === 'yes') { + return true; + } + if (answer === 'n' || answer === 'no') { + return false; + } + + _this.error('Invalid answer for question'); + } + + return false; + })(); + } + + // prompt the user to select an option from an array + select(header, question, options) { + return Promise.reject(new Error('Not implemented')); + } + + // render a progress bar and return a function which when called will trigger an update + progress(total) { + return function () {}; + } + + // utility function to disable progress bar + disableProgress() { + this.noProgress = true; + } + + // + prompt(message, choices) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + return Promise.reject(new Error('Not implemented')); + } +} +exports.default = BaseReporter; /***/ }), -/* 61 */ +/* 78 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -33840,130 +35402,206 @@ Object.defineProperty(exports, "__esModule", { var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -var _index; - -function _load_index() { - return _index = __webpack_require__(53); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _misc; - -function _load_misc() { - return _misc = _interopRequireWildcard(__webpack_require__(10)); -} +exports.explodeHostedGitFragment = explodeHostedGitFragment; -var _version; +var _errors; -function _load_version() { - return _version = _interopRequireWildcard(__webpack_require__(131)); +function _load_errors() { + return _errors = __webpack_require__(3); } -var _guessName; +var _index; -function _load_guessName() { - return _guessName = _interopRequireDefault(__webpack_require__(128)); +function _load_index() { + return _index = __webpack_require__(34); } -var _index2; +var _gitResolver; -function _load_index2() { - return _index2 = __webpack_require__(24); +function _load_gitResolver() { + return _gitResolver = _interopRequireDefault(__webpack_require__(96)); } var _exoticResolver; function _load_exoticResolver() { - return _exoticResolver = _interopRequireDefault(__webpack_require__(44)); + return _exoticResolver = _interopRequireDefault(__webpack_require__(61)); } var _git; function _load_git() { - return _git = _interopRequireDefault(__webpack_require__(127)); + return _git = _interopRequireDefault(__webpack_require__(165)); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +var _guessName; + +function _load_guessName() { + return _guessName = _interopRequireDefault(__webpack_require__(166)); +} function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const urlParse = __webpack_require__(11).parse; +function explodeHostedGitFragment(fragment, reporter) { + const preParts = fragment.split('@'); + if (preParts.length > 2) { + fragment = preParts[1] + '@' + preParts[2]; + } + + const parts = fragment.split(':'); -// we purposefully omit https and http as those are only valid if they end in the .git extension + if (parts.length == 3) { + // protocol + host + folder + parts[1] = parts[1].indexOf('//') >= 0 ? parts[1].substr(2) : parts[1]; + fragment = parts[1] + '/' + parts[2]; + } else if (parts.length == 2) { + if (parts[0].indexOf('@') == -1) { + // protocol + host + fragment = parts[1]; + } else { + // host + folder + fragment = parts[0] + '/' + parts[1]; + } + } else if (parts.length == 1) { + fragment = parts[0]; + } else { + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment)); + } + const userParts = fragment.split('/'); -const GIT_PROTOCOLS = ['git:', 'git+ssh:', 'git+https:', 'ssh:']; + if (userParts.length >= 2) { + if (userParts[0].indexOf('@') >= 0) { + userParts.shift(); + } -const GIT_HOSTS = ['github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org']; + const user = userParts.shift(); + const repoParts = userParts.join('/').split(/(?:[.]git)?#(.*)/); -class GitResolver extends (_exoticResolver || _load_exoticResolver()).default { + if (repoParts.length <= 3) { + return { + user, + repo: repoParts[0].replace('.git', ''), + hash: repoParts[1] || '' + }; + } + } + + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidHostedGitFragment', fragment)); +} + +class HostedGitResolver extends (_exoticResolver || _load_exoticResolver()).default { constructor(request, fragment) { super(request, fragment); - var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment); - - const url = _versionUtil$explodeH.url, - hash = _versionUtil$explodeH.hash; + const exploded = this.exploded = explodeHostedGitFragment(fragment, this.reporter); + const user = exploded.user, + repo = exploded.repo, + hash = exploded.hash; - this.url = url; + this.user = user; + this.repo = repo; this.hash = hash; } - static isVersion(pattern) { - const parts = urlParse(pattern); + static getTarballUrl(exploded, commit) { + exploded; + commit; + throw new Error('Not implemented'); + } - // this pattern hasn't been exploded yet, we'll hit this code path again later once - // we've been normalized #59 - if (!parts.protocol) { - return false; - } + static getGitHTTPUrl(exploded) { + exploded; + throw new Error('Not implemented'); + } - const pathname = parts.pathname; - if (pathname && pathname.endsWith('.git')) { - // ends in .git - return true; - } + static getGitHTTPBaseUrl(exploded) { + exploded; + throw new Error('Not implemented'); + } - if (GIT_PROTOCOLS.indexOf(parts.protocol) >= 0) { - return true; - } + static getGitSSHUrl(exploded) { + exploded; + throw new Error('Not implemented'); + } - if (parts.hostname && parts.path) { - const path = parts.path; - if (GIT_HOSTS.indexOf(parts.hostname) >= 0) { - // only if dependency is pointing to a git repo, - // e.g. facebook/flow and not file in a git repo facebook/flow/archive/v1.0.0.tar.gz - return path.split('/').filter(p => !!p).length === 2; + static getHTTPFileUrl(exploded, filename, commit) { + exploded; + filename; + commit; + throw new Error('Not implemented'); + } + + getRefOverHTTP(url) { + var _this = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const gitUrl = (_git || _load_git()).default.npmUrlToGitUrl(url); + const client = new (_git || _load_git()).default(_this.config, gitUrl, _this.hash); + + let out = yield _this.config.requestManager.request({ + url: `${url}/info/refs?service=git-upload-pack`, + queue: _this.resolver.fetchingQueue + }); + + if (out) { + // clean up output + let lines = out.trim().split('\n'); + + // remove first two lines which contains compatibility info etc + lines = lines.slice(2); + + // remove last line which contains the terminator "0000" + lines.pop(); + + // remove line lengths from start of each line + lines = lines.map(function (line) { + return line.slice(4); + }); + + out = lines.join('\n'); + } else { + throw new Error(_this.reporter.lang('hostedGitResolveError')); } - } - return false; + return client.setRefHosted(out); + })(); } - resolve(forked) { - var _this = this; + resolveOverHTTP(url) { + var _this2 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let tryRegistry = (() => { + const commit = yield _this2.getRefOverHTTP(url); + const config = _this2.config; + + + const tarballUrl = _this2.constructor.getTarballUrl(_this2.exploded, commit); + + const tryRegistry = (() => { var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (registry) { - const filename = (_index2 || _load_index2()).registries[registry].filename; + const filename = (_index || _load_index()).registries[registry].filename; - const file = yield client.getFile(filename); + const href = _this2.constructor.getHTTPFileUrl(_this2.exploded, filename, commit); + const file = yield config.requestManager.request({ + url: href, + queue: _this2.resolver.fetchingQueue + }); if (!file) { return null; } - const json = yield config.readJson(`${url}/${filename}`, function () { + const json = yield config.readJson(href, function () { return JSON.parse(file); }); json._uid = commit; json._remote = { - resolved: `${url}#${commit}`, - type: 'git', - reference: url, - hash: commit, + resolved: tarballUrl, + type: 'tarball', + reference: tarballUrl, registry }; return json; @@ -33974,80 +35612,93 @@ class GitResolver extends (_exoticResolver || _load_exoticResolver()).default { }; })(); - const url = _this.url; - - // shortcut for hosted git. we will fallback to a GitResolver if the hosted git - // optimisations fail which the `forked` flag indicates so we don't get into an - // infinite loop - - const parts = urlParse(url); - if (false) { - // check if this git url uses any of the hostnames defined in our hosted git resolvers - for (const name in (_index || _load_index()).hostedGit) { - const Resolver = (_index || _load_index()).hostedGit[name]; - if (Resolver.hostname !== parts.hostname) { - continue; - } + const file = yield tryRegistry(_this2.registry); + if (file) { + return file; + } - // we have a match! clean up the pathname of url artifacts - let pathname = parts.pathname; - pathname = (_misc || _load_misc()).removePrefix(pathname, '/'); // remove prefixed slash - pathname = (_misc || _load_misc()).removeSuffix(pathname, '.git'); // remove .git suffix if present + for (const registry in (_index || _load_index()).registries) { + if (registry === _this2.registry) { + continue; + } - const url = `${pathname}${_this.hash ? '#' + decodeURIComponent(_this.hash) : ''}`; - return _this.fork(Resolver, false, url); + const file = yield tryRegistry(registry); + if (file) { + return file; } } - // get from lockfile - const shrunk = _this.request.getLocked('git'); - if (shrunk) { - return shrunk; - } + return { + name: (0, (_guessName || _load_guessName()).default)(url), + version: '0.0.0', + _uid: commit, + _remote: { + resolved: tarballUrl, + type: 'tarball', + reference: tarballUrl, + registry: 'npm', + hash: undefined + } + }; + })(); + } - const config = _this.config; + hasHTTPCapability(url) { + var _this3 = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + return (yield _this3.config.requestManager.request({ + url, + method: 'HEAD', + queue: _this3.resolver.fetchingQueue, + followRedirect: false + })) !== false; + })(); + } - const gitUrl = (_git || _load_git()).default.npmUrlToGitUrl(url); - const client = new (_git || _load_git()).default(config, gitUrl, _this.hash); - const commit = yield client.init(); + resolve() { + var _this4 = this; - const file = yield tryRegistry(_this.registry); - if (file) { - return file; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // If we already have the tarball, just return it without having to make any HTTP requests. + const shrunk = _this4.request.getLocked('tarball'); + if (shrunk) { + return shrunk; } - for (const registry in (_index2 || _load_index2()).registries) { - if (registry === _this.registry) { - continue; - } + const httpUrl = _this4.constructor.getGitHTTPUrl(_this4.exploded); + const httpBaseUrl = _this4.constructor.getGitHTTPBaseUrl(_this4.exploded); + const sshUrl = _this4.constructor.getGitSSHUrl(_this4.exploded); - const file = yield tryRegistry(registry); - if (file) { - return file; - } + // If we can access the files over HTTP then we should as it's MUCH faster than git + // archive and tarball unarchiving. The HTTP API is only available for public repos + // though. + if (yield _this4.hasHTTPCapability(httpBaseUrl)) { + return _this4.resolveOverHTTP(httpUrl); } - return { - // This is just the default, it can be overridden with key of dependencies - name: (0, (_guessName || _load_guessName()).default)(url), - version: '0.0.0', - _uid: commit, - _remote: { - resolved: `${url}#${commit}`, - type: 'git', - reference: url, - hash: commit, - registry: 'npm' - } - }; + // If the url is accessible over git archive then we should immediately delegate to + // the git resolver. + // + // NOTE: Here we use a different url than when we delegate to the git resolver later on. + // This is because `git archive` requires access over ssh and github only allows that + // if you have write permissions + const sshGitUrl = (_git || _load_git()).default.npmUrlToGitUrl(sshUrl); + if (yield (_git || _load_git()).default.hasArchiveCapability(sshGitUrl)) { + const archiveClient = new (_git || _load_git()).default(_this4.config, sshGitUrl, _this4.hash); + const commit = yield archiveClient.init(); + return _this4.fork((_gitResolver || _load_gitResolver()).default, true, `${sshUrl}#${commit}`); + } + + // fallback to the plain git resolver + return _this4.fork((_gitResolver || _load_gitResolver()).default, true, sshUrl); })(); } } -exports.default = GitResolver; +exports.default = HostedGitResolver; /***/ }), -/* 62 */ +/* 79 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -34056,639 +35707,475 @@ exports.default = GitResolver; Object.defineProperty(exports, "__esModule", { value: true }); -exports.execCommand = exports.execFromManifest = exports.executeLifecycleScript = exports.makeEnv = undefined; -var _extends2; +var _map; -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(36)); +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); } -var _slicedToArray2; - -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _asyncToGenerator2; +const debug = __webpack_require__(203)('yarn'); -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +class BlockingQueue { + constructor(alias) { + let maxConcurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity; -let makeEnv = exports.makeEnv = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, cwd, config) { - const env = Object.assign({}, process.env); + this.concurrencyQueue = []; + this.maxConcurrency = maxConcurrency; + this.runningCount = 0; + this.warnedStuck = false; + this.alias = alias; + this.first = true; - // Merge in the `env` object specified in .yarnrc - const customEnv = config.getOption('env'); - if (customEnv && typeof customEnv === 'object') { - Object.assign(env, customEnv); - } + this.running = (0, (_map || _load_map()).default)(); + this.queue = (0, (_map || _load_map()).default)(); - env.npm_lifecycle_event = stage; - env.npm_node_execpath = env.NODE || process.execPath; - env.npm_execpath = env.npm_execpath || process.mainModule.filename; + this.stuckTick = this.stuckTick.bind(this); + } - // Set the env to production for npm compat if production mode. - // https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336 - if (config.production) { - env.NODE_ENV = 'production'; + stillActive() { + if (this.stuckTimer) { + clearTimeout(this.stuckTimer); } - // Note: npm_config_argv environment variable contains output of nopt - command-line - // parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684) - env.npm_config_argv = JSON.stringify({ - remain: [], - cooked: [config.commandName], - original: [config.commandName] - }); - - // add npm_package_* - const manifest = yield config.maybeReadManifest(cwd); - if (manifest) { - const queue = [['', manifest]]; - while (queue.length) { - var _queue$pop = queue.pop(), - _queue$pop2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_queue$pop, 2); - - const key = _queue$pop2[0], - val = _queue$pop2[1]; - - if (key[0] === '_') { - continue; - } - - if (typeof val === 'object') { - for (const subKey in val) { - const completeKey = [key, subKey].filter(function (part) { - return !!part; - }).join('_'); - queue.push([completeKey, val[subKey]]); - } - } else if (IGNORE_MANIFEST_KEYS.indexOf(key) < 0) { - let cleanVal = String(val); - if (cleanVal.indexOf('\n') >= 0) { - cleanVal = JSON.stringify(cleanVal); - } - - //replacing invalid chars with underscore - const cleanKey = key.replace(/[^a-zA-Z0-9_]/g, '_'); + this.stuckTimer = setTimeout(this.stuckTick, 5000); + } - env[`npm_package_${cleanKey}`] = cleanVal; - } - } + stuckTick() { + if (this.runningCount === 1) { + this.warnedStuck = true; + debug(`The ${JSON.stringify(this.alias)} blocking queue may be stuck. 5 seconds ` + `without any activity with 1 worker: ${Object.keys(this.running)[0]}`); } + } - // add npm_config_* - const keys = new Set([...Object.keys(config.registries.yarn.config), ...Object.keys(config.registries.npm.config)]); - for (const key of keys) { - if (key.match(/:_/) || IGNORE_CONFIG_KEYS.indexOf(key) >= 0) { - continue; - } + push(key, factory) { + if (this.first) { + this.first = false; + } else { + this.stillActive(); + } - let val = config.getOption(key); + return new Promise((resolve, reject) => { + // we're already running so push ourselves to the queue + const queue = this.queue[key] = this.queue[key] || []; + queue.push({ factory, resolve, reject }); - if (!val) { - val = ''; - } else if (typeof val === 'number') { - val = '' + val; - } else if (typeof val !== 'string') { - val = JSON.stringify(val); + if (!this.running[key]) { + this.shift(key); } + }); + } - if (val.indexOf('\n') >= 0) { - val = JSON.stringify(val); + shift(key) { + if (this.running[key]) { + delete this.running[key]; + this.runningCount--; + + if (this.warnedStuck) { + this.warnedStuck = false; + debug(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`); } + } - const cleanKey = key.replace(/^_+/, ''); - const envKey = `npm_config_${cleanKey}`.replace(/[^a-zA-Z0-9_]/g, '_'); - env[envKey] = val; + const queue = this.queue[key]; + if (!queue) { + return; } - return env; - }); + var _queue$shift = queue.shift(); - return function makeEnv(_x, _x2, _x3) { - return _ref.apply(this, arguments); - }; -})(); + const resolve = _queue$shift.resolve, + reject = _queue$shift.reject, + factory = _queue$shift.factory; -let executeLifecycleScript = exports.executeLifecycleScript = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cwd, cmd, spinner) { - // if we don't have a spinner then pipe everything to the terminal - const stdio = spinner ? undefined : 'inherit'; + if (!queue.length) { + delete this.queue[key]; + } - const env = yield makeEnv(stage, cwd, config); + const next = () => { + this.shift(key); + this.shiftConcurrencyQueue(); + }; - // split up the path - const pathParts = (env[(_constants || _load_constants()).ENV_PATH_KEY] || '').split(path.delimiter); + const run = () => { + this.running[key] = true; + this.runningCount++; - // Include node-gyp version that was bundled with the current Node.js version, - // if available. - pathParts.unshift(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'node-gyp-bin')); - pathParts.unshift(path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin')); + factory().then(function (val) { + resolve(val); + next(); + return null; + }).catch(function (err) { + reject(err); + next(); + }); + }; - // Add global bin folder if it is not present already, as some packages depend - // on a globally-installed version of node-gyp. - const globalBin = (0, (_global || _load_global()).getBinFolder)(config, {}); - if (pathParts.indexOf(globalBin) === -1) { - pathParts.unshift(globalBin); - } + this.maybePushConcurrencyQueue(run); + } - // add .bin folders to PATH - for (const registry of Object.keys((_index || _load_index()).registries)) { - const binFolder = path.join(config.registries[registry].folder, '.bin'); - pathParts.unshift(path.join(config.linkFolder, binFolder)); - pathParts.unshift(path.join(cwd, binFolder)); + maybePushConcurrencyQueue(run) { + if (this.runningCount < this.maxConcurrency) { + run(); + } else { + this.concurrencyQueue.push(run); } + } - yield checkForGypIfNeeded(config, cmd, pathParts); - - if (config.scriptsPrependNodePath) { - pathParts.unshift(path.join(path.dirname(process.execPath))); + shiftConcurrencyQueue() { + if (this.runningCount < this.maxConcurrency) { + const fn = this.concurrencyQueue.shift(); + if (fn) { + fn(); + } } + } +} +exports.default = BlockingQueue; - // join path back together - env[(_constants || _load_constants()).ENV_PATH_KEY] = pathParts.join(path.delimiter); +/***/ }), +/* 80 */ +/***/ (function(module, exports, __webpack_require__) { - // get shell - const conf = { windowsVerbatimArguments: false }; - let sh = 'sh'; - let shFlag = '-c'; - if (process.platform === 'win32') { - // cmd or command.com - sh = process.env.comspec || 'cmd'; +"use strict"; - // d - Ignore registry AutoRun commands - // s - Strip " quote characters from command. - // c - Run Command and then terminate - shFlag = '/d /s /c'; - // handle windows run scripts starting with a relative path - cmd = (0, (_fixCmdWinSlashes || _load_fixCmdWinSlashes()).fixCmdWinSlashes)(cmd); +Object.defineProperty(exports, "__esModule", { + value: true +}); - // handle quotes properly in windows environments - https://github.com/nodejs/node/issues/5060 - conf.windowsVerbatimArguments = true; - } +var _normalizePattern2; - let updateProgress; - if (spinner) { - updateProgress = function (data) { - const dataStr = data.toString() // turn buffer into string - .trim(); // trim whitespace +function _load_normalizePattern() { + return _normalizePattern2 = __webpack_require__(30); +} - invariant(spinner && spinner.tick, 'We should have spinner and its ticker here'); - if (dataStr) { - spinner.tick(dataStr - // Only get the last line - .substr(dataStr.lastIndexOf('\n') + 1) - // change tabs to spaces as they can interfere with the console - .replace(/\t/g, ' ')); - } - }; - } - const stdout = yield (_child || _load_child()).spawn(sh, [shFlag, cmd], (0, (_extends2 || _load_extends()).default)({ cwd, env, stdio }, conf), updateProgress); +const semver = __webpack_require__(22); - return { cwd, command: cmd, stdout }; - }); +class WorkspaceLayout { + constructor(workspaces, config) { + this.workspaces = workspaces; + this.config = config; + } - return function executeLifecycleScript(_x4, _x5, _x6, _x7, _x8) { - return _ref2.apply(this, arguments); - }; -})(); + getWorkspaceManifest(key) { + return this.workspaces[key]; + } -let _checkForGyp = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, paths) { - const reporter = config.reporter; + getManifestByPattern(pattern) { + var _normalizePattern = (0, (_normalizePattern2 || _load_normalizePattern()).normalizePattern)(pattern); - // Check every directory in the PATH + const name = _normalizePattern.name, + range = _normalizePattern.range; - const allChecks = yield Promise.all(paths.map(function (dir) { - return (0, (_fs || _load_fs()).exists)(path.join(dir, 'node-gyp')); - })); - if (allChecks.some(Boolean)) { - // node-gyp is available somewhere - return; + const workspace = this.getWorkspaceManifest(name); + if (!workspace || !semver.satisfies(workspace.manifest.version, range, this.config.looseSemver)) { + return null; } + return workspace; + } +} +exports.default = WorkspaceLayout; - reporter.info(reporter.lang('packageRequiresNodeGyp')); - - try { - yield (0, (_global || _load_global()).run)(config, reporter, {}, ['add', 'node-gyp']); - } catch (e) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('nodeGypAutoInstallFailed', e.message)); - } - }); +/***/ }), +/* 81 */ +/***/ (function(module, exports, __webpack_require__) { - return function _checkForGyp(_x9, _x10) { - return _ref3.apply(this, arguments); - }; -})(); +// getting tag from 19.1.3.6 Object.prototype.toString() +var cof = __webpack_require__(41) + , TAG = __webpack_require__(9)('toStringTag') + // ES3 wrong here + , ARG = cof(function(){ return arguments; }()) == 'Arguments'; -let execFromManifest = exports.execFromManifest = (() => { - var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, commandName, cwd) { - const pkg = yield config.maybeReadManifest(cwd); - if (!pkg || !pkg.scripts) { - return; - } +// fallback for IE11 Script Access Denied error +var tryGet = function(it, key){ + try { + return it[key]; + } catch(e){ /* empty */ } +}; - const cmd = pkg.scripts[commandName]; - if (cmd) { - yield execCommand(commandName, config, cmd, cwd); - } - }); +module.exports = function(it){ + var O, T, B; + return it === undefined ? 'Undefined' : it === null ? 'Null' + // @@toStringTag case + : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T + // builtinTag case + : ARG ? cof(O) + // ES3 arguments fallback + : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; +}; - return function execFromManifest(_x11, _x12, _x13) { - return _ref4.apply(this, arguments); - }; -})(); +/***/ }), +/* 82 */ +/***/ (function(module, exports) { -let execCommand = exports.execCommand = (() => { - var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cmd, cwd) { - const reporter = config.reporter; +module.exports = function(exec){ + try { + return !!exec(); + } catch(e){ + return true; + } +}; - try { - reporter.command(cmd); - yield executeLifecycleScript(stage, config, cwd, cmd); - return Promise.resolve(); - } catch (err) { - if (err instanceof (_errors || _load_errors()).SpawnError) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('commandFailed', err.EXIT_CODE)); - } else { - throw err; - } - } - }); +/***/ }), +/* 83 */ +/***/ (function(module, exports) { - return function execCommand(_x14, _x15, _x16, _x17) { - return _ref5.apply(this, arguments); +module.exports = function(bitmap, value){ + return { + enumerable : !(bitmap & 1), + configurable: !(bitmap & 2), + writable : !(bitmap & 4), + value : value }; -})(); - -var _errors; +}; -function _load_errors() { - return _errors = __webpack_require__(3); -} +/***/ }), +/* 84 */ +/***/ (function(module, exports, __webpack_require__) { -var _constants; +// 7.1.15 ToLength +var toInteger = __webpack_require__(69) + , min = Math.min; +module.exports = function(it){ + return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 +}; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} +/***/ }), +/* 85 */ +/***/ (function(module, exports, __webpack_require__) { -var _child; +"use strict"; -function _load_child() { - return _child = _interopRequireWildcard(__webpack_require__(45)); -} +var $at = __webpack_require__(196)(true); -var _fs; +// 21.1.3.27 String.prototype[@@iterator]() +__webpack_require__(102)(String, 'String', function(iterated){ + this._t = String(iterated); // target + this._i = 0; // next index +// 21.1.5.2.1 %StringIteratorPrototype%.next() +}, function(){ + var O = this._t + , index = this._i + , point; + if(index >= O.length)return {value: undefined, done: true}; + point = $at(O, index); + this._i += point.length; + return {value: point, done: false}; +}); -function _load_fs() { - return _fs = __webpack_require__(4); -} +/***/ }), +/* 86 */ +/***/ (function(module, exports, __webpack_require__) { -var _index; +"use strict"; +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. -function _load_index() { - return _index = __webpack_require__(53); -} -var _fixCmdWinSlashes; -function _load_fixCmdWinSlashes() { - return _fixCmdWinSlashes = __webpack_require__(384); -} +/*<replacement>*/ -var _global; +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/*</replacement>*/ -function _load_global() { - return _global = __webpack_require__(59); -} +module.exports = Duplex; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +/*<replacement>*/ +var processNextTick = __webpack_require__(222); +/*</replacement>*/ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/*<replacement>*/ +var util = __webpack_require__(110); +util.inherits = __webpack_require__(39); +/*</replacement>*/ -const invariant = __webpack_require__(5); +var Readable = __webpack_require__(305); +var Writable = __webpack_require__(307); -const path = __webpack_require__(1); +util.inherits(Duplex, Readable); -const IGNORE_MANIFEST_KEYS = ['readme']; - -// We treat these configs as internal, thus not expose them to process.env. -// This helps us avoid some gyp issues when building native modules. -// See https://github.com/yarnpkg/yarn/issues/2286. -const IGNORE_CONFIG_KEYS = ['lastUpdateCheck']; - -exports.default = executeLifecycleScript; - - -let checkGypPromise = null; -/** - * Special case: Some packages depend on node-gyp, but don't specify this in - * their package.json dependencies. They assume that node-gyp is available - * globally. We need to detect this case and show an error message. - */ -function checkForGypIfNeeded(config, cmd, paths) { - if (cmd.substr(0, cmd.indexOf(' ')) !== 'node-gyp') { - return Promise.resolve(); - } - - // Ensure this only runs once, rather than multiple times in parallel. - if (!checkGypPromise) { - checkGypPromise = _checkForGyp(config, paths); - } - return checkGypPromise; +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } -/***/ }), -/* 63 */ -/***/ (function(module, exports, __webpack_require__) { +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); -"use strict"; + Readable.call(this, options); + Writable.call(this, options); + if (options && options.readable === false) this.readable = false; -Object.defineProperty(exports, "__esModule", { - value: true -}); + if (options && options.writable === false) this.writable = false; -var _slicedToArray2; + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); + this.once('end', onend); } -exports.isValidPackageName = isValidPackageName; - -exports.default = function (info, isRoot, reporter, warn) { - if (isRoot) { - for (const key in (_typos || _load_typos()).default) { - if (key in info) { - warn(reporter.lang('manifestPotentialTypo', key, (_typos || _load_typos()).default[key])); - } - } - } - - // validate name - const name = info.name; - - if (typeof name === 'string') { - if (isRoot && isBuiltinModule(name)) { - warn(reporter.lang('manifestBuiltinModule', name)); - } - - // cannot start with a dot - if (name[0] === '.') { - throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameDot')); - } - - // cannot contain the following characters - if (!isValidPackageName(name)) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameIllegalChars')); - } - - // cannot equal node_modules or favicon.ico - const lower = name.toLowerCase(); - if (lower === 'node_modules' || lower === 'favicon.ico') { - throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameBlacklisted')); - } - } - - // validate license - if (isRoot && !info.private) { - if (typeof info.license === 'string') { - const license = info.license.replace(/\*$/g, ''); - if (!(0, (_util || _load_util()).isValidLicense)(license)) { - warn(reporter.lang('manifestLicenseInvalid')); - } - } else { - warn(reporter.lang('manifestLicenseNone')); - } - } - - // validate strings - for (const key of strings) { - const val = info[key]; - if (val && typeof val !== 'string') { - throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestStringExpected', key)); - } - } - - cleanDependencies(info, isRoot, reporter, warn); -}; - -exports.cleanDependencies = cleanDependencies; - -var _errors; +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; -function _load_errors() { - return _errors = __webpack_require__(3); + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); } -var _util; - -function _load_util() { - return _util = __webpack_require__(130); +function onEndNT(self) { + self.end(); } -var _typos; - -function _load_typos() { - return _typos = _interopRequireDefault(__webpack_require__(389)); +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const isBuiltinModule = __webpack_require__(534); - -const strings = ['name', 'version']; - -const dependencyKeys = [ -// npm registry will include optionalDependencies in dependencies and we'll want to dedupe them from the -// other fields first -'optionalDependencies', +/***/ }), +/* 87 */ +/***/ (function(module, exports, __webpack_require__) { -// it's seemingly common to include a dependency in dependencies and devDependencies of the same name but -// different ranges, this can cause a lot of issues with our determinism and the behaviour of npm is -// currently unspecified. -'dependencies', 'devDependencies']; +var buffer = __webpack_require__(120) -function isValidName(name) { - return !name.match(/[\/@\s\+%:]/) && encodeURIComponent(name) === name; +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + Object.keys(buffer).forEach(function (prop) { + exports[prop] = buffer[prop] + }) + exports.Buffer = SafeBuffer } -function isValidScopedName(name) { - if (name[0] !== '@') { - return false; - } - - const parts = name.slice(1).split('/'); - return parts.length === 2 && isValidName(parts[0]) && isValidName(parts[1]); +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -function isValidPackageName(name) { - return isValidName(name) || isValidScopedName(name); -} +// Copy static methods from Buffer +Object.keys(Buffer).forEach(function (prop) { + SafeBuffer[prop] = Buffer[prop] +}) -function cleanDependencies(info, isRoot, reporter, warn) { - // get dependency objects - const depTypes = []; - for (const type of dependencyKeys) { - const deps = info[type]; - if (!deps || typeof deps !== 'object') { - continue; - } - depTypes.push([type, deps]); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } + return Buffer(arg, encodingOrOffset, length) +} - // aggregate all non-trivial deps (not '' or '*') - const nonTrivialDeps = new Map(); - for (const _ref of depTypes) { - var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); - - const type = _ref2[0]; - const deps = _ref2[1]; - - for (const name of Object.keys(deps)) { - const version = deps[name]; - if (!nonTrivialDeps.has(name) && version && version !== '*') { - nonTrivialDeps.set(name, { type, version }); - } - } +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') } - - // overwrite first dep of package with non-trivial version, remove the rest - const setDeps = new Set(); - for (const _ref3 of depTypes) { - var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2); - - const type = _ref4[0]; - const deps = _ref4[1]; - - for (const name of Object.keys(deps)) { - let version = deps[name]; - - const dep = nonTrivialDeps.get(name); - if (dep) { - if (version && version !== '*' && version !== dep.version && isRoot) { - // only throw a warning when at the root - warn(reporter.lang('manifestDependencyCollision', dep.type, name, dep.version, type, version)); - } - version = dep.version; - } - - if (setDeps.has(name)) { - delete deps[name]; - } else { - deps[name] = version; - setDeps.add(name); - } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) } + } else { + buf.fill(0) } + return buf } -/***/ }), -/* 64 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.wait = wait; -exports.promisify = promisify; -exports.queue = queue; -function wait(delay) { - return new Promise(resolve => { - setTimeout(resolve, delay); - }); +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) } -function promisify(fn, firstData) { - return function () { - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - return new Promise(function (resolve, reject) { - args.push(function (err) { - for (var _len2 = arguments.length, result = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - result[_key2 - 1] = arguments[_key2]; - } +/***/ }), +/* 88 */ +/***/ (function(module, exports, __webpack_require__) { - let res = result; +var v1 = __webpack_require__(648); +var v4 = __webpack_require__(649); - if (result.length <= 1) { - res = result[0]; - } +var uuid = v4; +uuid.v1 = v1; +uuid.v4 = v4; - if (firstData) { - res = err; - err = null; - } +module.exports = uuid; - if (err) { - reject(err); - } else { - resolve(res); - } - }); - fn.apply(null, args); - }); - }; -} +/***/ }), +/* 89 */ +/***/ (function(module, exports) { -function queue(arr, promiseProducer) { - let concurrency = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Infinity; +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) - concurrency = Math.min(concurrency, arr.length); + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') - // clone - arr = arr.slice(); + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) - const results = []; - let total = arr.length; - if (!total) { - return Promise.resolve(results); - } + return wrapper - return new Promise((resolve, reject) => { - for (let i = 0; i < concurrency; i++) { - next(); + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} - function next() { - const item = arr.shift(); - const promise = promiseProducer(item); - promise.then(function (result) { - results.push(result); +/***/ }), +/* 90 */ +/***/ (function(module, exports) { - total--; - if (total === 0) { - resolve(results); - } else { - if (arr.length) { - next(); - } - } - }, reject); - } - }); -} +module.exports = require("tty"); /***/ }), -/* 65 */ +/* 91 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(__dirname) { + Object.defineProperty(exports, "__esModule", { value: true @@ -34698,7 +36185,7 @@ exports.getInstallationMethod = exports.version = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } let getInstallationMethod = exports.getInstallationMethod = (() => { @@ -34741,19 +36228,19 @@ function _load_fs() { var _fs2; function _load_fs2() { - return _fs2 = _interopRequireDefault(__webpack_require__(6)); + return _fs2 = _interopRequireDefault(__webpack_require__(5)); } var _path; function _load_path() { - return _path = _interopRequireDefault(__webpack_require__(1)); + return _path = _interopRequireDefault(__webpack_require__(0)); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // This will be bundled directly in the .js file for production builds -var _require = __webpack_require__(279); /** +var _require = __webpack_require__(147); /** * Determines the current version of Yarn itself. * */ @@ -34761,10 +36248,9 @@ var _require = __webpack_require__(279); /** const version = _require.version, originalInstallationMethod = _require.installationMethod; exports.version = version; -/* WEBPACK VAR INJECTION */}.call(exports, "/")) /***/ }), -/* 66 */ +/* 92 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -34773,1587 +36259,1126 @@ exports.version = version; Object.defineProperty(exports, "__esModule", { value: true }); +exports.run = exports.getBinFolder = undefined; -var _packageRequest; +var _asyncToGenerator2; -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const semver = __webpack_require__(27); +let updateCwd = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { + yield (_fs || _load_fs()).mkdirp(config.globalFolder); -class WorkspaceLayout { - constructor(workspaces, config) { - this.workspaces = workspaces; - this.config = config; - } + yield config.init({ + cwd: config.globalFolder, + binLinks: true, + globalFolder: config.globalFolder, + cacheFolder: config._cacheRootFolder, + linkFolder: config.linkFolder + }); + }); - getWorkspaceManifest(key) { - return this.workspaces[key]; - } + return function updateCwd(_x) { + return _ref.apply(this, arguments); + }; +})(); - getManifestByPattern(pattern) { - var _PackageRequest$norma = (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern); +let getBins = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { + // build up list of registry folders to search for binaries + const dirs = []; + for (const registryName of Object.keys((_index || _load_index()).registries)) { + const registry = config.registries[registryName]; + dirs.push(registry.loc); + } - const name = _PackageRequest$norma.name, - range = _PackageRequest$norma.range; + // build up list of binary files + const paths = new Set(); + for (const dir of dirs) { + const binDir = path.join(dir, '.bin'); + if (!(yield (_fs || _load_fs()).exists(binDir))) { + continue; + } - const workspace = this.getWorkspaceManifest(name); - if (!workspace || !semver.satisfies(workspace.manifest.version, range, this.config.looseSemver)) { - return null; + for (const name of yield (_fs || _load_fs()).readdir(binDir)) { + paths.add(path.join(binDir, name)); + } } - return workspace; - } -} -exports.default = WorkspaceLayout; + return paths; + }); -/***/ }), -/* 67 */ -/***/ (function(module, exports, __webpack_require__) { + return function getBins(_x2) { + return _ref2.apply(this, arguments); + }; +})(); -"use strict"; +let getGlobalPrefix = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags) { + if (flags.prefix) { + return flags.prefix; + } else if (config.getOption('prefix', true)) { + return String(config.getOption('prefix', true)); + } else if (process.env.PREFIX) { + return process.env.PREFIX; + } + const potentialPrefixFolders = [(_constants || _load_constants()).FALLBACK_GLOBAL_PREFIX]; + if (process.platform === 'win32') { + // %LOCALAPPDATA%\Yarn --> C:\Users\Alice\AppData\Local\Yarn + if (process.env.LOCALAPPDATA) { + potentialPrefixFolders.unshift(path.join(process.env.LOCALAPPDATA, 'Yarn')); + } + } else { + potentialPrefixFolders.unshift((_constants || _load_constants()).POSIX_GLOBAL_PREFIX); + } -exports.__esModule = true; + const binFolders = potentialPrefixFolders.map(function (prefix) { + return path.join(prefix, 'bin'); + }); + const prefixFolderQueryResult = yield (_fs || _load_fs()).getFirstSuitableFolder(binFolders); + const prefix = prefixFolderQueryResult.folder && path.dirname(prefixFolderQueryResult.folder); -var _from = __webpack_require__(394); + if (!prefix) { + config.reporter.warn(config.reporter.lang('noGlobalFolder', prefixFolderQueryResult.skipped.map(function (item) { + return path.dirname(item.folder); + }).join(', '))); -var _from2 = _interopRequireDefault(_from); + return (_constants || _load_constants()).FALLBACK_GLOBAL_PREFIX; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return prefix; + }); -exports.default = function (arr) { - return Array.isArray(arr) ? arr : (0, _from2.default)(arr); -}; + return function getGlobalPrefix(_x3, _x4) { + return _ref3.apply(this, arguments); + }; +})(); -/***/ }), -/* 68 */ -/***/ (function(module, exports, __webpack_require__) { +let getBinFolder = exports.getBinFolder = (() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags) { + const prefix = yield getGlobalPrefix(config, flags); + return path.resolve(prefix, 'bin'); + }); -// optional / simple context binding -var aFunction = __webpack_require__(134); -module.exports = function(fn, that, length){ - aFunction(fn); - if(that === undefined)return fn; - switch(length){ - case 1: return function(a){ - return fn.call(that, a); - }; - case 2: return function(a, b){ - return fn.call(that, a, b); - }; - case 3: return function(a, b, c){ - return fn.call(that, a, b, c); - }; - } - return function(/* ...args */){ - return fn.apply(that, arguments); + return function getBinFolder(_x5, _x6) { + return _ref4.apply(this, arguments); }; -}; +})(); -/***/ }), -/* 69 */ -/***/ (function(module, exports, __webpack_require__) { +let initUpdateBins = (() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags) { + const beforeBins = yield getBins(config); + const binFolder = yield getBinFolder(config, flags); -// Thank's IE8 for his funny defineProperty -module.exports = !__webpack_require__(138)(function(){ - return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; -}); + function throwPermError(err, dest) { + if (err.code === 'EACCES') { + throw new (_errors || _load_errors()).MessageError(reporter.lang('noPermission', dest)); + } else { + throw err; + } + } -/***/ }), -/* 70 */ -/***/ (function(module, exports, __webpack_require__) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + try { + yield (_fs || _load_fs()).mkdirp(binFolder); + } catch (err) { + throwPermError(err, binFolder); + } -var anObject = __webpack_require__(46) - , IE8_DOM_DEFINE = __webpack_require__(423) - , toPrimitive = __webpack_require__(441) - , dP = Object.defineProperty; + const afterBins = yield getBins(config); -exports.f = __webpack_require__(69) ? Object.defineProperty : function defineProperty(O, P, Attributes){ - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if(IE8_DOM_DEFINE)try { - return dP(O, P, Attributes); - } catch(e){ /* empty */ } - if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); - if('value' in Attributes)O[P] = Attributes.value; - return O; -}; + // remove old bins + for (const src of beforeBins) { + if (afterBins.has(src)) { + // not old + continue; + } -/***/ }), -/* 71 */ -/***/ (function(module, exports) { + // remove old bin + const dest = path.join(binFolder, path.basename(src)); + try { + yield (_fs || _load_fs()).unlink(dest); + } catch (err) { + throwPermError(err, dest); + } + } -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + // add new bins + for (const src of afterBins) { + if (beforeBins.has(src)) { + // already inserted + continue; + } -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. + // insert new bin + const dest = path.join(binFolder, path.basename(src)); + try { + yield (_fs || _load_fs()).unlink(dest); + yield (0, (_packageLinker || _load_packageLinker()).linkBin)(src, dest); + if (process.platform === 'win32' && dest.indexOf('.cmd') !== -1) { + yield (_fs || _load_fs()).rename(dest + '.cmd', dest); + } + } catch (err) { + throwPermError(err, dest); + } + } + }); + }); -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; + return function initUpdateBins(_x7, _x8, _x9) { + return _ref5.apply(this, arguments); + }; +})(); -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; +let list = (() => { + var _ref7 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + yield updateCwd(config); -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + // install so we get hard file paths + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.cwd); + const install = new (_install || _load_install()).Install({ skipIntegrityCheck: true }, config, new (_baseReporter || _load_baseReporter()).default(), lockfile); + const patterns = yield install.init(); -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; + // dump global modules + for (const pattern of patterns) { + const manifest = install.resolver.getStrictResolvedPattern(pattern); + ls(manifest, reporter, false); + } + }); -function isNumber(arg) { - return typeof arg === 'number'; + return function list(_x10, _x11, _x12, _x13) { + return _ref7.apply(this, arguments); + }; +})(); + +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); } -exports.isNumber = isNumber; -function isString(arg) { - return typeof arg === 'string'; +var _index; + +function _load_index() { + return _index = __webpack_require__(34); } -exports.isString = isString; -function isSymbol(arg) { - return typeof arg === 'symbol'; +var _baseReporter; + +function _load_baseReporter() { + return _baseReporter = _interopRequireDefault(__webpack_require__(77)); } -exports.isSymbol = isSymbol; -function isUndefined(arg) { - return arg === void 0; +var _buildSubCommands2; + +function _load_buildSubCommands() { + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); } -exports.isUndefined = isUndefined; -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; +var _lockfile; + +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); } -exports.isRegExp = isRegExp; -function isObject(arg) { - return typeof arg === 'object' && arg !== null; +var _install; + +function _load_install() { + return _install = __webpack_require__(31); } -exports.isObject = isObject; -function isDate(d) { - return objectToString(d) === '[object Date]'; +var _add; + +function _load_add() { + return _add = __webpack_require__(121); } -exports.isDate = isDate; -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); +var _remove; + +function _load_remove() { + return _remove = __webpack_require__(257); } -exports.isError = isError; -function isFunction(arg) { - return typeof arg === 'function'; +var _upgrade; + +function _load_upgrade() { + return _upgrade = __webpack_require__(157); } -exports.isFunction = isFunction; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; +var _upgradeInteractive; + +function _load_upgradeInteractive() { + return _upgradeInteractive = __webpack_require__(259); } -exports.isPrimitive = isPrimitive; -exports.isBuffer = Buffer.isBuffer; +var _packageLinker; -function objectToString(o) { - return Object.prototype.toString.call(o); +function _load_packageLinker() { + return _packageLinker = __webpack_require__(159); } +var _constants; -/***/ }), -/* 72 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_constants() { + return _constants = __webpack_require__(6); +} -// Copyright 2016 Joyent, Inc. +var _fs; -module.exports = Certificate; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} -var assert = __webpack_require__(9); -var algs = __webpack_require__(16); -var crypto = __webpack_require__(7); -var Fingerprint = __webpack_require__(73); -var Signature = __webpack_require__(33); -var errs = __webpack_require__(32); -var util = __webpack_require__(2); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var Identity = __webpack_require__(75); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -var formats = {}; -formats['openssh'] = __webpack_require__(618); -formats['x509'] = __webpack_require__(267); -formats['pem'] = __webpack_require__(619); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var CertificateParseError = errs.CertificateParseError; -var InvalidAlgorithmError = errs.InvalidAlgorithmError; +class GlobalAdd extends (_add || _load_add()).Add { + constructor(args, flags, config, reporter, lockfile) { + super(args, flags, config, reporter, lockfile); -function Certificate(opts) { - assert.object(opts, 'options'); - assert.arrayOfObject(opts.subjects, 'options.subjects'); - utils.assertCompatible(opts.subjects[0], Identity, [1, 0], - 'options.subjects'); - utils.assertCompatible(opts.subjectKey, Key, [1, 0], - 'options.subjectKey'); - utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer'); - if (opts.issuerKey !== undefined) { - utils.assertCompatible(opts.issuerKey, Key, [1, 0], - 'options.issuerKey'); - } - assert.object(opts.signatures, 'options.signatures'); - assert.buffer(opts.serial, 'options.serial'); - assert.date(opts.validFrom, 'options.validFrom'); - assert.date(opts.validUntil, 'optons.validUntil'); + this.linker.setTopLevelBinLinking(false); + } - assert.optionalArrayOfString(opts.purposes, 'options.purposes'); + maybeOutputSaveTree() { + for (const pattern of this.addedPatterns) { + const manifest = this.resolver.getStrictResolvedPattern(pattern); + ls(manifest, this.reporter, true); + } + return Promise.resolve(); + } - this._hashCache = {}; + _logSuccessSaveLockfile() { + // noop + } +} - this.subjects = opts.subjects; - this.issuer = opts.issuer; - this.subjectKey = opts.subjectKey; - this.issuerKey = opts.issuerKey; - this.signatures = opts.signatures; - this.serial = opts.serial; - this.validFrom = opts.validFrom; - this.validUntil = opts.validUntil; - this.purposes = opts.purposes; +const path = __webpack_require__(0); + +function hasWrapper(flags, args) { + return args[0] !== 'bin'; } -Certificate.formats = formats; +function ls(manifest, reporter, saved) { + const bins = manifest.bin ? Object.keys(manifest.bin) : []; + const human = `${manifest.name}@${manifest.version}`; + if (bins.length) { + if (saved) { + reporter.success(reporter.lang('packageInstalledWithBinaries', human)); + } else { + reporter.info(reporter.lang('packageHasBinaries', human)); + } + reporter.list(`bins-${manifest.name}`, bins); + } else if (saved) { + reporter.warn(reporter.lang('packageHasNoBinaries', human)); + } +} -Certificate.prototype.toBuffer = function (format, options) { - if (format === undefined) - format = 'x509'; - assert.string(format, 'format'); - assert.object(formats[format], 'formats[format]'); - assert.optionalObject(options, 'options'); +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('global', { + add(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield updateCwd(config); - return (formats[format].write(this, options)); -}; + const updateBins = yield initUpdateBins(config, reporter, flags); + if (args.indexOf('yarn') !== -1) { + reporter.warn(reporter.lang('packageContainsYarnAsGlobal')); + } -Certificate.prototype.toString = function (format, options) { - if (format === undefined) - format = 'pem'; - return (this.toBuffer(format, options).toString()); -}; + // install module + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.cwd); + const install = new GlobalAdd(args, flags, config, reporter, lockfile); + yield install.init(); -Certificate.prototype.fingerprint = function (algo) { - if (algo === undefined) - algo = 'sha256'; - assert.string(algo, 'algorithm'); - var opts = { - type: 'certificate', - hash: this.hash(algo), - algorithm: algo - }; - return (new Fingerprint(opts)); -}; + // link binaries + yield updateBins(); + })(); + }, -Certificate.prototype.hash = function (algo) { - assert.string(algo, 'algorithm'); - algo = algo.toLowerCase(); - if (algs.hashAlgs[algo] === undefined) - throw (new InvalidAlgorithmError(algo)); + bin(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + reporter.log((yield getBinFolder(config, flags))); + })(); + }, - if (this._hashCache[algo]) - return (this._hashCache[algo]); + ls(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + reporter.warn(`\`yarn global ls\` is deprecated. Please use \`yarn global list\`.`); + yield list(config, reporter, flags, args); + })(); + }, - var hash = crypto.createHash(algo). - update(this.toBuffer('x509')).digest(); - this._hashCache[algo] = hash; - return (hash); -}; + list(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield list(config, reporter, flags, args); + })(); + }, -Certificate.prototype.isExpired = function (when) { - if (when === undefined) - when = new Date(); - return (!((when.getTime() >= this.validFrom.getTime()) && - (when.getTime() < this.validUntil.getTime()))); -}; + remove(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield updateCwd(config); -Certificate.prototype.isSignedBy = function (issuerCert) { - utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer'); + const updateBins = yield initUpdateBins(config, reporter, flags); - if (!this.issuer.equals(issuerCert.subjects[0])) - return (false); - if (this.issuer.purposes && this.issuer.purposes.length > 0 && - this.issuer.purposes.indexOf('ca') === -1) { - return (false); - } + // remove module + yield (0, (_remove || _load_remove()).run)(config, reporter, flags, args); - return (this.isSignedByKey(issuerCert.subjectKey)); -}; + // remove binaries + yield updateBins(); + })(); + }, -Certificate.prototype.isSignedByKey = function (issuerKey) { - utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey'); + upgrade(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield updateCwd(config); - if (this.issuerKey !== undefined) { - return (this.issuerKey. - fingerprint('sha512').matches(issuerKey)); - } + const updateBins = yield initUpdateBins(config, reporter, flags); - var fmt = Object.keys(this.signatures)[0]; - var valid = formats[fmt].verify(this, issuerKey); - if (valid) - this.issuerKey = issuerKey; - return (valid); -}; + // upgrade module + yield (0, (_upgrade || _load_upgrade()).run)(config, reporter, flags, args); -Certificate.prototype.signWith = function (key) { - utils.assertCompatible(key, PrivateKey, [1, 2], 'key'); - var fmts = Object.keys(formats); - var didOne = false; - for (var i = 0; i < fmts.length; ++i) { - if (fmts[i] !== 'pem') { - var ret = formats[fmts[i]].sign(this, key); - if (ret === true) - didOne = true; - } - } - if (!didOne) { - throw (new Error('Failed to sign the certificate for any ' + - 'available certificate formats')); - } -}; + // update binaries + yield updateBins(); + })(); + }, -Certificate.createSelfSigned = function (subjectOrSubjects, key, options) { - var subjects; - if (Array.isArray(subjectOrSubjects)) - subjects = subjectOrSubjects; - else - subjects = [subjectOrSubjects]; + upgradeInteractive(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield updateCwd(config); - assert.arrayOfObject(subjects); - subjects.forEach(function (subject) { - utils.assertCompatible(subject, Identity, [1, 0], 'subject'); - }); + const updateBins = yield initUpdateBins(config, reporter, flags); - utils.assertCompatible(key, PrivateKey, [1, 2], 'private key'); + // upgrade module + yield (0, (_upgradeInteractive || _load_upgradeInteractive()).run)(config, reporter, flags, args); - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalObject(options.validFrom, 'options.validFrom'); - assert.optionalObject(options.validUntil, 'options.validUntil'); - var validFrom = options.validFrom; - var validUntil = options.validUntil; - if (validFrom === undefined) - validFrom = new Date(); - if (validUntil === undefined) { - assert.optionalNumber(options.lifetime, 'options.lifetime'); - var lifetime = options.lifetime; - if (lifetime === undefined) - lifetime = 10*365*24*3600; - validUntil = new Date(); - validUntil.setTime(validUntil.getTime() + lifetime*1000); - } - assert.optionalBuffer(options.serial, 'options.serial'); - var serial = options.serial; - if (serial === undefined) - serial = new Buffer('0000000000000001', 'hex'); + // update binaries + yield updateBins(); + })(); + } +}); - var purposes = options.purposes; - if (purposes === undefined) - purposes = []; +const run = _buildSubCommands.run, + _setFlags = _buildSubCommands.setFlags; +exports.run = run; +function setFlags(commander) { + _setFlags(commander); + commander.option('--prefix <prefix>', 'bin prefix to use to install binaries'); +} - if (purposes.indexOf('signature') === -1) - purposes.push('signature'); +/***/ }), +/* 93 */ +/***/ (function(module, exports, __webpack_require__) { - /* Self-signed certs are always CAs. */ - if (purposes.indexOf('ca') === -1) - purposes.push('ca'); - if (purposes.indexOf('crl') === -1) - purposes.push('crl'); +"use strict"; - /* - * If we weren't explicitly given any other purposes, do the sensible - * thing and add some basic ones depending on the subject type. - */ - if (purposes.length <= 3) { - var hostSubjects = subjects.filter(function (subject) { - return (subject.type === 'host'); - }); - var userSubjects = subjects.filter(function (subject) { - return (subject.type === 'user'); - }); - if (hostSubjects.length > 0) { - if (purposes.indexOf('serverAuth') === -1) - purposes.push('serverAuth'); - } - if (userSubjects.length > 0) { - if (purposes.indexOf('clientAuth') === -1) - purposes.push('clientAuth'); - } - if (userSubjects.length > 0 || hostSubjects.length > 0) { - if (purposes.indexOf('keyAgreement') === -1) - purposes.push('keyAgreement'); - if (key.type === 'rsa' && - purposes.indexOf('encryption') === -1) - purposes.push('encryption'); - } - } - var cert = new Certificate({ - subjects: subjects, - issuer: subjects[0], - subjectKey: key.toPublic(), - issuerKey: key.toPublic(), - signatures: {}, - serial: serial, - validFrom: validFrom, - validUntil: validUntil, - purposes: purposes - }); - cert.signWith(key); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.getToken = undefined; - return (cert); -}; +var _asyncToGenerator2; -Certificate.create = - function (subjectOrSubjects, key, issuer, issuerKey, options) { - var subjects; - if (Array.isArray(subjectOrSubjects)) - subjects = subjectOrSubjects; - else - subjects = [subjectOrSubjects]; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - assert.arrayOfObject(subjects); - subjects.forEach(function (subject) { - utils.assertCompatible(subject, Identity, [1, 0], 'subject'); - }); +let getCredentials = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) { + var _config$registries$ya = config.registries.yarn.config; + let username = _config$registries$ya.username, + email = _config$registries$ya.email; - utils.assertCompatible(key, Key, [1, 0], 'key'); - if (PrivateKey.isPrivateKey(key)) - key = key.toPublic(); - utils.assertCompatible(issuer, Identity, [1, 0], 'issuer'); - utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key'); - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalObject(options.validFrom, 'options.validFrom'); - assert.optionalObject(options.validUntil, 'options.validUntil'); - var validFrom = options.validFrom; - var validUntil = options.validUntil; - if (validFrom === undefined) - validFrom = new Date(); - if (validUntil === undefined) { - assert.optionalNumber(options.lifetime, 'options.lifetime'); - var lifetime = options.lifetime; - if (lifetime === undefined) - lifetime = 10*365*24*3600; - validUntil = new Date(); - validUntil.setTime(validUntil.getTime() + lifetime*1000); - } - assert.optionalBuffer(options.serial, 'options.serial'); - var serial = options.serial; - if (serial === undefined) - serial = new Buffer('0000000000000001', 'hex'); - - var purposes = options.purposes; - if (purposes === undefined) - purposes = []; + if (username) { + reporter.info(`${reporter.lang('npmUsername')}: ${username}`); + } else { + username = yield reporter.question(reporter.lang('npmUsername')); + if (!username) { + return null; + } + } - if (purposes.indexOf('signature') === -1) - purposes.push('signature'); + if (email) { + reporter.info(`${reporter.lang('npmEmail')}: ${email}`); + } else { + email = yield reporter.question(reporter.lang('npmEmail')); + if (!email) { + return null; + } + } - if (options.ca === true) { - if (purposes.indexOf('ca') === -1) - purposes.push('ca'); - if (purposes.indexOf('crl') === -1) - purposes.push('crl'); - } + yield config.registries.yarn.saveHomeConfig({ username, email }); - var hostSubjects = subjects.filter(function (subject) { - return (subject.type === 'host'); - }); - var userSubjects = subjects.filter(function (subject) { - return (subject.type === 'user'); - }); - if (hostSubjects.length > 0) { - if (purposes.indexOf('serverAuth') === -1) - purposes.push('serverAuth'); - } - if (userSubjects.length > 0) { - if (purposes.indexOf('clientAuth') === -1) - purposes.push('clientAuth'); - } - if (userSubjects.length > 0 || hostSubjects.length > 0) { - if (purposes.indexOf('keyAgreement') === -1) - purposes.push('keyAgreement'); - if (key.type === 'rsa' && - purposes.indexOf('encryption') === -1) - purposes.push('encryption'); - } + return { username, email }; + }); - var cert = new Certificate({ - subjects: subjects, - issuer: issuer, - subjectKey: key, - issuerKey: issuerKey.toPublic(), - signatures: {}, - serial: serial, - validFrom: validFrom, - validUntil: validUntil, - purposes: purposes - }); - cert.signWith(issuerKey); + return function getCredentials(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); - return (cert); -}; +let getToken = exports.getToken = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) { + let name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ''; -Certificate.parse = function (data, format, options) { - if (typeof (data) !== 'string') - assert.buffer(data, 'data'); - if (format === undefined) - format = 'auto'; - assert.string(format, 'format'); - if (typeof (options) === 'string') - options = { filename: options }; - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - assert.optionalString(options.filename, 'options.filename'); - if (options.filename === undefined) - options.filename = '(unnamed)'; + const auth = config.registries.npm.getAuth(name); + if (auth) { + config.registries.npm.setToken(auth); + return function revoke() { + reporter.info(reporter.lang('notRevokingConfigToken')); + return Promise.resolve(); + }; + } - assert.object(formats[format], 'formats[format]'); + const env = process.env.YARN_AUTH_TOKEN || process.env.NPM_AUTH_TOKEN; + if (env) { + config.registries.npm.setToken(`Bearer ${env}`); + return function revoke() { + reporter.info(reporter.lang('notRevokingEnvToken')); + return Promise.resolve(); + }; + } - try { - var k = formats[format].read(data, options); - return (k); - } catch (e) { - throw (new CertificateParseError(options.filename, format, e)); - } -}; + // + const creds = yield getCredentials(config, reporter); + if (!creds) { + reporter.warn(reporter.lang('loginAsPublic')); + return function revoke() { + reporter.info(reporter.lang('noTokenToRevoke')); + return Promise.resolve(); + }; + } -Certificate.isCertificate = function (obj, ver) { - return (utils.isCompatible(obj, Certificate, ver)); -}; + const username = creds.username, + email = creds.email; -/* - * API versions for Certificate: - * [1,0] -- initial ver - */ -Certificate.prototype._sshpkApiVersion = [1, 0]; + const password = yield reporter.question(reporter.lang('npmPassword'), { + password: true, + required: true + }); -Certificate._oldVersionDetect = function (obj) { - return ([1, 0]); -}; + // + const userobj = { + _id: `org.couchdb.user:${username}`, + name: username, + password, + email, + type: 'user', + roles: [], + date: new Date().toISOString() + }; + // + const res = yield config.registries.npm.request(`-/user/org.couchdb.user:${encodeURIComponent(username)}`, { + method: 'PUT', + body: userobj, + auth: { username, password, email } + }); -/***/ }), -/* 73 */ -/***/ (function(module, exports, __webpack_require__) { + if (res && res.ok) { + reporter.success(reporter.lang('loggedIn')); -// Copyright 2015 Joyent, Inc. + const token = res.token; + config.registries.npm.setToken(`Bearer ${token}`); -module.exports = Fingerprint; + return (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + reporter.success(reporter.lang('revokedToken')); + yield config.registries.npm.request(`-/user/token/${token}`, { + method: 'DELETE' + }); + }); -var assert = __webpack_require__(9); -var algs = __webpack_require__(16); -var crypto = __webpack_require__(7); -var errs = __webpack_require__(32); -var Key = __webpack_require__(17); -var Certificate = __webpack_require__(72); -var utils = __webpack_require__(13); + function revoke() { + return _ref3.apply(this, arguments); + } -var FingerprintFormatError = errs.FingerprintFormatError; -var InvalidAlgorithmError = errs.InvalidAlgorithmError; + return revoke; + })(); + } else { + throw new (_errors || _load_errors()).MessageError(reporter.lang('incorrectCredentials')); + } + }); -function Fingerprint(opts) { - assert.object(opts, 'options'); - assert.string(opts.type, 'options.type'); - assert.buffer(opts.hash, 'options.hash'); - assert.string(opts.algorithm, 'options.algorithm'); + return function getToken(_x3, _x4) { + return _ref2.apply(this, arguments); + }; +})(); - this.algorithm = opts.algorithm.toLowerCase(); - if (algs.hashAlgs[this.algorithm] !== true) - throw (new InvalidAlgorithmError(this.algorithm)); +let run = exports.run = (() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + yield getCredentials(config, reporter); + }); - this.hash = opts.hash; - this.type = opts.type; -} + return function run(_x6, _x7, _x8, _x9) { + return _ref4.apply(this, arguments); + }; +})(); -Fingerprint.prototype.toString = function (format) { - if (format === undefined) { - if (this.algorithm === 'md5') - format = 'hex'; - else - format = 'base64'; - } - assert.string(format); +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; - switch (format) { - case 'hex': - return (addColons(this.hash.toString('hex'))); - case 'base64': - return (sshBase64Format(this.algorithm, - this.hash.toString('base64'))); - default: - throw (new FingerprintFormatError(undefined, format)); - } -}; +var _errors; -Fingerprint.prototype.matches = function (other) { - assert.object(other, 'key or certificate'); - if (this.type === 'key') { - utils.assertCompatible(other, Key, [1, 0], 'key'); - } else { - utils.assertCompatible(other, Certificate, [1, 0], - 'certificate'); - } +function _load_errors() { + return _errors = __webpack_require__(3); +} - var theirHash = other.hash(this.algorithm); - var theirHash2 = crypto.createHash(this.algorithm). - update(theirHash).digest('base64'); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (this.hash2 === undefined) - this.hash2 = crypto.createHash(this.algorithm). - update(this.hash).digest('base64'); +function hasWrapper(commander, args) { + return true; +} - return (this.hash2 === theirHash2); -}; +function setFlags(commander) {} -Fingerprint.parse = function (fp, options) { - assert.string(fp, 'fingerprint'); +/***/ }), +/* 94 */ +/***/ (function(module, exports, __webpack_require__) { - var alg, hash, enAlgs; - if (Array.isArray(options)) { - enAlgs = options; - options = {}; - } - assert.optionalObject(options, 'options'); - if (options === undefined) - options = {}; - if (options.enAlgs !== undefined) - enAlgs = options.enAlgs; - assert.optionalArrayOfString(enAlgs, 'algorithms'); +"use strict"; - var parts = fp.split(':'); - if (parts.length == 2) { - alg = parts[0].toLowerCase(); - /*JSSTYLED*/ - var base64RE = /^[A-Za-z0-9+\/=]+$/; - if (!base64RE.test(parts[1])) - throw (new FingerprintFormatError(fp)); - try { - hash = new Buffer(parts[1], 'base64'); - } catch (e) { - throw (new FingerprintFormatError(fp)); - } - } else if (parts.length > 2) { - alg = 'md5'; - if (parts[0].toLowerCase() === 'md5') - parts = parts.slice(1); - parts = parts.join(''); - /*JSSTYLED*/ - var md5RE = /^[a-fA-F0-9]+$/; - if (!md5RE.test(parts)) - throw (new FingerprintFormatError(fp)); - try { - hash = new Buffer(parts, 'hex'); - } catch (e) { - throw (new FingerprintFormatError(fp)); - } - } - if (alg === undefined) - throw (new FingerprintFormatError(fp)); +Object.defineProperty(exports, "__esModule", { + value: true +}); - if (algs.hashAlgs[alg] === undefined) - throw (new InvalidAlgorithmError(alg)); +var _asyncToGenerator2; - if (enAlgs !== undefined) { - enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); }); - if (enAlgs.indexOf(alg) === -1) - throw (new InvalidAlgorithmError(alg)); - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - return (new Fingerprint({ - algorithm: alg, - hash: hash, - type: options.type || 'key' - })); -}; +var _path; -function addColons(s) { - /*JSSTYLED*/ - return (s.replace(/(.{2})(?=.)/g, '$1:')); +function _load_path() { + return _path = _interopRequireDefault(__webpack_require__(0)); } -function base64Strip(s) { - /*JSSTYLED*/ - return (s.replace(/=*$/, '')); -} +var _invariant; -function sshBase64Format(alg, h) { - return (alg.toUpperCase() + ':' + base64Strip(h)); +function _load_invariant() { + return _invariant = _interopRequireDefault(__webpack_require__(7)); } -Fingerprint.isFingerprint = function (obj, ver) { - return (utils.isCompatible(obj, Fingerprint, ver)); -}; +var _semver; -/* - * API versions for Fingerprint: - * [1,0] -- initial ver - * [1,1] -- first tagged ver - */ -Fingerprint.prototype._sshpkApiVersion = [1, 1]; +function _load_semver() { + return _semver = _interopRequireDefault(__webpack_require__(22)); +} -Fingerprint._oldVersionDetect = function (obj) { - assert.func(obj.toString); - assert.func(obj.matches); - return ([1, 0]); -}; +var _validate; +function _load_validate() { + return _validate = __webpack_require__(98); +} -/***/ }), -/* 74 */ -/***/ (function(module, exports, __webpack_require__) { +var _lockfile; -// Copyright 2015 Joyent, Inc. +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} -module.exports = { - read: read, - readPkcs8: readPkcs8, - write: write, - writePkcs8: writePkcs8, +var _packageReference; - readECDSACurve: readECDSACurve, - writeECDSACurve: writeECDSACurve -}; +function _load_packageReference() { + return _packageReference = _interopRequireDefault(__webpack_require__(417)); +} -var assert = __webpack_require__(9); -var asn1 = __webpack_require__(34); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var pem = __webpack_require__(41); +var _index; -function read(buf, options) { - return (pem.read(buf, options, 'pkcs8')); +function _load_index() { + return _index = __webpack_require__(35); } -function write(key, options) { - return (pem.write(key, options, 'pkcs8')); -} +var _errors; -/* Helper to read in a single mpint */ -function readMPInt(der, nm) { - assert.strictEqual(der.peek(), asn1.Ber.Integer, - nm + ' is not an Integer'); - return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); +function _load_errors() { + return _errors = __webpack_require__(3); } -function readPkcs8(alg, type, der) { - /* Private keys in pkcs#8 format have a weird extra int */ - if (der.peek() === asn1.Ber.Integer) { - assert.strictEqual(type, 'private', - 'unexpected Integer at start of public key'); - der.readString(asn1.Ber.Integer, true); - } - - der.readSequence(); - var next = der.offset + der.length; +var _constants; - var oid = der.readOID(); - switch (oid) { - case '1.2.840.113549.1.1.1': - der._offset = next; - if (type === 'public') - return (readPkcs8RSAPublic(der)); - else - return (readPkcs8RSAPrivate(der)); - case '1.2.840.10040.4.1': - if (type === 'public') - return (readPkcs8DSAPublic(der)); - else - return (readPkcs8DSAPrivate(der)); - case '1.2.840.10045.2.1': - if (type === 'public') - return (readPkcs8ECDSAPublic(der)); - else - return (readPkcs8ECDSAPrivate(der)); - default: - throw (new Error('Unknown key type OID ' + oid)); - } +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); } -function readPkcs8RSAPublic(der) { - // bit string sequence - der.readSequence(asn1.Ber.BitString); - der.readByte(); - der.readSequence(); +var _version; - // modulus - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'exponent'); +function _load_version() { + return _version = _interopRequireWildcard(__webpack_require__(170)); +} - // now, make the key - var key = { - type: 'rsa', - source: der.originalInput, - parts: [ - { name: 'e', data: e }, - { name: 'n', data: n } - ] - }; +var _workspaceResolver; - return (new Key(key)); +function _load_workspaceResolver() { + return _workspaceResolver = _interopRequireDefault(__webpack_require__(428)); } -function readPkcs8RSAPrivate(der) { - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - - var ver = readMPInt(der, 'version'); - assert.equal(ver[0], 0x0, 'unknown RSA private key version'); +var _fs; - // modulus then public exponent - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'public exponent'); - var d = readMPInt(der, 'private exponent'); - var p = readMPInt(der, 'prime1'); - var q = readMPInt(der, 'prime2'); - var dmodp = readMPInt(der, 'exponent1'); - var dmodq = readMPInt(der, 'exponent2'); - var iqmp = readMPInt(der, 'iqmp'); +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - // now, make the key - var key = { - type: 'rsa', - parts: [ - { name: 'n', data: n }, - { name: 'e', data: e }, - { name: 'd', data: d }, - { name: 'iqmp', data: iqmp }, - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'dmodp', data: dmodp }, - { name: 'dmodq', data: dmodq } - ] - }; +var _normalizePattern4; - return (new PrivateKey(key)); +function _load_normalizePattern() { + return _normalizePattern4 = __webpack_require__(30); } -function readPkcs8DSAPublic(der) { - der.readSequence(); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // bit string sequence - der.readSequence(asn1.Ber.BitString); - der.readByte(); +class PackageRequest { + constructor(req, resolver) { + this.parentRequest = req.parentRequest; + this.parentNames = []; + this.lockfile = resolver.lockfile; + this.registry = req.registry; + this.reporter = resolver.reporter; + this.resolver = resolver; + this.optional = req.optional; + this.pattern = req.pattern; + this.config = resolver.config; + this.foundInfo = null; - var y = readMPInt(der, 'y'); + resolver.usedRegistries.add(req.registry); + } - // now, make the key - var key = { - type: 'dsa', - parts: [ - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g }, - { name: 'y', data: y } - ] - }; - - return (new Key(key)); -} + getLocked(remoteType) { + // always prioritise root lockfile + const shrunk = this.lockfile.getLocked(this.pattern); -function readPkcs8DSAPrivate(der) { - der.readSequence(); + if (shrunk && shrunk.resolved) { + const resolvedParts = (_version || _load_version()).explodeHashedUrl(shrunk.resolved); + // If it's a private git url set remote to 'git'. + const preferredRemoteType = resolvedParts.url.startsWith('git+ssh://') ? 'git' : remoteType; - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); + return { + name: shrunk.name, + version: shrunk.version, + _uid: shrunk.uid, + _remote: { + resolved: shrunk.resolved, + type: preferredRemoteType, + reference: resolvedParts.url, + hash: resolvedParts.hash, + registry: shrunk.registry + }, + optionalDependencies: shrunk.optionalDependencies, + dependencies: shrunk.dependencies + }; + } else { + return null; + } + } - der.readSequence(asn1.Ber.OctetString); - var x = readMPInt(der, 'x'); + /** + * If the input pattern matches a registry one then attempt to find it on the registry. + * Otherwise fork off to an exotic resolver if one matches. + */ - /* The pkcs#8 format does not include the public key */ - var y = utils.calculateDSAPublic(g, p, x); + findVersionOnRegistry(pattern) { + var _this = this; - var key = { - type: 'dsa', - parts: [ - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g }, - { name: 'y', data: y }, - { name: 'x', data: x } - ] - }; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref = yield _this.normalize(pattern); - return (new PrivateKey(key)); -} + const range = _ref.range, + name = _ref.name; -function readECDSACurve(der) { - var curveName, curveNames; - var j, c, cd; - if (der.peek() === asn1.Ber.OID) { - var oid = der.readOID(); + const exoticResolver = (0, (_index || _load_index()).getExoticResolver)(range); + if (exoticResolver) { + let data = yield _this.findExoticVersionInfo(exoticResolver, range); - curveNames = Object.keys(algs.curves); - for (j = 0; j < curveNames.length; ++j) { - c = curveNames[j]; - cd = algs.curves[c]; - if (cd.pkcs8oid === oid) { - curveName = c; - break; - } - } + // clone data as we're manipulating it in place and this could be resolved multiple + // times + data = Object.assign({}, data); - } else { - // ECParameters sequence - der.readSequence(); - var version = der.readString(asn1.Ber.Integer, true); - assert.strictEqual(version[0], 1, 'ECDSA key not version 1'); + // this is so the returned package response uses the overridden name. ie. if the + // package's actual name is `bar`, but it's been specified in the manifest like: + // "foo": "http://foo.com/bar.tar.gz" + // then we use the foo name + data.name = name; + return data; + } - var curve = {}; + const Resolver = _this.getRegistryResolver(); + const resolver = new Resolver(_this, name, range); + return resolver.resolve(); + })(); + } - // FieldID sequence - der.readSequence(); - var fieldTypeOid = der.readOID(); - assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1', - 'ECDSA key is not from a prime-field'); - var p = curve.p = utils.mpNormalize( - der.readString(asn1.Ber.Integer, true)); - /* - * p always starts with a 1 bit, so count the zeros to get its - * real size. - */ - curve.size = p.length * 8 - utils.countZeros(p); + /** + * Get the registry resolver associated with this package request. + */ - // Curve sequence - der.readSequence(); - curve.a = utils.mpNormalize( - der.readString(asn1.Ber.OctetString, true)); - curve.b = utils.mpNormalize( - der.readString(asn1.Ber.OctetString, true)); - if (der.peek() === asn1.Ber.BitString) - curve.s = der.readString(asn1.Ber.BitString, true); + getRegistryResolver() { + const Resolver = (_index || _load_index()).registries[this.registry]; + if (Resolver) { + return Resolver; + } else { + throw new (_errors || _load_errors()).MessageError(this.reporter.lang('unknownRegistryResolver', this.registry)); + } + } - // Combined Gx and Gy - curve.G = der.readString(asn1.Ber.OctetString, true); - assert.strictEqual(curve.G[0], 0x4, - 'uncompressed G is required'); + normalizeRange(pattern) { + var _this2 = this; - curve.n = utils.mpNormalize( - der.readString(asn1.Ber.Integer, true)); - curve.h = utils.mpNormalize( - der.readString(asn1.Ber.Integer, true)); - assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' + - 'required'); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (pattern.indexOf(':') > -1 || pattern.indexOf('@') > -1 || (0, (_index || _load_index()).getExoticResolver)(pattern)) { + return pattern; + } - curveNames = Object.keys(algs.curves); - var ks = Object.keys(curve); - for (j = 0; j < curveNames.length; ++j) { - c = curveNames[j]; - cd = algs.curves[c]; - var equal = true; - for (var i = 0; i < ks.length; ++i) { - var k = ks[i]; - if (cd[k] === undefined) - continue; - if (typeof (cd[k]) === 'object' && - cd[k].equals !== undefined) { - if (!cd[k].equals(curve[k])) { - equal = false; - break; - } - } else if (Buffer.isBuffer(cd[k])) { - if (cd[k].toString('binary') - !== curve[k].toString('binary')) { - equal = false; - break; - } - } else { - if (cd[k] !== curve[k]) { - equal = false; - break; - } - } - } - if (equal) { - curveName = c; - break; - } - } - } - return (curveName); -} + if (!(_semver || _load_semver()).default.validRange(pattern)) { + try { + if (yield (_fs || _load_fs()).exists((_path || _load_path()).default.join(_this2.config.cwd, pattern, (_constants || _load_constants()).NODE_PACKAGE_JSON))) { + _this2.reporter.warn(_this2.reporter.lang('implicitFileDeprecated', pattern)); + return `file:${pattern}`; + } + } catch (err) { + // pass + } + } -function readPkcs8ECDSAPrivate(der) { - var curveName = readECDSACurve(der); - assert.string(curveName, 'a known elliptic curve'); + return pattern; + })(); + } - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); + normalize(pattern) { + var _this3 = this; - var version = readMPInt(der, 'version'); - assert.equal(version[0], 1, 'unknown version of ECDSA key'); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _normalizePattern = (0, (_normalizePattern4 || _load_normalizePattern()).normalizePattern)(pattern); - var d = der.readString(asn1.Ber.OctetString, true); - der.readSequence(0xa1); + const name = _normalizePattern.name, + range = _normalizePattern.range, + hasVersion = _normalizePattern.hasVersion; - var Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); + const newRange = yield _this3.normalizeRange(range); + return { name, range: newRange, hasVersion }; + })(); + } - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: new Buffer(curveName) }, - { name: 'Q', data: Q }, - { name: 'd', data: d } - ] - }; + /** + * Construct an exotic resolver instance with the input `ExoticResolver` and `range`. + */ - return (new PrivateKey(key)); -} + findExoticVersionInfo(ExoticResolver, range) { + const resolver = new ExoticResolver(this, range); + return resolver.resolve(); + } -function readPkcs8ECDSAPublic(der) { - var curveName = readECDSACurve(der); - assert.string(curveName, 'a known elliptic curve'); + /** + * If the current pattern matches an exotic resolver then delegate to it or else try + * the registry. + */ - var Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); + findVersionInfo() { + const exoticResolver = (0, (_index || _load_index()).getExoticResolver)(this.pattern); + if (exoticResolver) { + return this.findExoticVersionInfo(exoticResolver, this.pattern); + } else if ((_workspaceResolver || _load_workspaceResolver()).default.isWorkspace(this.pattern, this.resolver.workspaceLayout)) { + (0, (_invariant || _load_invariant()).default)(this.resolver.workspaceLayout, 'expected workspaceLayout'); + const resolver = new (_workspaceResolver || _load_workspaceResolver()).default(this, this.pattern, this.resolver.workspaceLayout); + return resolver.resolve(); + } else { + return this.findVersionOnRegistry(this.pattern); + } + } - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: new Buffer(curveName) }, - { name: 'Q', data: Q } - ] - }; + reportResolvedRangeMatch(info, resolved) {} - return (new Key(key)); -} + /** + * Do the final resolve of a package that had a match with an existing version. + * After all unique versions have been discovered, so the best available version + * is found. + */ + resolveToExistingVersion(info) { + // get final resolved version + var _normalizePattern2 = (0, (_normalizePattern4 || _load_normalizePattern()).normalizePattern)(this.pattern); -function writePkcs8(der, key) { - der.startSequence(); + const range = _normalizePattern2.range, + name = _normalizePattern2.name; - if (PrivateKey.isPrivateKey(key)) { - var sillyInt = new Buffer(1); - sillyInt[0] = 0x0; - der.writeBuffer(sillyInt, asn1.Ber.Integer); - } + const solvedRange = (_semver || _load_semver()).default.validRange(range) ? info.version : range; + const resolved = this.resolver.getHighestRangeVersionMatch(name, solvedRange, info); + (0, (_invariant || _load_invariant()).default)(resolved, 'should have a resolved reference'); - der.startSequence(); - switch (key.type) { - case 'rsa': - der.writeOID('1.2.840.113549.1.1.1'); - if (PrivateKey.isPrivateKey(key)) - writePkcs8RSAPrivate(key, der); - else - writePkcs8RSAPublic(key, der); - break; - case 'dsa': - der.writeOID('1.2.840.10040.4.1'); - if (PrivateKey.isPrivateKey(key)) - writePkcs8DSAPrivate(key, der); - else - writePkcs8DSAPublic(key, der); - break; - case 'ecdsa': - der.writeOID('1.2.840.10045.2.1'); - if (PrivateKey.isPrivateKey(key)) - writePkcs8ECDSAPrivate(key, der); - else - writePkcs8ECDSAPublic(key, der); - break; - default: - throw (new Error('Unsupported key type: ' + key.type)); - } + this.reportResolvedRangeMatch(info, resolved); + const ref = resolved._reference; + (0, (_invariant || _load_invariant()).default)(ref, 'Resolved package info has no package reference'); + ref.addRequest(this); + ref.addPattern(this.pattern, resolved); + } - der.endSequence(); -} + /** + * TODO description + */ + find(_ref2) { + var _this4 = this; -function writePkcs8RSAPrivate(key, der) { - der.writeNull(); - der.endSequence(); + let fresh = _ref2.fresh, + frozen = _ref2.frozen; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // find version info for this package pattern + const info = yield _this4.findVersionInfo(); - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); + info.fresh = fresh; + (0, (_validate || _load_validate()).cleanDependencies)(info, false, _this4.reporter, function () { + // swallow warnings + }); - var version = new Buffer(1); - version[0] = 0; - der.writeBuffer(version, asn1.Ber.Integer); + // check if while we were resolving this dep we've already resolved one that satisfies + // the same range - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); - der.writeBuffer(key.part.d.data, asn1.Ber.Integer); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - if (!key.part.dmodp || !key.part.dmodq) - utils.addRSAMissing(key); - der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); - der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); - der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); + var _normalizePattern3 = (0, (_normalizePattern4 || _load_normalizePattern()).normalizePattern)(_this4.pattern); - der.endSequence(); - der.endSequence(); -} + const range = _normalizePattern3.range, + name = _normalizePattern3.name; -function writePkcs8RSAPublic(key, der) { - der.writeNull(); - der.endSequence(); + const solvedRange = (_semver || _load_semver()).default.validRange(range) ? info.version : range; + const resolved = !info.fresh || frozen ? _this4.resolver.getExactVersionMatch(name, solvedRange, info) : _this4.resolver.getHighestRangeVersionMatch(name, solvedRange, info); - der.startSequence(asn1.Ber.BitString); - der.writeByte(0x00); + if (resolved) { + _this4.resolver.reportPackageWithExistingVersion(_this4, info); + return; + } - der.startSequence(); - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); - der.endSequence(); + if (info.flat && !_this4.resolver.flat) { + throw new (_errors || _load_errors()).MessageError(_this4.reporter.lang('flatGlobalError')); + } - der.endSequence(); -} + // validate version info + PackageRequest.validateVersionInfo(info, _this4.reporter); -function writePkcs8DSAPrivate(key, der) { - der.startSequence(); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); - der.endSequence(); + // + const remote = info._remote; + (0, (_invariant || _load_invariant()).default)(remote, 'Missing remote'); - der.endSequence(); + // set package reference + const ref = new (_packageReference || _load_packageReference()).default(_this4, info, remote); + ref.addPattern(_this4.pattern, info); + ref.addOptional(_this4.optional); + ref.setFresh(fresh); + info._reference = ref; + info._remote = remote; + // start installation of dependencies + const promises = []; + const deps = []; + const parentNames = [..._this4.parentNames, name]; + // normal deps + for (const depName in info.dependencies) { + const depPattern = depName + '@' + info.dependencies[depName]; + deps.push(depPattern); + promises.push(_this4.resolver.find({ + pattern: depPattern, + registry: remote.registry, + // dependencies of optional dependencies should themselves be optional + optional: _this4.optional, + parentRequest: _this4, + parentNames + })); + } - der.startSequence(asn1.Ber.OctetString); - der.writeBuffer(key.part.x.data, asn1.Ber.Integer); - der.endSequence(); -} + // optional deps + for (const depName in info.optionalDependencies) { + const depPattern = depName + '@' + info.optionalDependencies[depName]; + deps.push(depPattern); + promises.push(_this4.resolver.find({ + pattern: depPattern, + registry: remote.registry, + optional: true, + parentRequest: _this4, + parentNames + })); + } + if (remote.type === 'workspace' && !_this4.config.production) { + // workspaces support dev dependencies + for (const depName in info.devDependencies) { + const depPattern = depName + '@' + info.devDependencies[depName]; + deps.push(depPattern); + promises.push(_this4.resolver.find({ + pattern: depPattern, + registry: remote.registry, + optional: false, + parentRequest: _this4, + parentNames + })); + } + } -function writePkcs8DSAPublic(key, der) { - der.startSequence(); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); - der.endSequence(); - der.endSequence(); + for (const promise of promises) { + yield promise; + } - der.startSequence(asn1.Ber.BitString); - der.writeByte(0x00); - der.writeBuffer(key.part.y.data, asn1.Ber.Integer); - der.endSequence(); -} + ref.addDependencies(deps); -function writeECDSACurve(key, der) { - var curve = algs.curves[key.curve]; - if (curve.pkcs8oid) { - /* This one has a name in pkcs#8, so just write the oid */ - der.writeOID(curve.pkcs8oid); + // Now that we have all dependencies, it's safe to propagate optional + for (const otherRequest of ref.requests.slice(1)) { + ref.addOptional(otherRequest.optional); + } + })(); + } - } else { - // ECParameters sequence - der.startSequence(); + /** + * TODO description + */ - var version = new Buffer(1); - version.writeUInt8(1, 0); - der.writeBuffer(version, asn1.Ber.Integer); + static validateVersionInfo(info, reporter) { + // human readable name to use in errors + const human = `${info.name}@${info.version}`; - // FieldID sequence - der.startSequence(); - der.writeOID('1.2.840.10045.1.1'); // prime-field - der.writeBuffer(curve.p, asn1.Ber.Integer); - der.endSequence(); + info.version = PackageRequest.getPackageVersion(info); - // Curve sequence - der.startSequence(); - var a = curve.p; - if (a[0] === 0x0) - a = a.slice(1); - der.writeBuffer(a, asn1.Ber.OctetString); - der.writeBuffer(curve.b, asn1.Ber.OctetString); - der.writeBuffer(curve.s, asn1.Ber.BitString); - der.endSequence(); + for (const key of (_constants || _load_constants()).REQUIRED_PACKAGE_KEYS) { + if (!info[key]) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('missingRequiredPackageKey', human, key)); + } + } + } - der.writeBuffer(curve.G, asn1.Ber.OctetString); - der.writeBuffer(curve.n, asn1.Ber.Integer); - var h = curve.h; - if (!h) { - h = new Buffer(1); - h[0] = 1; - } - der.writeBuffer(h, asn1.Ber.Integer); + /** + * Returns the package version if present, else defaults to the uid + */ - // ECParameters - der.endSequence(); - } -} + static getPackageVersion(info) { + // TODO possibly reconsider this behaviour + return info.version === undefined ? info._uid : info.version; + } -function writePkcs8ECDSAPublic(key, der) { - writeECDSACurve(key, der); - der.endSequence(); + /** + * Gets all of the outdated packages and sorts them appropriately + */ - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); -} + static getOutdatedPackages(lockfile, install, config, reporter, filterByPatterns) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref3 = yield install.fetchRequestFromCwd(); -function writePkcs8ECDSAPrivate(key, der) { - writeECDSACurve(key, der); - der.endSequence(); + const reqPatterns = _ref3.requests, + workspaceLayout = _ref3.workspaceLayout; - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); + // Filter out workspace patterns if necessary - var version = new Buffer(1); - version[0] = 1; - der.writeBuffer(version, asn1.Ber.Integer); + let depReqPatterns = workspaceLayout ? reqPatterns.filter(function (p) { + return !workspaceLayout.getManifestByPattern(p.pattern); + }) : reqPatterns; - der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); + // filter the list down to just the packages requested. + // prevents us from having to query the metadata for all packages. + if (filterByPatterns && filterByPatterns.length) { + const filterByNames = filterByPatterns.map(function (pattern) { + return (0, (_normalizePattern4 || _load_normalizePattern()).normalizePattern)(pattern).name; + }); + depReqPatterns = depReqPatterns.filter(function (dep) { + return filterByNames.indexOf((0, (_normalizePattern4 || _load_normalizePattern()).normalizePattern)(dep.pattern).name) >= 0; + }); + } - der.startSequence(0xa1); - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); - der.endSequence(); + const deps = yield Promise.all(depReqPatterns.map((() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref5) { + let pattern = _ref5.pattern, + hint = _ref5.hint; - der.endSequence(); - der.endSequence(); -} - - -/***/ }), -/* 75 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright 2017 Joyent, Inc. - -module.exports = Identity; - -var assert = __webpack_require__(9); -var algs = __webpack_require__(16); -var crypto = __webpack_require__(7); -var Fingerprint = __webpack_require__(73); -var Signature = __webpack_require__(33); -var errs = __webpack_require__(32); -var util = __webpack_require__(2); -var utils = __webpack_require__(13); -var asn1 = __webpack_require__(34); - -/*JSSTYLED*/ -var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i; - -var oids = {}; -oids.cn = '2.5.4.3'; -oids.o = '2.5.4.10'; -oids.ou = '2.5.4.11'; -oids.l = '2.5.4.7'; -oids.s = '2.5.4.8'; -oids.c = '2.5.4.6'; -oids.sn = '2.5.4.4'; -oids.dc = '0.9.2342.19200300.100.1.25'; -oids.uid = '0.9.2342.19200300.100.1.1'; -oids.mail = '0.9.2342.19200300.100.1.3'; - -var unoids = {}; -Object.keys(oids).forEach(function (k) { - unoids[oids[k]] = k; -}); - -function Identity(opts) { - var self = this; - assert.object(opts, 'options'); - assert.arrayOfObject(opts.components, 'options.components'); - this.components = opts.components; - this.componentLookup = {}; - this.components.forEach(function (c) { - if (c.name && !c.oid) - c.oid = oids[c.name]; - if (c.oid && !c.name) - c.name = unoids[c.oid]; - if (self.componentLookup[c.name] === undefined) - self.componentLookup[c.name] = []; - self.componentLookup[c.name].push(c); - }); - if (this.componentLookup.cn && this.componentLookup.cn.length > 0) { - this.cn = this.componentLookup.cn[0].value; - } - assert.optionalString(opts.type, 'options.type'); - if (opts.type === undefined) { - if (this.components.length === 1 && - this.componentLookup.cn && - this.componentLookup.cn.length === 1 && - this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { - this.type = 'host'; - this.hostname = this.componentLookup.cn[0].value; - - } else if (this.componentLookup.dc && - this.components.length === this.componentLookup.dc.length) { - this.type = 'host'; - this.hostname = this.componentLookup.dc.map( - function (c) { - return (c.value); - }).join('.'); + const locked = lockfile.getLocked(pattern); + if (!locked) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('lockfileOutdated')); + } - } else if (this.componentLookup.uid && - this.components.length === - this.componentLookup.uid.length) { - this.type = 'user'; - this.uid = this.componentLookup.uid[0].value; + const name = locked.name, + current = locked.version; - } else if (this.componentLookup.cn && - this.componentLookup.cn.length === 1 && - this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { - this.type = 'host'; - this.hostname = this.componentLookup.cn[0].value; + let latest = ''; + let wanted = ''; + let url = ''; - } else if (this.componentLookup.uid && - this.componentLookup.uid.length === 1) { - this.type = 'user'; - this.uid = this.componentLookup.uid[0].value; + const normalized = (0, (_normalizePattern4 || _load_normalizePattern()).normalizePattern)(pattern); - } else if (this.componentLookup.mail && - this.componentLookup.mail.length === 1) { - this.type = 'email'; - this.email = this.componentLookup.mail[0].value; + if ((0, (_index || _load_index()).getExoticResolver)(pattern) || (0, (_index || _load_index()).getExoticResolver)(normalized.range)) { + latest = wanted = 'exotic'; + url = normalized.range; + } else { + const registry = config.registries[locked.registry]; - } else if (this.componentLookup.cn && - this.componentLookup.cn.length === 1) { - this.type = 'user'; - this.uid = this.componentLookup.cn[0].value; + var _ref6 = yield registry.checkOutdated(config, name, normalized.range); - } else { - this.type = 'unknown'; - } - } else { - this.type = opts.type; - if (this.type === 'host') - this.hostname = opts.hostname; - else if (this.type === 'user') - this.uid = opts.uid; - else if (this.type === 'email') - this.email = opts.email; - else - throw (new Error('Unknown type ' + this.type)); - } -} + latest = _ref6.latest; + wanted = _ref6.wanted; + url = _ref6.url; + } -Identity.prototype.toString = function () { - return (this.components.map(function (c) { - return (c.name.toUpperCase() + '=' + c.value); - }).join(', ')); -}; + return { name, current, wanted, latest, url, hint, range: normalized.range, upgradeTo: '' }; + }); -/* - * These are from X.680 -- PrintableString allowed chars are in section 37.4 - * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to - * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006 - * (the basic ASCII character set). - */ -/* JSSTYLED */ -var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/; -/* JSSTYLED */ -var NOT_IA5 = /[^\x00-\x7f]/; + return function (_x) { + return _ref4.apply(this, arguments); + }; + })())); -Identity.prototype.toAsn1 = function (der, tag) { - der.startSequence(tag); - this.components.forEach(function (c) { - der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set); - der.startSequence(); - der.writeOID(c.oid); - /* - * If we fit in a PrintableString, use that. Otherwise use an - * IA5String or UTF8String. - */ - if (c.value.match(NOT_IA5)) { - var v = new Buffer(c.value, 'utf8'); - der.writeBuffer(v, asn1.Ber.Utf8String); - } else if (c.value.match(NOT_PRINTABLE)) { - der.writeString(c.value, asn1.Ber.IA5String); - } else { - der.writeString(c.value, asn1.Ber.PrintableString); - } - der.endSequence(); - der.endSequence(); - }); - der.endSequence(); -}; + // Make sure to always output `exotic` versions to be compatible with npm + const isDepOld = function (_ref7) { + let current = _ref7.current, + latest = _ref7.latest, + wanted = _ref7.wanted; + return latest === 'exotic' || latest !== 'exotic' && ((_semver || _load_semver()).default.lt(current, wanted) || (_semver || _load_semver()).default.lt(current, latest)); + }; + const orderByName = function (depA, depB) { + return depA.name.localeCompare(depB.name); + }; -function globMatch(a, b) { - if (a === '**' || b === '**') - return (true); - var aParts = a.split('.'); - var bParts = b.split('.'); - if (aParts.length !== bParts.length) - return (false); - for (var i = 0; i < aParts.length; ++i) { - if (aParts[i] === '*' || bParts[i] === '*') - continue; - if (aParts[i] !== bParts[i]) - return (false); - } - return (true); + return deps.filter(isDepOld).sort(orderByName); + })(); + } } +exports.default = PackageRequest; -Identity.prototype.equals = function (other) { - if (!Identity.isIdentity(other, [1, 0])) - return (false); - if (other.components.length !== this.components.length) - return (false); - for (var i = 0; i < this.components.length; ++i) { - if (this.components[i].oid !== other.components[i].oid) - return (false); - if (!globMatch(this.components[i].value, - other.components[i].value)) { - return (false); - } - } - return (true); -}; - -Identity.forHost = function (hostname) { - assert.string(hostname, 'hostname'); - return (new Identity({ - type: 'host', - hostname: hostname, - components: [ { name: 'cn', value: hostname } ] - })); -}; - -Identity.forUser = function (uid) { - assert.string(uid, 'uid'); - return (new Identity({ - type: 'user', - uid: uid, - components: [ { name: 'uid', value: uid } ] - })); -}; - -Identity.forEmail = function (email) { - assert.string(email, 'email'); - return (new Identity({ - type: 'email', - email: email, - components: [ { name: 'mail', value: email } ] - })); -}; - -Identity.parseDN = function (dn) { - assert.string(dn, 'dn'); - var parts = dn.split(','); - var cmps = parts.map(function (c) { - c = c.trim(); - var eqPos = c.indexOf('='); - var name = c.slice(0, eqPos).toLowerCase(); - var value = c.slice(eqPos + 1); - return ({ name: name, value: value }); - }); - return (new Identity({ components: cmps })); -}; - -Identity.parseAsn1 = function (der, top) { - var components = []; - der.readSequence(top); - var end = der.offset + der.length; - while (der.offset < end) { - der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set); - var after = der.offset + der.length; - der.readSequence(); - var oid = der.readOID(); - var type = der.peek(); - var value; - switch (type) { - case asn1.Ber.PrintableString: - case asn1.Ber.IA5String: - case asn1.Ber.OctetString: - case asn1.Ber.T61String: - value = der.readString(type); - break; - case asn1.Ber.Utf8String: - value = der.readString(type, true); - value = value.toString('utf8'); - break; - case asn1.Ber.CharacterString: - case asn1.Ber.BMPString: - value = der.readString(type, true); - value = value.toString('utf16le'); - break; - default: - throw (new Error('Unknown asn1 type ' + type)); - } - components.push({ oid: oid, value: value }); - der._offset = after; - } - der._offset = end; - return (new Identity({ - components: components - })); -}; - -Identity.isIdentity = function (obj, ver) { - return (utils.isCompatible(obj, Identity, ver)); -}; - -/* - * API versions for Identity: - * [1,0] -- initial ver - */ -Identity.prototype._sshpkApiVersion = [1, 0]; +/***/ }), +/* 95 */ +/***/ (function(module, exports, __webpack_require__) { -Identity._oldVersionDetect = function (obj) { - return ([1, 0]); -}; +"use strict"; -/***/ }), -/* 76 */ -/***/ (function(module, exports) { +Object.defineProperty(exports, "__esModule", { + value: true +}); +class BaseResolver { + constructor(request, fragment) { + this.resolver = request.resolver; + this.reporter = request.reporter; + this.fragment = fragment; + this.registry = request.registry; + this.request = request; + this.pattern = request.pattern; + this.config = request.config; + } -module.exports = require("buffer"); + fork(Resolver, resolveArg) { + for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + args[_key - 2] = arguments[_key]; + } -/***/ }), -/* 77 */ -/***/ (function(module, exports) { + const resolver = new Resolver(this.request, ...args); + resolver.registry = this.registry; + return resolver.resolve(resolveArg); + } -module.exports = require("net"); + resolve(resolveArg) { + throw new Error('Not implemented'); + } +} +exports.default = BaseResolver; /***/ }), -/* 78 */ +/* 96 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -36362,254 +37387,222 @@ module.exports = require("net"); Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = exports.Add = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -let run = exports.run = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (!args.length) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('missingAddDependencies')); - } - - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.lockfileFolder, reporter); +var _index; - yield (0, (_install || _load_install()).wrapLifecycle)(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const install = new Add(args, flags, config, reporter, lockfile); - yield install.init(); - })); - }); +function _load_index() { + return _index = __webpack_require__(35); +} - return function run(_x, _x2, _x3, _x4) { - return _ref2.apply(this, arguments); - }; -})(); +var _misc; -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; +function _load_misc() { + return _misc = _interopRequireWildcard(__webpack_require__(10)); +} -var _wrapper; +var _version; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); +function _load_version() { + return _version = _interopRequireWildcard(__webpack_require__(170)); } -var _packageRequest; +var _guessName; -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); +function _load_guessName() { + return _guessName = _interopRequireDefault(__webpack_require__(166)); } -var _list; +var _index2; -function _load_list() { - return _list = __webpack_require__(192); +function _load_index2() { + return _index2 = __webpack_require__(34); } -var _install; +var _exoticResolver; -function _load_install() { - return _install = __webpack_require__(23); +function _load_exoticResolver() { + return _exoticResolver = _interopRequireDefault(__webpack_require__(61)); } -var _errors; +var _git; -function _load_errors() { - return _errors = __webpack_require__(3); +function _load_git() { + return _git = _interopRequireDefault(__webpack_require__(165)); } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const invariant = __webpack_require__(5); +const urlParse = __webpack_require__(14).parse; -class Add extends (_install || _load_install()).Install { - constructor(args, flags, config, reporter, lockfile) { - super(flags, config, reporter, lockfile); - this.args = args; - // only one flag is supported, so we can figure out which one was passed to `yarn add` - this.flagToOrigin = [flags.dev && 'devDependencies', flags.optional && 'optionalDependencies', flags.peer && 'peerDependencies', 'dependencies'].filter(Boolean).shift(); +const GIT_PROTOCOL_PATTERN = /git\+.+:/; + +// we purposefully omit https and http as those are only valid if they end in the .git extension +const GIT_PROTOCOLS = ['git:', 'ssh:']; + +const GIT_HOSTS = ['github.com', 'gitlab.com', 'bitbucket.com', 'bitbucket.org']; + +class GitResolver extends (_exoticResolver || _load_exoticResolver()).default { + constructor(request, fragment) { + super(request, fragment); + + var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment); + + const url = _versionUtil$explodeH.url, + hash = _versionUtil$explodeH.hash; + + this.url = url; + this.hash = hash; } - /** - * TODO - */ + static isVersion(pattern) { + const parts = urlParse(pattern); - prepareRequests(requests) { - const requestsWithArgs = requests.slice(); + // this pattern hasn't been exploded yet, we'll hit this code path again later once + // we've been normalized #59 + if (!parts.protocol) { + return false; + } - for (const pattern of this.args) { - requestsWithArgs.push({ - pattern, - registry: 'npm', - optional: false - }); + const pathname = parts.pathname; + if (pathname && pathname.endsWith('.git')) { + // ends in .git + return true; } - return requestsWithArgs; - } - /** - * returns version for a pattern based on Manifest - */ - getPatternVersion(pattern, pkg) { - var _flags = this.flags; - const exact = _flags.exact, - tilde = _flags.tilde; + if (GIT_PROTOCOL_PATTERN.test(parts.protocol)) { + return true; + } - const parts = (_packageRequest || _load_packageRequest()).default.normalizePattern(pattern); - let version; - if ((_packageRequest || _load_packageRequest()).default.getExoticResolver(pattern)) { - // wasn't a name/range tuple so this is just a raw exotic pattern - version = pattern; - } else if (parts.hasVersion && parts.range) { - // if the user specified a range then use it verbatim - version = parts.range === 'latest' ? `^${pkg.version}` : parts.range; - } else if (tilde) { - // --save-tilde - version = `~${pkg.version}`; - } else if (exact) { - // --save-exact - version = pkg.version; - } else { - // default to save prefix - version = `${String(this.config.getOption('save-prefix') || '')}${pkg.version}`; + if (GIT_PROTOCOLS.indexOf(parts.protocol) >= 0) { + return true; } - return version; - } - preparePatterns(patterns) { - const preparedPatterns = patterns.slice(); - for (const pattern of this.resolver.dedupePatterns(this.args)) { - const pkg = this.resolver.getResolvedPattern(pattern); - invariant(pkg, `missing package ${pattern}`); - const version = this.getPatternVersion(pattern, pkg); - const newPattern = `${pkg.name}@${version}`; - preparedPatterns.push(newPattern); - this.addedPatterns.push(newPattern); - if (newPattern === pattern) { - continue; + if (parts.hostname && parts.path) { + const path = parts.path; + if (GIT_HOSTS.indexOf(parts.hostname) >= 0) { + // only if dependency is pointing to a git repo, + // e.g. facebook/flow and not file in a git repo facebook/flow/archive/v1.0.0.tar.gz + return path.split('/').filter(p => !!p).length === 2; } - this.resolver.replacePattern(pattern, newPattern); } - return preparedPatterns; - } - bailout(patterns) { - return Promise.resolve(false); + return false; } - /** - * Description - */ - - init() { + resolve(forked) { var _this = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this.addedPatterns = []; - const patterns = yield (_install || _load_install()).Install.prototype.init.call(_this); - yield _this.maybeOutputSaveTree(patterns); - yield _this.savePackages(); - return patterns; - })(); - } - - /** - * Description - */ - - fetchRequestFromCwd() { - return (_install || _load_install()).Install.prototype.fetchRequestFromCwd.call(this, this.args); - } + let tryRegistry = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (registry) { + const filename = (_index2 || _load_index2()).registries[registry].filename; - /** - * Output a tree of any newly added dependencies. - */ + const file = yield client.getFile(filename); + if (!file) { + return null; + } - maybeOutputSaveTree(patterns) { - var _this2 = this; + const json = yield config.readJson(`${url}/${filename}`, function () { + return JSON.parse(file); + }); + json._uid = commit; + json._remote = { + resolved: `${url}#${commit}`, + type: 'git', + reference: url, + hash: commit, + registry + }; + return json; + }); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // don't limit the shown tree depth - const opts = { - reqDepth: 0 - }; + return function tryRegistry(_x) { + return _ref.apply(this, arguments); + }; + })(); - var _ref = yield (0, (_list || _load_list()).buildTree)(_this2.resolver, _this2.linker, patterns, opts, true, true); + const url = _this.url; - const trees = _ref.trees, - count = _ref.count; + // shortcut for hosted git. we will fallback to a GitResolver if the hosted git + // optimisations fail which the `forked` flag indicates so we don't get into an + // infinite loop - _this2.reporter.success(count === 1 ? _this2.reporter.lang('savedNewDependency') : _this2.reporter.lang('savedNewDependencies', count)); - _this2.reporter.tree('newDependencies', trees); - })(); - } + const parts = urlParse(url); + if (false) { + // check if this git url uses any of the hostnames defined in our hosted git resolvers + for (const name in (_index || _load_index()).hostedGit) { + const Resolver = (_index || _load_index()).hostedGit[name]; + if (Resolver.hostname !== parts.hostname) { + continue; + } - /** - * Save added packages to manifest if any of the --save flags were used. - */ + // we have a match! clean up the pathname of url artifacts + let pathname = parts.pathname; + pathname = (_misc || _load_misc()).removePrefix(pathname, '/'); // remove prefixed slash + pathname = (_misc || _load_misc()).removeSuffix(pathname, '.git'); // remove .git suffix if present - savePackages() { - var _this3 = this; + const url = `${pathname}${_this.hash ? '#' + decodeURIComponent(_this.hash) : ''}`; + return _this.fork(Resolver, false, url); + } + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // fill rootPatternsToOrigin without `excludePatterns` - yield (_install || _load_install()).Install.prototype.fetchRequestFromCwd.call(_this3); - const patternOrigins = Object.keys(_this3.rootPatternsToOrigin); + // get from lockfile + const shrunk = _this.request.getLocked('git'); + if (shrunk) { + return shrunk; + } - // get all the different registry manifests in this folder - const manifests = yield _this3.config.getRootManifests(); + const config = _this.config; - // add new patterns to their appropriate registry manifest - for (const pattern of _this3.addedPatterns) { - const pkg = _this3.resolver.getResolvedPattern(pattern); - invariant(pkg, `missing package ${pattern}`); - const version = _this3.getPatternVersion(pattern, pkg); - const ref = pkg._reference; - invariant(ref, 'expected package reference'); - // lookup the package to determine dependency type; used during `yarn upgrade` - const depType = patternOrigins.reduce(function (acc, prev) { - if (prev.indexOf(`${pkg.name}@`) === 0) { - return _this3.rootPatternsToOrigin[prev]; - } - return acc; - }, null); - // depType is calculated when `yarn upgrade` command is used - const target = depType || _this3.flagToOrigin; + const gitUrl = (_git || _load_git()).default.npmUrlToGitUrl(url); + const client = new (_git || _load_git()).default(config, gitUrl, _this.hash); + const commit = yield client.init(); - // add it to manifest - const object = manifests[ref.registry].object; + const file = yield tryRegistry(_this.registry); + if (file) { + return file; + } + for (const registry in (_index2 || _load_index2()).registries) { + if (registry === _this.registry) { + continue; + } - object[target] = object[target] || {}; - object[target][pkg.name] = version; + const file = yield tryRegistry(registry); + if (file) { + return file; + } } - yield _this3.config.saveRootManifests(manifests); + return { + // This is just the default, it can be overridden with key of dependencies + name: (0, (_guessName || _load_guessName()).default)(url), + version: '0.0.0', + _uid: commit, + _remote: { + resolved: `${url}#${commit}`, + type: 'git', + reference: url, + hash: commit, + registry: 'npm' + } + }; })(); } } - -exports.Add = Add; -function hasWrapper(commander) { - return true; -} - -function setFlags(commander) { - commander.usage('add [packages ...] [flags]'); - commander.option('-D, --dev', 'save package to your `devDependencies`'); - commander.option('-P, --peer', 'save package to your `peerDependencies`'); - commander.option('-O, --optional', 'save package to your `optionalDependencies`'); - commander.option('-E, --exact', 'install exact version'); - commander.option('-T, --tilde', 'install most recent release with the same minor version'); -} +exports.default = GitResolver; /***/ }), -/* 79 */ +/* 97 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -36618,134 +37611,268 @@ function setFlags(commander) { Object.defineProperty(exports, "__esModule", { value: true }); +exports.execCommand = exports.execFromManifest = exports.executeLifecycleScript = exports.makeEnv = undefined; -var _asyncToGenerator2; +var _slicedToArray2; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } -var _index; +var _extends2; -function _load_index() { - return _index = _interopRequireDefault(__webpack_require__(129)); +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); } -var _constants; +var _asyncToGenerator2; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _fs; +let makeEnv = exports.makeEnv = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, cwd, config) { + const env = (0, (_extends2 || _load_extends()).default)({ + NODE: process.execPath + }, process.env); -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + // Merge in the `env` object specified in .yarnrc + const customEnv = config.getOption('env'); + if (customEnv && typeof customEnv === 'object') { + Object.assign(env, customEnv); + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + env.npm_lifecycle_event = stage; + env.npm_node_execpath = env.NODE; + env.npm_execpath = env.npm_execpath || process.mainModule.filename; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // Set the env to production for npm compat if production mode. + // https://github.com/npm/npm/blob/30d75e738b9cb7a6a3f9b50e971adcbe63458ed3/lib/utils/lifecycle.js#L336 + if (config.production) { + env.NODE_ENV = 'production'; + } -const path = __webpack_require__(1); -/* eslint no-unused-vars: 0 */ + // Note: npm_config_argv environment variable contains output of nopt - command-line + // parser used by npm. Since we use other parser, we just roughly emulate it's output. (See: #684) + env.npm_config_argv = JSON.stringify({ + remain: [], + cooked: [config.commandName], + original: [config.commandName] + }); -class BaseFetcher { - constructor(dest, remote, config) { - this.reporter = config.reporter; - this.packageName = remote.packageName; - this.reference = remote.reference; - this.registry = remote.registry; - this.hash = remote.hash; - this.remote = remote; - this.config = config; - this.dest = dest; - } + const manifest = yield config.maybeReadManifest(cwd); + if (manifest) { + if (manifest.scripts && Object.prototype.hasOwnProperty.call(manifest.scripts, stage)) { + env.npm_lifecycle_script = manifest.scripts[stage]; + } - setupMirrorFromCache() { - // fetcher subclasses may use this to perform actions such as copying over a cached tarball to the offline - // mirror etc - return Promise.resolve(); - } + // add npm_package_* + const queue = [['', manifest]]; + while (queue.length) { + var _queue$pop = queue.pop(), + _queue$pop2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_queue$pop, 2); - _fetch() { - return Promise.reject(new Error('Not implemented')); - } + const key = _queue$pop2[0], + val = _queue$pop2[1]; - fetch(defaultManifest) { - var _this = this; + if (key[0] === '_') { + continue; + } - const dest = this.dest; + if (typeof val === 'object') { + for (const subKey in val) { + const completeKey = [key, subKey].filter(function (part) { + return !!part; + }).join('_'); + queue.push([completeKey, val[subKey]]); + } + } else if (IGNORE_MANIFEST_KEYS.indexOf(key) < 0) { + let cleanVal = String(val); + if (cleanVal.indexOf('\n') >= 0) { + cleanVal = JSON.stringify(cleanVal); + } - return (_fs || _load_fs()).lockQueue.push(dest, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield (_fs || _load_fs()).mkdirp(dest); + //replacing invalid chars with underscore + const cleanKey = key.replace(/[^a-zA-Z0-9_]/g, '_'); - // fetch package and get the hash + env[`npm_package_${cleanKey}`] = cleanVal; + } + } + } - var _ref2 = yield _this._fetch(); + // add npm_config_* + const keys = new Set([...Object.keys(config.registries.yarn.config), ...Object.keys(config.registries.npm.config)]); + for (const key of keys) { + if (key.match(/:_/) || IGNORE_CONFIG_KEYS.indexOf(key) >= 0) { + continue; + } - const hash = _ref2.hash; + let val = config.getOption(key); + if (!val) { + val = ''; + } else if (typeof val === 'number') { + val = '' + val; + } else if (typeof val !== 'string') { + val = JSON.stringify(val); + } - const pkg = yield (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // load the new normalized manifest - try { - return yield _this.config.readManifest(dest, _this.registry); - } catch (e) { - if (e.code === 'ENOENT' && defaultManifest) { - return (0, (_index || _load_index()).default)(defaultManifest, dest, _this.config, false); - } else { - throw e; - } - } - })(); + if (val.indexOf('\n') >= 0) { + val = JSON.stringify(val); + } - yield (_fs || _load_fs()).writeFile(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME), JSON.stringify({ - manifest: pkg, - artifacts: [], - remote: _this.remote, - registry: _this.registry, - hash - }, null, ' ')); + const cleanKey = key.replace(/^_+/, ''); + const envKey = `npm_config_${cleanKey}`.replace(/[^a-zA-Z0-9_]/g, '_'); + env[envKey] = val; + } - return { - hash, - dest, - package: pkg, - cached: false + // split up the path + const envPath = env[(_constants || _load_constants()).ENV_PATH_KEY]; + const pathParts = envPath ? envPath.split(path.delimiter) : []; + + // Include node-gyp version that was bundled with the current Node.js version, + // if available. + pathParts.unshift(path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'node-gyp-bin')); + pathParts.unshift(path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'node-gyp-bin')); + + // Add global bin folder if it is not present already, as some packages depend + // on a globally-installed version of node-gyp. + const globalBin = yield (0, (_global || _load_global()).getBinFolder)(config, {}); + if (pathParts.indexOf(globalBin) === -1) { + pathParts.unshift(globalBin); + } + + // add .bin folders to PATH + for (const registry of Object.keys((_index || _load_index()).registries)) { + const binFolder = path.join(config.registries[registry].folder, '.bin'); + pathParts.unshift(path.join(config.linkFolder, binFolder)); + pathParts.unshift(path.join(cwd, binFolder)); + } + + if (config.scriptsPrependNodePath) { + pathParts.unshift(path.join(path.dirname(process.execPath))); + } + + // join path back together + env[(_constants || _load_constants()).ENV_PATH_KEY] = pathParts.join(path.delimiter); + + return env; + }); + + return function makeEnv(_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; +})(); + +let executeLifecycleScript = exports.executeLifecycleScript = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cwd, cmd, spinner) { + // if we don't have a spinner then pipe everything to the terminal + const stdio = spinner ? undefined : 'inherit'; + + const env = yield makeEnv(stage, cwd, config); + + yield checkForGypIfNeeded(config, cmd, env[(_constants || _load_constants()).ENV_PATH_KEY].split(path.delimiter)); + + // get shell + if (process.platform === 'win32') { + // handle windows run scripts starting with a relative path + cmd = (0, (_fixCmdWinSlashes || _load_fixCmdWinSlashes()).fixCmdWinSlashes)(cmd); + } + + let updateProgress; + if (spinner) { + updateProgress = function (data) { + const dataStr = data.toString() // turn buffer into string + .trim(); // trim whitespace + + invariant(spinner && spinner.tick, 'We should have spinner and its ticker here'); + if (dataStr) { + spinner.tick(dataStr + // Only get the last line + .substr(dataStr.lastIndexOf('\n') + 1) + // change tabs to spaces as they can interfere with the console + .replace(/\t/g, ' ')); + } }; + } + const stdout = yield (_child || _load_child()).spawn(cmd, [], { shell: true, cwd, env, stdio }, updateProgress); + + return { cwd, command: cmd, stdout }; + }); + + return function executeLifecycleScript(_x4, _x5, _x6, _x7, _x8) { + return _ref2.apply(this, arguments); + }; +})(); + +let _checkForGyp = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, paths) { + const reporter = config.reporter; + + // Check every directory in the PATH + + const allChecks = yield Promise.all(paths.map(function (dir) { + return (0, (_fs || _load_fs()).exists)(path.join(dir, 'node-gyp')); })); - } -} -exports.default = BaseFetcher; + if (allChecks.some(Boolean)) { + // node-gyp is available somewhere + return; + } -/***/ }), -/* 80 */ -/***/ (function(module, exports, __webpack_require__) { + reporter.info(reporter.lang('packageRequiresNodeGyp')); -"use strict"; + try { + yield (0, (_global || _load_global()).run)(config, reporter, {}, ['add', 'node-gyp']); + } catch (e) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('nodeGypAutoInstallFailed', e.message)); + } + }); + return function _checkForGyp(_x9, _x10) { + return _ref3.apply(this, arguments); + }; +})(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Parser = undefined; -exports.tokenise = tokenise; +let execFromManifest = exports.execFromManifest = (() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, commandName, cwd) { + const pkg = yield config.maybeReadManifest(cwd); + if (!pkg || !pkg.scripts) { + return; + } -exports.default = function (str) { - let fileLoc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'lockfile'; + const cmd = pkg.scripts[commandName]; + if (cmd) { + yield execCommand(commandName, config, cmd, cwd); + } + }); - str = stripBOM(str); - const parser = new Parser(str, fileLoc); - parser.next(); - return parser.parse(); -}; + return function execFromManifest(_x11, _x12, _x13) { + return _ref4.apply(this, arguments); + }; +})(); -var _constants; +let execCommand = exports.execCommand = (() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (stage, config, cmd, cwd) { + const reporter = config.reporter; -function _load_constants() { - return _constants = __webpack_require__(8); -} + try { + reporter.command(cmd); + yield executeLifecycleScript(stage, config, cwd, cmd); + return Promise.resolve(); + } catch (err) { + if (err instanceof (_errors || _load_errors()).ProcessTermError) { + throw new (_errors || _load_errors()).MessageError(err.EXIT_SIGNAL ? reporter.lang('commandFailedWithSignal', err.EXIT_SIGNAL) : reporter.lang('commandFailedWithCode', err.EXIT_CODE)); + } else { + throw err; + } + } + }); + + return function execCommand(_x14, _x15, _x16, _x17) { + return _ref5.apply(this, arguments); + }; +})(); var _errors; @@ -36753,9590 +37880,9817 @@ function _load_errors() { return _errors = __webpack_require__(3); } -var _map; +var _constants; -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _child; -const invariant = __webpack_require__(5); -/* eslint quotes: 0 */ +function _load_child() { + return _child = _interopRequireWildcard(__webpack_require__(48)); +} -const stripBOM = __webpack_require__(268); +var _fs; -const VERSION_REGEX = /^yarn lockfile v(\d+)$/; +function _load_fs() { + return _fs = __webpack_require__(4); +} -const TOKEN_TYPES = { - boolean: 'BOOLEAN', - string: 'STRING', - identifier: 'IDENTIFIER', - eof: 'EOF', - colon: 'COLON', - newline: 'NEWLINE', - comment: 'COMMENT', - indent: 'INDENT', - invalid: 'INVALID', - number: 'NUMBER', - comma: 'COMMA' -}; +var _index; -const VALID_PROP_VALUE_TOKENS = [TOKEN_TYPES.boolean, TOKEN_TYPES.string, TOKEN_TYPES.number]; +function _load_index() { + return _index = __webpack_require__(35); +} -function isValidPropValueToken(token) { - return VALID_PROP_VALUE_TOKENS.indexOf(token.type) >= 0; +var _fixCmdWinSlashes; + +function _load_fixCmdWinSlashes() { + return _fixCmdWinSlashes = __webpack_require__(435); } -function* tokenise(input) { - let lastNewline = false; - let line = 1; - let col = 0; +var _global; - function buildToken(type, value) { - return { line, col, type, value }; - } +function _load_global() { + return _global = __webpack_require__(92); +} - while (input.length) { - let chop = 0; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (input[0] === '\n') { - chop++; - line++; - col = 0; - yield buildToken(TOKEN_TYPES.newline); - } else if (input[0] === '#') { - chop++; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - let val = ''; - while (input[chop] !== '\n') { - val += input[chop]; - chop++; - } - yield buildToken(TOKEN_TYPES.comment, val); - } else if (input[0] === ' ') { - if (lastNewline) { - let indent = ''; - for (let i = 0; input[i] === ' '; i++) { - indent += input[i]; - } +const invariant = __webpack_require__(7); - if (indent.length % 2) { - throw new TypeError('Invalid number of spaces'); - } else { - chop = indent.length; - yield buildToken(TOKEN_TYPES.indent, indent.length / 2); - } - } else { - chop++; - } - } else if (input[0] === '"') { - let val = ''; +const path = __webpack_require__(0); - for (let i = 0;; i++) { - const currentChar = input[i]; - val += currentChar; +const IGNORE_MANIFEST_KEYS = ['readme']; - if (i > 0 && currentChar === '"') { - const isEscaped = input[i - 1] === '\\' && input[i - 2] !== '\\'; - if (!isEscaped) { - break; - } - } - } +// We treat these configs as internal, thus not expose them to process.env. +// This helps us avoid some gyp issues when building native modules. +// See https://github.com/yarnpkg/yarn/issues/2286. +const IGNORE_CONFIG_KEYS = ['lastUpdateCheck']; - chop = val.length; +exports.default = executeLifecycleScript; - try { - yield buildToken(TOKEN_TYPES.string, JSON.parse(val)); - } catch (err) { - if (err instanceof SyntaxError) { - yield buildToken(TOKEN_TYPES.invalid); - } else { - throw err; - } - } - } else if (/^[0-9]/.test(input)) { - let val = ''; - for (let i = 0; /^[0-9]$/.test(input[i]); i++) { - val += input[i]; - } - chop = val.length; - yield buildToken(TOKEN_TYPES.number, +val); - } else if (/^true/.test(input)) { - yield buildToken(TOKEN_TYPES.boolean, true); - chop = 4; - } else if (/^false/.test(input)) { - yield buildToken(TOKEN_TYPES.boolean, false); - chop = 5; - } else if (input[0] === ':') { - yield buildToken(TOKEN_TYPES.colon); - chop++; - } else if (input[0] === ',') { - yield buildToken(TOKEN_TYPES.comma); - chop++; - } else if (/^[a-zA-Z\/-]/g.test(input)) { - let name = ''; - for (let i = 0; i < input.length; i++) { - const char = input[i]; - if (char === ':' || char === ' ' || char === '\n' || char === ',') { - break; - } else { - name += char; - } - } - chop = name.length; +let checkGypPromise = null; +/** + * Special case: Some packages depend on node-gyp, but don't specify this in + * their package.json dependencies. They assume that node-gyp is available + * globally. We need to detect this case and show an error message. + */ +function checkForGypIfNeeded(config, cmd, paths) { + if (cmd.substr(0, cmd.indexOf(' ')) !== 'node-gyp') { + return Promise.resolve(); + } - yield buildToken(TOKEN_TYPES.string, name); - } else { - yield buildToken(TOKEN_TYPES.invalid); - } + // Ensure this only runs once, rather than multiple times in parallel. + if (!checkGypPromise) { + checkGypPromise = _checkForGyp(config, paths); + } + return checkGypPromise; +} - if (!chop) { - // will trigger infinite recursion - yield buildToken(TOKEN_TYPES.invalid); - } +/***/ }), +/* 98 */ +/***/ (function(module, exports, __webpack_require__) { - col += chop; - lastNewline = input[0] === '\n'; - input = input.slice(chop); - } +"use strict"; - yield buildToken(TOKEN_TYPES.eof); -} -class Parser { - constructor(input) { - let fileLoc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'lockfile'; +Object.defineProperty(exports, "__esModule", { + value: true +}); - this.comments = []; - this.tokens = tokenise(input); - this.fileLoc = fileLoc; - } +var _slicedToArray2; - onComment(token) { - const value = token.value; - invariant(typeof value === 'string', 'expected token value to be a string'); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} - const comment = value.trim(); +exports.isValidPackageName = isValidPackageName; - const versionMatch = comment.match(VERSION_REGEX); - if (versionMatch) { - const version = +versionMatch[1]; - if (version > (_constants || _load_constants()).LOCKFILE_VERSION) { - throw new (_errors || _load_errors()).MessageError(`Can't install from a lockfile of version ${version} as you're on an old yarn version that only supports ` + `versions up to ${(_constants || _load_constants()).LOCKFILE_VERSION}. Run \`$ yarn self-update\` to upgrade to the latest version.`); +exports.default = function (info, isRoot, reporter, warn) { + if (isRoot) { + for (const key in (_typos || _load_typos()).default) { + if (key in info) { + warn(reporter.lang('manifestPotentialTypo', key, (_typos || _load_typos()).default[key])); } } - - this.comments.push(comment); } - next() { - const item = this.tokens.next(); - invariant(item, 'expected a token'); + // validate name + const name = info.name; - const done = item.done, - value = item.value; + if (typeof name === 'string') { + if (isRoot && isBuiltinModule(name)) { + warn(reporter.lang('manifestBuiltinModule', name)); + } - if (done || !value) { - throw new Error('No more tokens'); - } else if (value.type === TOKEN_TYPES.comment) { - this.onComment(value); - return this.next(); - } else { - return this.token = value; + // cannot start with a dot + if (name[0] === '.') { + throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameDot')); } - } - unexpected() { - let msg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'Unexpected token'; + // cannot contain the following characters + if (!isValidPackageName(name)) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameIllegalChars')); + } - throw new SyntaxError(`${msg} ${this.token.line}:${this.token.col} in ${this.fileLoc}`); + // cannot equal node_modules or favicon.ico + const lower = name.toLowerCase(); + if (lower === 'node_modules' || lower === 'favicon.ico') { + throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestNameBlacklisted')); + } } - expect(tokType) { - if (this.token.type === tokType) { - this.next(); + // validate license + if (isRoot && !info.private) { + if (typeof info.license === 'string') { + const license = info.license.replace(/\*$/g, ''); + if (!(0, (_util || _load_util()).isValidLicense)(license)) { + warn(reporter.lang('manifestLicenseInvalid')); + } } else { - this.unexpected(); + warn(reporter.lang('manifestLicenseNone')); } } - eat(tokType) { - if (this.token.type === tokType) { - this.next(); - return true; - } else { - return false; + // validate strings + for (const key of strings) { + const val = info[key]; + if (val && typeof val !== 'string') { + throw new (_errors || _load_errors()).MessageError(reporter.lang('manifestStringExpected', key)); } } - parse() { - let indent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; - - const obj = (0, (_map || _load_map()).default)(); - - while (true) { - const propToken = this.token; - - if (propToken.type === TOKEN_TYPES.newline) { - const nextToken = this.next(); - if (!indent) { - // if we have 0 indentation then the next token doesn't matter - continue; - } - - if (nextToken.type !== TOKEN_TYPES.indent) { - // if we have no indentation after a newline then we've gone down a level - break; - } - - if (nextToken.value === indent) { - // all is good, the indent is on our level - this.next(); - } else { - // the indentation is less than our level - break; - } - } else if (propToken.type === TOKEN_TYPES.indent) { - if (propToken.value === indent) { - this.next(); - } else { - break; - } - } else if (propToken.type === TOKEN_TYPES.eof) { - break; - } else if (propToken.type === TOKEN_TYPES.string) { - // property key - const key = propToken.value; - invariant(key, 'Expected a key'); - - const keys = [key]; - this.next(); - - // support multiple keys - while (this.token.type === TOKEN_TYPES.comma) { - this.next(); // skip comma - - const keyToken = this.token; - if (keyToken.type !== TOKEN_TYPES.string) { - this.unexpected('Expected string'); - } - - const key = keyToken.value; - invariant(key, 'Expected a key'); - keys.push(key); - this.next(); - } + cleanDependencies(info, isRoot, reporter, warn); +}; - const valToken = this.token; +exports.cleanDependencies = cleanDependencies; - if (valToken.type === TOKEN_TYPES.colon) { - // object - this.next(); +var _errors; - // parse object - const val = this.parse(indent + 1); +function _load_errors() { + return _errors = __webpack_require__(3); +} - for (const key of keys) { - obj[key] = val; - } +var _util; - if (indent && this.token.type !== TOKEN_TYPES.indent) { - break; - } - } else if (isValidPropValueToken(valToken)) { - // plain value - for (const key of keys) { - obj[key] = valToken.value; - } +function _load_util() { + return _util = __webpack_require__(168); +} - this.next(); - } else { - this.unexpected('Invalid value type'); - } - } else { - this.unexpected('Unknown token'); - } - } +var _typos; - return obj; - } +function _load_typos() { + return _typos = _interopRequireDefault(__webpack_require__(442)); } -exports.Parser = Parser; - -/***/ }), -/* 81 */ -/***/ (function(module, exports, __webpack_require__) { +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -"use strict"; +const isBuiltinModule = __webpack_require__(548); +const strings = ['name', 'version']; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = stringify; +const dependencyKeys = [ +// npm registry will include optionalDependencies in dependencies and we'll want to dedupe them from the +// other fields first +'optionalDependencies', -var _misc; +// it's seemingly common to include a dependency in dependencies and devDependencies of the same name but +// different ranges, this can cause a lot of issues with our determinism and the behaviour of npm is +// currently unspecified. +'dependencies', 'devDependencies']; -function _load_misc() { - return _misc = __webpack_require__(10); +function isValidName(name) { + return !name.match(/[\/@\s\+%:]/) && encodeURIComponent(name) === name; } -var _constants; +function isValidScopedName(name) { + if (name[0] !== '@') { + return false; + } -function _load_constants() { - return _constants = __webpack_require__(8); + const parts = name.slice(1).split('/'); + return parts.length === 2 && isValidName(parts[0]) && isValidName(parts[1]); } -const YARN_VERSION = __webpack_require__(279).version; -const NODE_VERSION = process.version; - -function shouldWrapKey(str) { - return str.indexOf('true') === 0 || str.indexOf('false') === 0 || /[:\s\n\\",\[\]]/g.test(str) || /^[0-9]/g.test(str) || !/^[a-zA-Z]/g.test(str); +function isValidPackageName(name) { + return isValidName(name) || isValidScopedName(name); } -function maybeWrap(str) { - if (typeof str === 'boolean' || typeof str === 'number' || shouldWrapKey(str)) { - return JSON.stringify(str); - } else { - return str; +function cleanDependencies(info, isRoot, reporter, warn) { + // get dependency objects + const depTypes = []; + for (const type of dependencyKeys) { + const deps = info[type]; + if (!deps || typeof deps !== 'object') { + continue; + } + depTypes.push([type, deps]); } -} -const priorities = { - name: 1, - version: 2, - uid: 3, - resolved: 4, - registry: 5, - dependencies: 6 -}; + // aggregate all non-trivial deps (not '' or '*') + const nonTrivialDeps = new Map(); + for (const _ref of depTypes) { + var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); -function priorityThenAlphaSort(a, b) { - if (priorities[a] || priorities[b]) { - return (priorities[a] || 100) > (priorities[b] || 100) ? 1 : -1; - } else { - return (0, (_misc || _load_misc()).sortAlpha)(a, b); - } -} + const type = _ref2[0]; + const deps = _ref2[1]; -function _stringify(obj, options) { - if (typeof obj !== 'object') { - throw new TypeError(); + for (const name of Object.keys(deps)) { + const version = deps[name]; + if (!nonTrivialDeps.has(name) && version && version !== '*') { + nonTrivialDeps.set(name, { type, version }); + } + } } - const indent = options.indent; - const lines = []; - - // Sorting order needs to be consistent between runs, we run native sort by name because there are no - // problems with it being unstable because there are no to keys the same - // However priorities can be duplicated and native sort can shuffle things from run to run - const keys = Object.keys(obj).sort(priorityThenAlphaSort); - - let addedKeys = []; + // overwrite first dep of package with non-trivial version, remove the rest + const setDeps = new Set(); + for (const _ref3 of depTypes) { + var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2); - for (let i = 0; i < keys.length; i++) { - const key = keys[i]; - const val = obj[key]; - if (val == null || addedKeys.indexOf(key) >= 0) { - continue; - } + const type = _ref4[0]; + const deps = _ref4[1]; - // - const valKeys = [key]; + for (const name of Object.keys(deps)) { + let version = deps[name]; - // get all keys that have the same value equality, we only want this for objects - if (typeof val === 'object') { - for (let j = i + 1; j < keys.length; j++) { - const key = keys[j]; - if (val === obj[key]) { - valKeys.push(key); + const dep = nonTrivialDeps.get(name); + if (dep) { + if (version && version !== '*' && version !== dep.version && isRoot) { + // only throw a warning when at the root + warn(reporter.lang('manifestDependencyCollision', dep.type, name, dep.version, type, version)); } + version = dep.version; } - } - - // - const keyLine = valKeys.sort((_misc || _load_misc()).sortAlpha).map(maybeWrap).join(', '); - if (typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number') { - lines.push(`${keyLine} ${maybeWrap(val)}`); - } else if (typeof val === 'object') { - lines.push(`${keyLine}:\n${_stringify(val, { indent: indent + ' ' })}` + (options.topLevel ? '\n' : '')); - } else { - throw new TypeError(); + if (setDeps.has(name)) { + delete deps[name]; + } else { + deps[name] = version; + setDeps.add(name); + } } - - addedKeys = addedKeys.concat(valKeys); - } - - return indent + lines.join(`\n${indent}`); -} - -function stringify(obj, noHeader, enableVersions) { - const val = _stringify(obj, { - indent: '', - topLevel: true - }); - if (noHeader) { - return val; - } - - const lines = []; - lines.push('# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.'); - lines.push(`# yarn lockfile v${(_constants || _load_constants()).LOCKFILE_VERSION}`); - if (enableVersions) { - lines.push(`# yarn v${YARN_VERSION}`); - lines.push(`# node ${NODE_VERSION}`); } - lines.push('\n'); - lines.push(val); - - return lines.join('\n'); } /***/ }), -/* 82 */ +/* 99 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _consoleReporter; - -function _load_consoleReporter() { - return _consoleReporter = __webpack_require__(368); -} - -Object.defineProperty(exports, 'ConsoleReporter', { - enumerable: true, - get: function () { - return _interopRequireDefault(_consoleReporter || _load_consoleReporter()).default; - } -}); - -var _bufferReporter; - -function _load_bufferReporter() { - return _bufferReporter = __webpack_require__(367); -} - -Object.defineProperty(exports, 'BufferReporter', { - enumerable: true, - get: function () { - return _interopRequireDefault(_bufferReporter || _load_bufferReporter()).default; - } -}); - -var _eventReporter; - -function _load_eventReporter() { - return _eventReporter = __webpack_require__(372); -} - -Object.defineProperty(exports, 'EventReporter', { - enumerable: true, - get: function () { - return _interopRequireDefault(_eventReporter || _load_eventReporter()).default; - } -}); - -var _jsonReporter; - -function _load_jsonReporter() { - return _jsonReporter = __webpack_require__(124); -} +exports.__esModule = true; -Object.defineProperty(exports, 'JSONReporter', { - enumerable: true, - get: function () { - return _interopRequireDefault(_jsonReporter || _load_jsonReporter()).default; - } -}); +var _from = __webpack_require__(446); -var _noopReporter; +var _from2 = _interopRequireDefault(_from); -function _load_noopReporter() { - return _noopReporter = __webpack_require__(374); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -Object.defineProperty(exports, 'NoopReporter', { - enumerable: true, - get: function () { - return _interopRequireDefault(_noopReporter || _load_noopReporter()).default; - } -}); +exports.default = function (arr) { + return Array.isArray(arr) ? arr : (0, _from2.default)(arr); +}; -var _baseReporter; +/***/ }), +/* 100 */ +/***/ (function(module, exports) { -function _load_baseReporter() { - return _baseReporter = __webpack_require__(51); -} +// IE 8- don't enum bug keys +module.exports = ( + 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' +).split(','); -Object.defineProperty(exports, 'Reporter', { - enumerable: true, - get: function () { - return _interopRequireDefault(_baseReporter || _load_baseReporter()).default; - } -}); +/***/ }), +/* 101 */ +/***/ (function(module, exports, __webpack_require__) { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +module.exports = __webpack_require__(13).document && document.documentElement; /***/ }), -/* 83 */ +/* 102 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var LIBRARY = __webpack_require__(103) + , $export = __webpack_require__(66) + , redefine = __webpack_require__(193) + , hide = __webpack_require__(29) + , has = __webpack_require__(42) + , Iterators = __webpack_require__(32) + , $iterCreate = __webpack_require__(185) + , setToStringTag = __webpack_require__(67) + , getPrototypeOf = __webpack_require__(190) + , ITERATOR = __webpack_require__(9)('iterator') + , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` + , FF_ITERATOR = '@@iterator' + , KEYS = 'keys' + , VALUES = 'values'; -Object.defineProperty(exports, "__esModule", { - value: true -}); -class BaseResolver { - constructor(request, fragment) { - this.resolver = request.resolver; - this.reporter = request.reporter; - this.fragment = fragment; - this.registry = request.registry; - this.request = request; - this.pattern = request.pattern; - this.config = request.config; - } - - fork(Resolver, resolveArg) { - for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - args[_key - 2] = arguments[_key]; - } - - const resolver = new Resolver(this.request, ...args); - resolver.registry = this.registry; - return resolver.resolve(resolveArg); - } +var returnThis = function(){ return this; }; - resolve() { - throw new Error('Not implemented'); - } -} -exports.default = BaseResolver; - -/***/ }), -/* 84 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _map; - -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); -} - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const debug = __webpack_require__(453)('yarn'); - -class BlockingQueue { - constructor(alias) { - let maxConcurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity; - - this.concurrencyQueue = []; - this.maxConcurrency = maxConcurrency; - this.runningCount = 0; - this.warnedStuck = false; - this.alias = alias; - this.first = true; - - this.running = (0, (_map || _load_map()).default)(); - this.queue = (0, (_map || _load_map()).default)(); - - this.stuckTick = this.stuckTick.bind(this); - } - - stillActive() { - if (this.stuckTimer) { - clearTimeout(this.stuckTimer); +module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ + $iterCreate(Constructor, NAME, next); + var getMethod = function(kind){ + if(!BUGGY && kind in proto)return proto[kind]; + switch(kind){ + case KEYS: return function keys(){ return new Constructor(this, kind); }; + case VALUES: return function values(){ return new Constructor(this, kind); }; + } return function entries(){ return new Constructor(this, kind); }; + }; + var TAG = NAME + ' Iterator' + , DEF_VALUES = DEFAULT == VALUES + , VALUES_BUG = false + , proto = Base.prototype + , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] + , $default = $native || getMethod(DEFAULT) + , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined + , $anyNative = NAME == 'Array' ? proto.entries || $native : $native + , methods, key, IteratorPrototype; + // Fix native + if($anyNative){ + IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); + if(IteratorPrototype !== Object.prototype){ + // Set @@toStringTag to native iterators + setToStringTag(IteratorPrototype, TAG, true); + // fix for some old engines + if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } - - this.stuckTimer = setTimeout(this.stuckTick, 5000); } - - stuckTick() { - if (this.runningCount === 1) { - this.warnedStuck = true; - debug(`The ${JSON.stringify(this.alias)} blocking queue may be stuck. 5 seconds ` + `without any activity with 1 worker: ${Object.keys(this.running)[0]}`); - } + // fix Array#{values, @@iterator}.name in V8 / FF + if(DEF_VALUES && $native && $native.name !== VALUES){ + VALUES_BUG = true; + $default = function values(){ return $native.call(this); }; + } + // Define iterator + if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ + hide(proto, ITERATOR, $default); + } + // Plug for library + Iterators[NAME] = $default; + Iterators[TAG] = returnThis; + if(DEFAULT){ + methods = { + values: DEF_VALUES ? $default : getMethod(VALUES), + keys: IS_SET ? $default : getMethod(KEYS), + entries: $entries + }; + if(FORCED)for(key in methods){ + if(!(key in proto))redefine(proto, key, methods[key]); + } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } + return methods; +}; - push(key, factory) { - if (this.first) { - this.first = false; - } else { - this.stillActive(); - } +/***/ }), +/* 103 */ +/***/ (function(module, exports) { - return new Promise((resolve, reject) => { - // we're already running so push ourselves to the queue - const queue = this.queue[key] = this.queue[key] || []; - queue.push({ factory, resolve, reject }); +module.exports = true; - if (!this.running[key]) { - this.shift(key); - } - }); - } +/***/ }), +/* 104 */ +/***/ (function(module, exports, __webpack_require__) { - shift(key) { - if (this.running[key]) { - delete this.running[key]; - this.runningCount--; +var global = __webpack_require__(13) + , SHARED = '__core-js_shared__' + , store = global[SHARED] || (global[SHARED] = {}); +module.exports = function(key){ + return store[key] || (store[key] = {}); +}; - if (this.warnedStuck) { - this.warnedStuck = false; - debug(`${JSON.stringify(this.alias)} blocking queue finally resolved. Nothing to worry about.`); - } - } +/***/ }), +/* 105 */ +/***/ (function(module, exports, __webpack_require__) { - const queue = this.queue[key]; - if (!queue) { - return; - } +var ctx = __webpack_require__(37) + , invoke = __webpack_require__(184) + , html = __webpack_require__(101) + , cel = __webpack_require__(65) + , global = __webpack_require__(13) + , process = global.process + , setTask = global.setImmediate + , clearTask = global.clearImmediate + , MessageChannel = global.MessageChannel + , counter = 0 + , queue = {} + , ONREADYSTATECHANGE = 'onreadystatechange' + , defer, channel, port; +var run = function(){ + var id = +this; + if(queue.hasOwnProperty(id)){ + var fn = queue[id]; + delete queue[id]; + fn(); + } +}; +var listener = function(event){ + run.call(event.data); +}; +// Node.js 0.9+ & IE10+ has setImmediate, otherwise: +if(!setTask || !clearTask){ + setTask = function setImmediate(fn){ + var args = [], i = 1; + while(arguments.length > i)args.push(arguments[i++]); + queue[++counter] = function(){ + invoke(typeof fn == 'function' ? fn : Function(fn), args); + }; + defer(counter); + return counter; + }; + clearTask = function clearImmediate(id){ + delete queue[id]; + }; + // Node.js 0.8- + if(__webpack_require__(41)(process) == 'process'){ + defer = function(id){ + process.nextTick(ctx(run, id, 1)); + }; + // Browsers with MessageChannel, includes WebWorkers + } else if(MessageChannel){ + channel = new MessageChannel; + port = channel.port2; + channel.port1.onmessage = listener; + defer = ctx(port.postMessage, port, 1); + // Browsers with postMessage, skip WebWorkers + // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' + } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ + defer = function(id){ + global.postMessage(id + '', '*'); + }; + global.addEventListener('message', listener, false); + // IE8- + } else if(ONREADYSTATECHANGE in cel('script')){ + defer = function(id){ + html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ + html.removeChild(this); + run.call(id); + }; + }; + // Rest old browsers + } else { + defer = function(id){ + setTimeout(ctx(run, id, 1), 0); + }; + } +} +module.exports = { + set: setTask, + clear: clearTask +}; - var _queue$shift = queue.shift(); +/***/ }), +/* 106 */ +/***/ (function(module, exports, __webpack_require__) { - const resolve = _queue$shift.resolve, - reject = _queue$shift.reject, - factory = _queue$shift.factory; +// 7.1.13 ToObject(argument) +var defined = __webpack_require__(64); +module.exports = function(it){ + return Object(defined(it)); +}; - if (!queue.length) { - delete this.queue[key]; - } +/***/ }), +/* 107 */ +/***/ (function(module, exports) { - const next = () => { - this.shift(key); - this.shiftConcurrencyQueue(); - }; +var id = 0 + , px = Math.random(); +module.exports = function(key){ + return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); +}; - const run = () => { - this.running[key] = true; - this.runningCount++; +/***/ }), +/* 108 */ +/***/ (function(module, exports, __webpack_require__) { - factory().then(function (val) { - resolve(val); - next(); - return null; - }).catch(function (err) { - reject(err); - next(); - }); - }; +var classof = __webpack_require__(81) + , ITERATOR = __webpack_require__(9)('iterator') + , Iterators = __webpack_require__(32); +module.exports = __webpack_require__(21).getIteratorMethod = function(it){ + if(it != undefined)return it[ITERATOR] + || it['@@iterator'] + || Iterators[classof(it)]; +}; - this.maybePushConcurrencyQueue(run); - } +/***/ }), +/* 109 */ +/***/ (function(module, exports, __webpack_require__) { - maybePushConcurrencyQueue(run) { - if (this.runningCount < this.maxConcurrency) { - run(); - } else { - this.concurrencyQueue.push(run); - } - } +__webpack_require__(199); +var global = __webpack_require__(13) + , hide = __webpack_require__(29) + , Iterators = __webpack_require__(32) + , TO_STRING_TAG = __webpack_require__(9)('toStringTag'); - shiftConcurrencyQueue() { - if (this.runningCount < this.maxConcurrency) { - const fn = this.concurrencyQueue.shift(); - if (fn) { - fn(); - } - } - } +for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ + var NAME = collections[i] + , Collection = global[NAME] + , proto = Collection && Collection.prototype; + if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); + Iterators[NAME] = Iterators.Array; } -exports.default = BlockingQueue; /***/ }), -/* 85 */ -/***/ (function(module, exports, __webpack_require__) { +/* 110 */ +/***/ (function(module, exports) { -"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hash = hash; -const crypto = __webpack_require__(7); -const stream = __webpack_require__(20); +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; -function hash(content) { - let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'md5'; +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; - return crypto.createHash(type).update(content).digest('hex'); +function isNull(arg) { + return arg === null; } +exports.isNull = isNull; -class HashStream extends stream.Transform { - constructor(options) { - super(options); - this._hash = crypto.createHash('sha1'); - this._updated = false; - } +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; - _transform(chunk, encoding, callback) { - this._updated = true; - this._hash.update(chunk); - callback(null, chunk); - } +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; - getHash() { - return this._hash.digest('hex'); - } +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; - test(sum) { - return this._updated && sum === this.getHash(); - } +function isSymbol(arg) { + return typeof arg === 'symbol'; } -exports.HashStream = HashStream; +exports.isSymbol = isSymbol; -/***/ }), -/* 86 */ -/***/ (function(module, exports, __webpack_require__) { +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; -"use strict"; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; -Object.defineProperty(exports, "__esModule", { - value: true -}); +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; -var _rootUser; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; -function _load_rootUser() { - return _rootUser = _interopRequireDefault(__webpack_require__(392)); +function isFunction(arg) { + return typeof arg === 'function'; } +exports.isFunction = isFunction; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; -const path = __webpack_require__(1); +exports.isBuffer = Buffer.isBuffer; -const userHomeDir = process.platform === 'linux' && (_rootUser || _load_rootUser()).default ? path.resolve('/usr/local/share') : __webpack_require__(113).homedir(); +function objectToString(o) { + return Object.prototype.toString.call(o); +} -exports.default = userHomeDir; /***/ }), -/* 87 */ +/* 111 */ /***/ (function(module, exports, __webpack_require__) { -// Load modules - -var Http = __webpack_require__(50); -var Hoek = __webpack_require__(95); +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -// Declare internals +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __webpack_require__(221); -var internals = {}; +/** + * The currently active debug mode names, and names to skip. + */ -exports.wrap = function (error, statusCode, message) { +exports.names = []; +exports.skips = []; - Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object'); - return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message)); -}; +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ +exports.formatters = {}; -exports.create = function (statusCode, message, data) { +/** + * Previous log timestamp. + */ - return internals.create(statusCode, message, data, exports.create); -}; +var prevTime; -internals.create = function (statusCode, message, data, ctor) { +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ - var error = new Error(message ? message : undefined); // Avoids settings null message - Error.captureStackTrace(error, ctor); // Filter the stack to our external API - error.data = data || null; - internals.initialize(error, statusCode); - return error; -}; +function selectColor(namespace) { + var hash = 0, i; -internals.initialize = function (error, statusCode, message) { + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - var numberCode = parseInt(statusCode, 10); - Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode); + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - error.isBoom = true; - error.isServer = numberCode >= 500; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ - if (!error.hasOwnProperty('data')) { - error.data = null; - } +function createDebug(namespace) { - error.output = { - statusCode: numberCode, - payload: {}, - headers: {} - }; + function debug() { + // disabled? + if (!debug.enabled) return; - error.reformat = internals.reformat; - error.reformat(); + var self = debug; - if (!message && - !error.message) { + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - message = error.output.payload.error; + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; } - if (message) { - error.message = (message + (error.message ? ': ' + error.message : '')); - } - - return error; -}; - - -internals.reformat = function () { - - this.output.payload.statusCode = this.output.statusCode; - this.output.payload.error = Http.STATUS_CODES[this.output.statusCode] || 'Unknown'; + args[0] = exports.coerce(args[0]); - if (this.output.statusCode === 500) { - this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user - } - else if (this.message) { - this.output.payload.message = this.message; + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } -}; - -// 4xx Client Errors + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); -exports.badRequest = function (message, data) { + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - return internals.create(400, message, data, exports.badRequest); -}; + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } -exports.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[]) + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); - var err = internals.create(401, message, undefined, exports.unauthorized); + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } - if (!scheme) { - return err; - } + return debug; +} - var wwwAuthenticate = ''; - var i = 0; - var il = 0; +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ - if (typeof scheme === 'string') { +function enable(namespaces) { + exports.save(namespaces); - // function (message, scheme, attributes) + exports.names = []; + exports.skips = []; - wwwAuthenticate = scheme; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; - if (attributes || message) { - err.output.payload.attributes = {}; - } + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} - if (attributes) { - var names = Object.keys(attributes); - for (i = 0, il = names.length; i < il; ++i) { - var name = names[i]; - if (i) { - wwwAuthenticate += ','; - } +/** + * Disable debug output. + * + * @api public + */ - var value = attributes[name]; - if (value === null || - value === undefined) { // Value can be zero +function disable() { + exports.enable(''); +} - value = ''; - } - wwwAuthenticate += ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"'; - err.output.payload.attributes[name] = value; - } - } +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - if (message) { - if (attributes) { - wwwAuthenticate += ','; - } - wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"'; - err.output.payload.attributes.error = message; - } - else { - err.isMissing = true; - } +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; } - else { - - // function (message, wwwAuthenticate[]) - - var wwwArray = scheme; - for (i = 0, il = wwwArray.length; i < il; ++i) { - if (i) { - wwwAuthenticate += ', '; - } - - wwwAuthenticate += wwwArray[i]; - } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; } + } + return false; +} - err.output.headers['WWW-Authenticate'] = wwwAuthenticate; - - return err; -}; +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} -exports.forbidden = function (message, data) { - return internals.create(403, message, data, exports.forbidden); -}; +/***/ }), +/* 112 */ +/***/ (function(module, exports, __webpack_require__) { +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch -exports.notFound = function (message, data) { +var fs = __webpack_require__(5) +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync - return internals.create(404, message, data, exports.notFound); -}; +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = __webpack_require__(207) +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} -exports.methodNotAllowed = function (message, data) { +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } - return internals.create(405, message, data, exports.methodNotAllowed); -}; + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) +} +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } -exports.notAcceptable = function (message, data) { + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} - return internals.create(406, message, data, exports.notAcceptable); -}; +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync +} +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} -exports.proxyAuthRequired = function (message, data) { - return internals.create(407, message, data, exports.proxyAuthRequired); -}; +/***/ }), +/* 113 */ +/***/ (function(module, exports, __webpack_require__) { +exports.alphasort = alphasort +exports.alphasorti = alphasorti +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored -exports.clientTimeout = function (message, data) { +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} - return internals.create(408, message, data, exports.clientTimeout); -}; +var path = __webpack_require__(0) +var minimatch = __webpack_require__(57) +var isAbsolute = __webpack_require__(73) +var Minimatch = minimatch.Minimatch +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} -exports.conflict = function (message, data) { +function alphasort (a, b) { + return a.localeCompare(b) +} - return internals.create(409, message, data, exports.conflict); -}; +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] -exports.resourceGone = function (message, data) { + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} - return internals.create(410, message, data, exports.resourceGone); -}; +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} -exports.lengthRequired = function (message, data) { +function setopts (self, pattern, options) { + if (!options) + options = {} - return internals.create(411, message, data, exports.lengthRequired); -}; + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute -exports.preconditionFailed = function (message, data) { + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) - return internals.create(412, message, data, exports.preconditionFailed); -}; + setupIgnores(self, options) + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } -exports.entityTooLarge = function (message, data) { + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") - return internals.create(413, message, data, exports.entityTooLarge); -}; + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true -exports.uriTooLong = function (message, data) { + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} - return internals.create(414, message, data, exports.uriTooLong); -}; +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } -exports.unsupportedMediaType = function (message, data) { + if (!nou) + all = Object.keys(all) - return internals.create(415, message, data, exports.unsupportedMediaType); -}; + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort) + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } -exports.rangeNotSatisfiable = function (message, data) { + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) - return internals.create(416, message, data, exports.rangeNotSatisfiable); -}; + self.found = all +} +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' -exports.expectationFailed = function (message, data) { + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) - return internals.create(417, message, data, exports.expectationFailed); -}; + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } -exports.badData = function (message, data) { + return m +} - return internals.create(422, message, data, exports.badData); -}; +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') -exports.preconditionRequired = function (message, data) { + return abs +} - return internals.create(428, message, data, exports.preconditionRequired); -}; +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false -exports.tooManyRequests = function (message, data) { + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} - return internals.create(429, message, data, exports.tooManyRequests); -}; +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} -// 5xx Server Errors -exports.internal = function (message, data, statusCode) { +/***/ }), +/* 114 */ +/***/ (function(module, exports, __webpack_require__) { - return internals.serverError(message, data, statusCode, exports.internal); -}; +var path = __webpack_require__(0); +var fs = __webpack_require__(5); +var _0777 = parseInt('0777', 8); -internals.serverError = function (message, data, statusCode, ctor) { +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - var error; - if (data instanceof Error) { - error = exports.wrap(data, statusCode, message); - } else { - error = internals.create(statusCode || 500, message, undefined, ctor); - error.data = data; +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; - return error; -}; - - -exports.notImplemented = function (message, data) { - - return internals.serverError(message, data, 501, exports.notImplemented); -}; - + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} -exports.badGateway = function (message, data) { +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; - return internals.serverError(message, data, 502, exports.badGateway); -}; + p = path.resolve(p); + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; -exports.serverTimeout = function (message, data) { + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } - return internals.serverError(message, data, 503, exports.serverTimeout); + return made; }; -exports.gatewayTimeout = function (message, data) { - - return internals.serverError(message, data, 504, exports.gatewayTimeout); -}; +/***/ }), +/* 115 */ +/***/ (function(module, exports, __webpack_require__) { +// Copyright 2016 Joyent, Inc. -exports.badImplementation = function (message, data) { +module.exports = Certificate; - var err = internals.serverError(message, data, 500, exports.badImplementation); - err.isDeveloperError = true; - return err; -}; +var assert = __webpack_require__(11); +var algs = __webpack_require__(23); +var crypto = __webpack_require__(8); +var Fingerprint = __webpack_require__(116); +var Signature = __webpack_require__(45); +var errs = __webpack_require__(44); +var util = __webpack_require__(2); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var Identity = __webpack_require__(118); +var formats = {}; +formats['openssh'] = __webpack_require__(633); +formats['x509'] = __webpack_require__(320); +formats['pem'] = __webpack_require__(634); -/***/ }), -/* 88 */ -/***/ (function(module, exports) { +var CertificateParseError = errs.CertificateParseError; +var InvalidAlgorithmError = errs.InvalidAlgorithmError; -var toString = {}.toString; +function Certificate(opts) { + assert.object(opts, 'options'); + assert.arrayOfObject(opts.subjects, 'options.subjects'); + utils.assertCompatible(opts.subjects[0], Identity, [1, 0], + 'options.subjects'); + utils.assertCompatible(opts.subjectKey, Key, [1, 0], + 'options.subjectKey'); + utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer'); + if (opts.issuerKey !== undefined) { + utils.assertCompatible(opts.issuerKey, Key, [1, 0], + 'options.issuerKey'); + } + assert.object(opts.signatures, 'options.signatures'); + assert.buffer(opts.serial, 'options.serial'); + assert.date(opts.validFrom, 'options.validFrom'); + assert.date(opts.validUntil, 'optons.validUntil'); -module.exports = function(it){ - return toString.call(it).slice(8, -1); -}; + assert.optionalArrayOfString(opts.purposes, 'options.purposes'); -/***/ }), -/* 89 */ -/***/ (function(module, exports, __webpack_require__) { + this._hashCache = {}; -var global = __webpack_require__(29) - , core = __webpack_require__(31) - , ctx = __webpack_require__(68) - , hide = __webpack_require__(54) - , PROTOTYPE = 'prototype'; + this.subjects = opts.subjects; + this.issuer = opts.issuer; + this.subjectKey = opts.subjectKey; + this.issuerKey = opts.issuerKey; + this.signatures = opts.signatures; + this.serial = opts.serial; + this.validFrom = opts.validFrom; + this.validUntil = opts.validUntil; + this.purposes = opts.purposes; +} -var $export = function(type, name, source){ - var IS_FORCED = type & $export.F - , IS_GLOBAL = type & $export.G - , IS_STATIC = type & $export.S - , IS_PROTO = type & $export.P - , IS_BIND = type & $export.B - , IS_WRAP = type & $export.W - , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) - , expProto = exports[PROTOTYPE] - , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] - , key, own, out; - if(IS_GLOBAL)source = name; - for(key in source){ - // contains in native - own = !IS_FORCED && target && target[key] !== undefined; - if(own && key in exports)continue; - // export native or passed - out = own ? target[key] : source[key]; - // prevent global pollution for namespaces - exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] - // bind timers to global for call from export context - : IS_BIND && own ? ctx(out, global) - // wrap global constructors for prevent change them in library - : IS_WRAP && target[key] == out ? (function(C){ - var F = function(a, b, c){ - if(this instanceof C){ - switch(arguments.length){ - case 0: return new C; - case 1: return new C(a); - case 2: return new C(a, b); - } return new C(a, b, c); - } return C.apply(this, arguments); - }; - F[PROTOTYPE] = C[PROTOTYPE]; - return F; - // make static versions for prototype methods - })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; - // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% - if(IS_PROTO){ - (exports.virtual || (exports.virtual = {}))[key] = out; - // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% - if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); - } - } -}; -// type bitmap -$export.F = 1; // forced -$export.G = 2; // global -$export.S = 4; // static -$export.P = 8; // proto -$export.B = 16; // bind -$export.W = 32; // wrap -$export.U = 64; // safe -$export.R = 128; // real proto method for `library` -module.exports = $export; +Certificate.formats = formats; -/***/ }), -/* 90 */ -/***/ (function(module, exports) { +Certificate.prototype.toBuffer = function (format, options) { + if (format === undefined) + format = 'x509'; + assert.string(format, 'format'); + assert.object(formats[format], 'formats[format]'); + assert.optionalObject(options, 'options'); -var hasOwnProperty = {}.hasOwnProperty; -module.exports = function(it, key){ - return hasOwnProperty.call(it, key); + return (formats[format].write(this, options)); }; -/***/ }), -/* 91 */ -/***/ (function(module, exports) { - -module.exports = function(it){ - return typeof it === 'object' ? it !== null : typeof it === 'function'; +Certificate.prototype.toString = function (format, options) { + if (format === undefined) + format = 'pem'; + return (this.toBuffer(format, options).toString()); }; -/***/ }), -/* 92 */ -/***/ (function(module, exports, __webpack_require__) { +Certificate.prototype.fingerprint = function (algo) { + if (algo === undefined) + algo = 'sha256'; + assert.string(algo, 'algorithm'); + var opts = { + type: 'certificate', + hash: this.hash(algo), + algorithm: algo + }; + return (new Fingerprint(opts)); +}; -"use strict"; +Certificate.prototype.hash = function (algo) { + assert.string(algo, 'algorithm'); + algo = algo.toLowerCase(); + if (algs.hashAlgs[algo] === undefined) + throw (new InvalidAlgorithmError(algo)); -var $at = __webpack_require__(439)(true); + if (this._hashCache[algo]) + return (this._hashCache[algo]); -// 21.1.3.27 String.prototype[@@iterator]() -__webpack_require__(219)(String, 'String', function(iterated){ - this._t = String(iterated); // target - this._i = 0; // next index -// 21.1.5.2.1 %StringIteratorPrototype%.next() -}, function(){ - var O = this._t - , index = this._i - , point; - if(index >= O.length)return {value: undefined, done: true}; - point = $at(O, index); - this._i += point.length; - return {value: point, done: false}; -}); + var hash = crypto.createHash(algo). + update(this.toBuffer('x509')).digest(); + this._hashCache[algo] = hash; + return (hash); +}; -/***/ }), -/* 93 */ -/***/ (function(module, exports, __webpack_require__) { +Certificate.prototype.isExpired = function (when) { + if (when === undefined) + when = new Date(); + return (!((when.getTime() >= this.validFrom.getTime()) && + (when.getTime() < this.validUntil.getTime()))); +}; -// Basic Javascript Elliptic Curve implementation -// Ported loosely from BouncyCastle's Java EC code -// Only Fp curves implemented for now +Certificate.prototype.isSignedBy = function (issuerCert) { + utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer'); -// Requires jsbn.js and jsbn2.js -var BigInteger = __webpack_require__(40).BigInteger -var Barrett = BigInteger.prototype.Barrett + if (!this.issuer.equals(issuerCert.subjects[0])) + return (false); + if (this.issuer.purposes && this.issuer.purposes.length > 0 && + this.issuer.purposes.indexOf('ca') === -1) { + return (false); + } -// ---------------- -// ECFieldElementFp + return (this.isSignedByKey(issuerCert.subjectKey)); +}; -// constructor -function ECFieldElementFp(q,x) { - this.x = x; - // TODO if(x.compareTo(q) >= 0) error - this.q = q; -} +Certificate.prototype.isSignedByKey = function (issuerKey) { + utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey'); -function feFpEquals(other) { - if(other == this) return true; - return (this.q.equals(other.q) && this.x.equals(other.x)); -} + if (this.issuerKey !== undefined) { + return (this.issuerKey. + fingerprint('sha512').matches(issuerKey)); + } -function feFpToBigInteger() { - return this.x; -} + var fmt = Object.keys(this.signatures)[0]; + var valid = formats[fmt].verify(this, issuerKey); + if (valid) + this.issuerKey = issuerKey; + return (valid); +}; -function feFpNegate() { - return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); -} +Certificate.prototype.signWith = function (key) { + utils.assertCompatible(key, PrivateKey, [1, 2], 'key'); + var fmts = Object.keys(formats); + var didOne = false; + for (var i = 0; i < fmts.length; ++i) { + if (fmts[i] !== 'pem') { + var ret = formats[fmts[i]].sign(this, key); + if (ret === true) + didOne = true; + } + } + if (!didOne) { + throw (new Error('Failed to sign the certificate for any ' + + 'available certificate formats')); + } +}; -function feFpAdd(b) { - return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); -} +Certificate.createSelfSigned = function (subjectOrSubjects, key, options) { + var subjects; + if (Array.isArray(subjectOrSubjects)) + subjects = subjectOrSubjects; + else + subjects = [subjectOrSubjects]; -function feFpSubtract(b) { - return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); -} + assert.arrayOfObject(subjects); + subjects.forEach(function (subject) { + utils.assertCompatible(subject, Identity, [1, 0], 'subject'); + }); -function feFpMultiply(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); -} + utils.assertCompatible(key, PrivateKey, [1, 2], 'private key'); -function feFpSquare() { - return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); -} + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalObject(options.validFrom, 'options.validFrom'); + assert.optionalObject(options.validUntil, 'options.validUntil'); + var validFrom = options.validFrom; + var validUntil = options.validUntil; + if (validFrom === undefined) + validFrom = new Date(); + if (validUntil === undefined) { + assert.optionalNumber(options.lifetime, 'options.lifetime'); + var lifetime = options.lifetime; + if (lifetime === undefined) + lifetime = 10*365*24*3600; + validUntil = new Date(); + validUntil.setTime(validUntil.getTime() + lifetime*1000); + } + assert.optionalBuffer(options.serial, 'options.serial'); + var serial = options.serial; + if (serial === undefined) + serial = new Buffer('0000000000000001', 'hex'); -function feFpDivide(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); -} + var purposes = options.purposes; + if (purposes === undefined) + purposes = []; -ECFieldElementFp.prototype.equals = feFpEquals; -ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; -ECFieldElementFp.prototype.negate = feFpNegate; -ECFieldElementFp.prototype.add = feFpAdd; -ECFieldElementFp.prototype.subtract = feFpSubtract; -ECFieldElementFp.prototype.multiply = feFpMultiply; -ECFieldElementFp.prototype.square = feFpSquare; -ECFieldElementFp.prototype.divide = feFpDivide; + if (purposes.indexOf('signature') === -1) + purposes.push('signature'); -// ---------------- -// ECPointFp + /* Self-signed certs are always CAs. */ + if (purposes.indexOf('ca') === -1) + purposes.push('ca'); + if (purposes.indexOf('crl') === -1) + purposes.push('crl'); -// constructor -function ECPointFp(curve,x,y,z) { - this.curve = curve; - this.x = x; - this.y = y; - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - if(z == null) { - this.z = BigInteger.ONE; - } - else { - this.z = z; - } - this.zinv = null; - //TODO: compression flag -} + /* + * If we weren't explicitly given any other purposes, do the sensible + * thing and add some basic ones depending on the subject type. + */ + if (purposes.length <= 3) { + var hostSubjects = subjects.filter(function (subject) { + return (subject.type === 'host'); + }); + var userSubjects = subjects.filter(function (subject) { + return (subject.type === 'user'); + }); + if (hostSubjects.length > 0) { + if (purposes.indexOf('serverAuth') === -1) + purposes.push('serverAuth'); + } + if (userSubjects.length > 0) { + if (purposes.indexOf('clientAuth') === -1) + purposes.push('clientAuth'); + } + if (userSubjects.length > 0 || hostSubjects.length > 0) { + if (purposes.indexOf('keyAgreement') === -1) + purposes.push('keyAgreement'); + if (key.type === 'rsa' && + purposes.indexOf('encryption') === -1) + purposes.push('encryption'); + } + } -function pointFpGetX() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.x.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); -} + var cert = new Certificate({ + subjects: subjects, + issuer: subjects[0], + subjectKey: key.toPublic(), + issuerKey: key.toPublic(), + signatures: {}, + serial: serial, + validFrom: validFrom, + validUntil: validUntil, + purposes: purposes + }); + cert.signWith(key); -function pointFpGetY() { - if(this.zinv == null) { - this.zinv = this.z.modInverse(this.curve.q); - } - var r = this.y.toBigInteger().multiply(this.zinv); - this.curve.reduce(r); - return this.curve.fromBigInteger(r); -} + return (cert); +}; -function pointFpEquals(other) { - if(other == this) return true; - if(this.isInfinity()) return other.isInfinity(); - if(other.isInfinity()) return this.isInfinity(); - var u, v; - // u = Y2 * Z1 - Y1 * Z2 - u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); - if(!u.equals(BigInteger.ZERO)) return false; - // v = X2 * Z1 - X1 * Z2 - v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); - return v.equals(BigInteger.ZERO); -} +Certificate.create = + function (subjectOrSubjects, key, issuer, issuerKey, options) { + var subjects; + if (Array.isArray(subjectOrSubjects)) + subjects = subjectOrSubjects; + else + subjects = [subjectOrSubjects]; -function pointFpIsInfinity() { - if((this.x == null) && (this.y == null)) return true; - return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); -} + assert.arrayOfObject(subjects); + subjects.forEach(function (subject) { + utils.assertCompatible(subject, Identity, [1, 0], 'subject'); + }); -function pointFpNegate() { - return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); -} + utils.assertCompatible(key, Key, [1, 0], 'key'); + if (PrivateKey.isPrivateKey(key)) + key = key.toPublic(); + utils.assertCompatible(issuer, Identity, [1, 0], 'issuer'); + utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key'); -function pointFpAdd(b) { - if(this.isInfinity()) return b; - if(b.isInfinity()) return this; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalObject(options.validFrom, 'options.validFrom'); + assert.optionalObject(options.validUntil, 'options.validUntil'); + var validFrom = options.validFrom; + var validUntil = options.validUntil; + if (validFrom === undefined) + validFrom = new Date(); + if (validUntil === undefined) { + assert.optionalNumber(options.lifetime, 'options.lifetime'); + var lifetime = options.lifetime; + if (lifetime === undefined) + lifetime = 10*365*24*3600; + validUntil = new Date(); + validUntil.setTime(validUntil.getTime() + lifetime*1000); + } + assert.optionalBuffer(options.serial, 'options.serial'); + var serial = options.serial; + if (serial === undefined) + serial = new Buffer('0000000000000001', 'hex'); - // u = Y2 * Z1 - Y1 * Z2 - var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); - // v = X2 * Z1 - X1 * Z2 - var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); + var purposes = options.purposes; + if (purposes === undefined) + purposes = []; - if(BigInteger.ZERO.equals(v)) { - if(BigInteger.ZERO.equals(u)) { - return this.twice(); // this == b, so double - } - return this.curve.getInfinity(); // this = -b, so infinity - } + if (purposes.indexOf('signature') === -1) + purposes.push('signature'); - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); - var x2 = b.x.toBigInteger(); - var y2 = b.y.toBigInteger(); + if (options.ca === true) { + if (purposes.indexOf('ca') === -1) + purposes.push('ca'); + if (purposes.indexOf('crl') === -1) + purposes.push('crl'); + } - var v2 = v.square(); - var v3 = v2.multiply(v); - var x1v2 = x1.multiply(v2); - var zu2 = u.square().multiply(this.z); + var hostSubjects = subjects.filter(function (subject) { + return (subject.type === 'host'); + }); + var userSubjects = subjects.filter(function (subject) { + return (subject.type === 'user'); + }); + if (hostSubjects.length > 0) { + if (purposes.indexOf('serverAuth') === -1) + purposes.push('serverAuth'); + } + if (userSubjects.length > 0) { + if (purposes.indexOf('clientAuth') === -1) + purposes.push('clientAuth'); + } + if (userSubjects.length > 0 || hostSubjects.length > 0) { + if (purposes.indexOf('keyAgreement') === -1) + purposes.push('keyAgreement'); + if (key.type === 'rsa' && + purposes.indexOf('encryption') === -1) + purposes.push('encryption'); + } - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); + var cert = new Certificate({ + subjects: subjects, + issuer: issuer, + subjectKey: key, + issuerKey: issuerKey.toPublic(), + signatures: {}, + serial: serial, + validFrom: validFrom, + validUntil: validUntil, + purposes: purposes + }); + cert.signWith(issuerKey); - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); -} + return (cert); +}; -function pointFpTwice() { - if(this.isInfinity()) return this; - if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); +Certificate.parse = function (data, format, options) { + if (typeof (data) !== 'string') + assert.buffer(data, 'data'); + if (format === undefined) + format = 'auto'; + assert.string(format, 'format'); + if (typeof (options) === 'string') + options = { filename: options }; + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + assert.optionalString(options.filename, 'options.filename'); + if (options.filename === undefined) + options.filename = '(unnamed)'; - // TODO: optimized handling of constants - var THREE = new BigInteger("3"); - var x1 = this.x.toBigInteger(); - var y1 = this.y.toBigInteger(); + assert.object(formats[format], 'formats[format]'); - var y1z1 = y1.multiply(this.z); - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); - var a = this.curve.a.toBigInteger(); + try { + var k = formats[format].read(data, options); + return (k); + } catch (e) { + throw (new CertificateParseError(options.filename, format, e)); + } +}; - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE); - if(!BigInteger.ZERO.equals(a)) { - w = w.add(this.z.square().multiply(a)); - } - w = w.mod(this.curve.q); - //this.curve.reduce(w); - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); +Certificate.isCertificate = function (obj, ver) { + return (utils.isCompatible(obj, Certificate, ver)); +}; - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); -} +/* + * API versions for Certificate: + * [1,0] -- initial ver + */ +Certificate.prototype._sshpkApiVersion = [1, 0]; -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -function pointFpMultiply(k) { - if(this.isInfinity()) return this; - if(k.signum() == 0) return this.curve.getInfinity(); +Certificate._oldVersionDetect = function (obj) { + return ([1, 0]); +}; - var e = k; - var h = e.multiply(new BigInteger("3")); - var neg = this.negate(); - var R = this; +/***/ }), +/* 116 */ +/***/ (function(module, exports, __webpack_require__) { - var i; - for(i = h.bitLength() - 2; i > 0; --i) { - R = R.twice(); +// Copyright 2015 Joyent, Inc. - var hBit = h.testBit(i); - var eBit = e.testBit(i); +module.exports = Fingerprint; - if (hBit != eBit) { - R = R.add(hBit ? this : neg); - } - } +var assert = __webpack_require__(11); +var algs = __webpack_require__(23); +var crypto = __webpack_require__(8); +var errs = __webpack_require__(44); +var Key = __webpack_require__(24); +var Certificate = __webpack_require__(115); +var utils = __webpack_require__(17); - return R; -} +var FingerprintFormatError = errs.FingerprintFormatError; +var InvalidAlgorithmError = errs.InvalidAlgorithmError; -// Compute this*j + x*k (simultaneous multiplication) -function pointFpMultiplyTwo(j,x,k) { - var i; - if(j.bitLength() > k.bitLength()) - i = j.bitLength() - 1; - else - i = k.bitLength() - 1; +function Fingerprint(opts) { + assert.object(opts, 'options'); + assert.string(opts.type, 'options.type'); + assert.buffer(opts.hash, 'options.hash'); + assert.string(opts.algorithm, 'options.algorithm'); - var R = this.curve.getInfinity(); - var both = this.add(x); - while(i >= 0) { - R = R.twice(); - if(j.testBit(i)) { - if(k.testBit(i)) { - R = R.add(both); - } - else { - R = R.add(this); - } - } - else { - if(k.testBit(i)) { - R = R.add(x); - } - } - --i; - } + this.algorithm = opts.algorithm.toLowerCase(); + if (algs.hashAlgs[this.algorithm] !== true) + throw (new InvalidAlgorithmError(this.algorithm)); - return R; + this.hash = opts.hash; + this.type = opts.type; } -ECPointFp.prototype.getX = pointFpGetX; -ECPointFp.prototype.getY = pointFpGetY; -ECPointFp.prototype.equals = pointFpEquals; -ECPointFp.prototype.isInfinity = pointFpIsInfinity; -ECPointFp.prototype.negate = pointFpNegate; -ECPointFp.prototype.add = pointFpAdd; -ECPointFp.prototype.twice = pointFpTwice; -ECPointFp.prototype.multiply = pointFpMultiply; -ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; +Fingerprint.prototype.toString = function (format) { + if (format === undefined) { + if (this.algorithm === 'md5') + format = 'hex'; + else + format = 'base64'; + } + assert.string(format); -// ---------------- -// ECCurveFp + switch (format) { + case 'hex': + return (addColons(this.hash.toString('hex'))); + case 'base64': + return (sshBase64Format(this.algorithm, + this.hash.toString('base64'))); + default: + throw (new FingerprintFormatError(undefined, format)); + } +}; -// constructor -function ECCurveFp(q,a,b) { - this.q = q; - this.a = this.fromBigInteger(a); - this.b = this.fromBigInteger(b); - this.infinity = new ECPointFp(this, null, null); - this.reducer = new Barrett(this.q); -} +Fingerprint.prototype.matches = function (other) { + assert.object(other, 'key or certificate'); + if (this.type === 'key') { + utils.assertCompatible(other, Key, [1, 0], 'key'); + } else { + utils.assertCompatible(other, Certificate, [1, 0], + 'certificate'); + } -function curveFpGetQ() { - return this.q; -} + var theirHash = other.hash(this.algorithm); + var theirHash2 = crypto.createHash(this.algorithm). + update(theirHash).digest('base64'); -function curveFpGetA() { - return this.a; -} + if (this.hash2 === undefined) + this.hash2 = crypto.createHash(this.algorithm). + update(this.hash).digest('base64'); -function curveFpGetB() { - return this.b; -} + return (this.hash2 === theirHash2); +}; -function curveFpEquals(other) { - if(other == this) return true; - return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); -} +Fingerprint.parse = function (fp, options) { + assert.string(fp, 'fingerprint'); -function curveFpGetInfinity() { - return this.infinity; + var alg, hash, enAlgs; + if (Array.isArray(options)) { + enAlgs = options; + options = {}; + } + assert.optionalObject(options, 'options'); + if (options === undefined) + options = {}; + if (options.enAlgs !== undefined) + enAlgs = options.enAlgs; + assert.optionalArrayOfString(enAlgs, 'algorithms'); + + var parts = fp.split(':'); + if (parts.length == 2) { + alg = parts[0].toLowerCase(); + /*JSSTYLED*/ + var base64RE = /^[A-Za-z0-9+\/=]+$/; + if (!base64RE.test(parts[1])) + throw (new FingerprintFormatError(fp)); + try { + hash = new Buffer(parts[1], 'base64'); + } catch (e) { + throw (new FingerprintFormatError(fp)); + } + } else if (parts.length > 2) { + alg = 'md5'; + if (parts[0].toLowerCase() === 'md5') + parts = parts.slice(1); + parts = parts.join(''); + /*JSSTYLED*/ + var md5RE = /^[a-fA-F0-9]+$/; + if (!md5RE.test(parts)) + throw (new FingerprintFormatError(fp)); + try { + hash = new Buffer(parts, 'hex'); + } catch (e) { + throw (new FingerprintFormatError(fp)); + } + } + + if (alg === undefined) + throw (new FingerprintFormatError(fp)); + + if (algs.hashAlgs[alg] === undefined) + throw (new InvalidAlgorithmError(alg)); + + if (enAlgs !== undefined) { + enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); }); + if (enAlgs.indexOf(alg) === -1) + throw (new InvalidAlgorithmError(alg)); + } + + return (new Fingerprint({ + algorithm: alg, + hash: hash, + type: options.type || 'key' + })); +}; + +function addColons(s) { + /*JSSTYLED*/ + return (s.replace(/(.{2})(?=.)/g, '$1:')); } -function curveFpFromBigInteger(x) { - return new ECFieldElementFp(this.q, x); +function base64Strip(s) { + /*JSSTYLED*/ + return (s.replace(/=*$/, '')); } -function curveReduce(x) { - this.reducer.reduce(x); +function sshBase64Format(alg, h) { + return (alg.toUpperCase() + ':' + base64Strip(h)); } -// for now, work with hex strings because they're easier in JS -function curveFpDecodePointHex(s) { - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - case 3: - // point compression not supported yet - return null; - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); +Fingerprint.isFingerprint = function (obj, ver) { + return (utils.isCompatible(obj, Fingerprint, ver)); +}; - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); +/* + * API versions for Fingerprint: + * [1,0] -- initial ver + * [1,1] -- first tagged ver + */ +Fingerprint.prototype._sshpkApiVersion = [1, 1]; - default: // unsupported - return null; - } -} +Fingerprint._oldVersionDetect = function (obj) { + assert.func(obj.toString); + assert.func(obj.matches); + return ([1, 0]); +}; -function curveFpEncodePointHex(p) { - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var yHex = p.getY().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) { - xHex = "0" + xHex; - } - while (yHex.length < oLen) { - yHex = "0" + yHex; - } - return "04" + xHex + yHex; -} -ECCurveFp.prototype.getQ = curveFpGetQ; -ECCurveFp.prototype.getA = curveFpGetA; -ECCurveFp.prototype.getB = curveFpGetB; -ECCurveFp.prototype.equals = curveFpEquals; -ECCurveFp.prototype.getInfinity = curveFpGetInfinity; -ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; -ECCurveFp.prototype.reduce = curveReduce; -//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; -ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; +/***/ }), +/* 117 */ +/***/ (function(module, exports, __webpack_require__) { -// from: https://github.com/kaielvin/jsbn-ec-point-compression -ECCurveFp.prototype.decodePointHex = function(s) -{ - var yIsEven; - switch(parseInt(s.substr(0,2), 16)) { // first byte - case 0: - return this.infinity; - case 2: - yIsEven = false; - case 3: - if(yIsEven == undefined) yIsEven = true; - var len = s.length - 2; - var xHex = s.substr(2, len); - var x = this.fromBigInteger(new BigInteger(xHex,16)); - var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); - var beta = alpha.sqrt(); +// Copyright 2015 Joyent, Inc. - if (beta == null) throw "Invalid point compression"; +module.exports = { + read: read, + readPkcs8: readPkcs8, + write: write, + writePkcs8: writePkcs8, - var betaValue = beta.toBigInteger(); - if (betaValue.testBit(0) != yIsEven) - { - // Use the other root - beta = this.fromBigInteger(this.getQ().subtract(betaValue)); - } - return new ECPointFp(this,x,beta); - case 4: - case 6: - case 7: - var len = (s.length - 2) / 2; - var xHex = s.substr(2, len); - var yHex = s.substr(len+2, len); + readECDSACurve: readECDSACurve, + writeECDSACurve: writeECDSACurve +}; - return new ECPointFp(this, - this.fromBigInteger(new BigInteger(xHex, 16)), - this.fromBigInteger(new BigInteger(yHex, 16))); +var assert = __webpack_require__(11); +var asn1 = __webpack_require__(50); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var pem = __webpack_require__(58); - default: // unsupported - return null; - } +function read(buf, options) { + return (pem.read(buf, options, 'pkcs8')); } -ECCurveFp.prototype.encodeCompressedPointHex = function(p) -{ - if (p.isInfinity()) return "00"; - var xHex = p.getX().toBigInteger().toString(16); - var oLen = this.getQ().toString(16).length; - if ((oLen % 2) != 0) oLen++; - while (xHex.length < oLen) - xHex = "0" + xHex; - var yPrefix; - if(p.getY().toBigInteger().isEven()) yPrefix = "02"; - else yPrefix = "03"; - return yPrefix + xHex; +function write(key, options) { + return (pem.write(key, options, 'pkcs8')); } +/* Helper to read in a single mpint */ +function readMPInt(der, nm) { + assert.strictEqual(der.peek(), asn1.Ber.Integer, + nm + ' is not an Integer'); + return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); +} -ECFieldElementFp.prototype.getR = function() -{ - if(this.r != undefined) return this.r; +function readPkcs8(alg, type, der) { + /* Private keys in pkcs#8 format have a weird extra int */ + if (der.peek() === asn1.Ber.Integer) { + assert.strictEqual(type, 'private', + 'unexpected Integer at start of public key'); + der.readString(asn1.Ber.Integer, true); + } - this.r = null; - var bitLength = this.q.bitLength(); - if (bitLength > 128) - { - var firstWord = this.q.shiftRight(bitLength - 64); - if (firstWord.intValue() == -1) - { - this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); - } - } - return this.r; -} -ECFieldElementFp.prototype.modMult = function(x1,x2) -{ - return this.modReduce(x1.multiply(x2)); -} -ECFieldElementFp.prototype.modReduce = function(x) -{ - if (this.getR() != null) - { - var qLen = q.bitLength(); - while (x.bitLength() > (qLen + 1)) - { - var u = x.shiftRight(qLen); - var v = x.subtract(u.shiftLeft(qLen)); - if (!this.getR().equals(BigInteger.ONE)) - { - u = u.multiply(this.getR()); - } - x = u.add(v); - } - while (x.compareTo(q) >= 0) - { - x = x.subtract(q); - } - } - else - { - x = x.mod(q); - } - return x; -} -ECFieldElementFp.prototype.sqrt = function() -{ - if (!this.q.testBit(0)) throw "unsupported"; - - // p mod 4 == 3 - if (this.q.testBit(1)) - { - var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); - return z.square().equals(this) ? z : null; - } + der.readSequence(); + var next = der.offset + der.length; - // p mod 4 == 1 - var qMinusOne = this.q.subtract(BigInteger.ONE); + var oid = der.readOID(); + switch (oid) { + case '1.2.840.113549.1.1.1': + der._offset = next; + if (type === 'public') + return (readPkcs8RSAPublic(der)); + else + return (readPkcs8RSAPrivate(der)); + case '1.2.840.10040.4.1': + if (type === 'public') + return (readPkcs8DSAPublic(der)); + else + return (readPkcs8DSAPrivate(der)); + case '1.2.840.10045.2.1': + if (type === 'public') + return (readPkcs8ECDSAPublic(der)); + else + return (readPkcs8ECDSAPrivate(der)); + default: + throw (new Error('Unknown key type OID ' + oid)); + } +} - var legendreExponent = qMinusOne.shiftRight(1); - if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) - { - return null; - } +function readPkcs8RSAPublic(der) { + // bit string sequence + der.readSequence(asn1.Ber.BitString); + der.readByte(); + der.readSequence(); - var u = qMinusOne.shiftRight(2); - var k = u.shiftLeft(1).add(BigInteger.ONE); + // modulus + var n = readMPInt(der, 'modulus'); + var e = readMPInt(der, 'exponent'); - var Q = this.x; - var fourQ = modDouble(modDouble(Q)); + // now, make the key + var key = { + type: 'rsa', + source: der.originalInput, + parts: [ + { name: 'e', data: e }, + { name: 'n', data: n } + ] + }; - var U, V; - do - { - var P; - do - { - P = new BigInteger(this.q.bitLength(), new SecureRandom()); - } - while (P.compareTo(this.q) >= 0 - || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); + return (new Key(key)); +} - var result = this.lucasSequence(P, Q, k); - U = result[0]; - V = result[1]; +function readPkcs8RSAPrivate(der) { + der.readSequence(asn1.Ber.OctetString); + der.readSequence(); - if (this.modMult(V, V).equals(fourQ)) - { - // Integer division by 2, mod q - if (V.testBit(0)) - { - V = V.add(q); - } + var ver = readMPInt(der, 'version'); + assert.equal(ver[0], 0x0, 'unknown RSA private key version'); - V = V.shiftRight(1); + // modulus then public exponent + var n = readMPInt(der, 'modulus'); + var e = readMPInt(der, 'public exponent'); + var d = readMPInt(der, 'private exponent'); + var p = readMPInt(der, 'prime1'); + var q = readMPInt(der, 'prime2'); + var dmodp = readMPInt(der, 'exponent1'); + var dmodq = readMPInt(der, 'exponent2'); + var iqmp = readMPInt(der, 'iqmp'); - return new ECFieldElementFp(q,V); - } - } - while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); + // now, make the key + var key = { + type: 'rsa', + parts: [ + { name: 'n', data: n }, + { name: 'e', data: e }, + { name: 'd', data: d }, + { name: 'iqmp', data: iqmp }, + { name: 'p', data: p }, + { name: 'q', data: q }, + { name: 'dmodp', data: dmodp }, + { name: 'dmodq', data: dmodq } + ] + }; - return null; + return (new PrivateKey(key)); } -ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) -{ - var n = k.bitLength(); - var s = k.getLowestSetBit(); - - var Uh = BigInteger.ONE; - var Vl = BigInteger.TWO; - var Vh = P; - var Ql = BigInteger.ONE; - var Qh = BigInteger.ONE; - for (var j = n - 1; j >= s + 1; --j) - { - Ql = this.modMult(Ql, Qh); +function readPkcs8DSAPublic(der) { + der.readSequence(); - if (k.testBit(j)) - { - Qh = this.modMult(Ql, Q); - Uh = this.modMult(Uh, Vh); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); - } - else - { - Qh = Ql; - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - } - } + var p = readMPInt(der, 'p'); + var q = readMPInt(der, 'q'); + var g = readMPInt(der, 'g'); - Ql = this.modMult(Ql, Qh); - Qh = this.modMult(Ql, Q); - Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); - Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); - Ql = this.modMult(Ql, Qh); + // bit string sequence + der.readSequence(asn1.Ber.BitString); + der.readByte(); - for (var j = 1; j <= s; ++j) - { - Uh = this.modMult(Uh, Vl); - Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); - Ql = this.modMult(Ql, Ql); - } + var y = readMPInt(der, 'y'); - return [ Uh, Vl ]; -} + // now, make the key + var key = { + type: 'dsa', + parts: [ + { name: 'p', data: p }, + { name: 'q', data: q }, + { name: 'g', data: g }, + { name: 'y', data: y } + ] + }; -var exports = { - ECCurveFp: ECCurveFp, - ECPointFp: ECPointFp, - ECFieldElementFp: ECFieldElementFp + return (new Key(key)); } -module.exports = exports +function readPkcs8DSAPrivate(der) { + der.readSequence(); + var p = readMPInt(der, 'p'); + var q = readMPInt(der, 'q'); + var g = readMPInt(der, 'g'); -/***/ }), -/* 94 */ -/***/ (function(module, exports, __webpack_require__) { + der.readSequence(asn1.Ber.OctetString); + var x = readMPInt(der, 'x'); -// Load modules + /* The pkcs#8 format does not include the public key */ + var y = utils.calculateDSAPublic(g, p, x); -var Sntp = __webpack_require__(262); -var Boom = __webpack_require__(87); + var key = { + type: 'dsa', + parts: [ + { name: 'p', data: p }, + { name: 'q', data: q }, + { name: 'g', data: g }, + { name: 'y', data: y }, + { name: 'x', data: x } + ] + }; + return (new PrivateKey(key)); +} -// Declare internals +function readECDSACurve(der) { + var curveName, curveNames; + var j, c, cd; -var internals = {}; + if (der.peek() === asn1.Ber.OID) { + var oid = der.readOID(); + curveNames = Object.keys(algs.curves); + for (j = 0; j < curveNames.length; ++j) { + c = curveNames[j]; + cd = algs.curves[c]; + if (cd.pkcs8oid === oid) { + curveName = c; + break; + } + } -exports.version = function () { + } else { + // ECParameters sequence + der.readSequence(); + var version = der.readString(asn1.Ber.Integer, true); + assert.strictEqual(version[0], 1, 'ECDSA key not version 1'); - return __webpack_require__(508).version; -}; + var curve = {}; + // FieldID sequence + der.readSequence(); + var fieldTypeOid = der.readOID(); + assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1', + 'ECDSA key is not from a prime-field'); + var p = curve.p = utils.mpNormalize( + der.readString(asn1.Ber.Integer, true)); + /* + * p always starts with a 1 bit, so count the zeros to get its + * real size. + */ + curve.size = p.length * 8 - utils.countZeros(p); -exports.limits = { - maxMatchLength: 4096 // Limit the length of uris and headers to avoid a DoS attack on string matching -}; + // Curve sequence + der.readSequence(); + curve.a = utils.mpNormalize( + der.readString(asn1.Ber.OctetString, true)); + curve.b = utils.mpNormalize( + der.readString(asn1.Ber.OctetString, true)); + if (der.peek() === asn1.Ber.BitString) + curve.s = der.readString(asn1.Ber.BitString, true); + // Combined Gx and Gy + curve.G = der.readString(asn1.Ber.OctetString, true); + assert.strictEqual(curve.G[0], 0x4, + 'uncompressed G is required'); -// Extract host and port from request + curve.n = utils.mpNormalize( + der.readString(asn1.Ber.Integer, true)); + curve.h = utils.mpNormalize( + der.readString(asn1.Ber.Integer, true)); + assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' + + 'required'); -// $1 $2 -internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/; // (IPv4, hostname)|(IPv6) + curveNames = Object.keys(algs.curves); + var ks = Object.keys(curve); + for (j = 0; j < curveNames.length; ++j) { + c = curveNames[j]; + cd = algs.curves[c]; + var equal = true; + for (var i = 0; i < ks.length; ++i) { + var k = ks[i]; + if (cd[k] === undefined) + continue; + if (typeof (cd[k]) === 'object' && + cd[k].equals !== undefined) { + if (!cd[k].equals(curve[k])) { + equal = false; + break; + } + } else if (Buffer.isBuffer(cd[k])) { + if (cd[k].toString('binary') + !== curve[k].toString('binary')) { + equal = false; + break; + } + } else { + if (cd[k] !== curve[k]) { + equal = false; + break; + } + } + } + if (equal) { + curveName = c; + break; + } + } + } + return (curveName); +} +function readPkcs8ECDSAPrivate(der) { + var curveName = readECDSACurve(der); + assert.string(curveName, 'a known elliptic curve'); -exports.parseHost = function (req, hostHeaderName) { + der.readSequence(asn1.Ber.OctetString); + der.readSequence(); - hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host'); - var hostHeader = req.headers[hostHeaderName]; - if (!hostHeader) { - return null; - } + var version = readMPInt(der, 'version'); + assert.equal(version[0], 1, 'unknown version of ECDSA key'); - if (hostHeader.length > exports.limits.maxMatchLength) { - return null; - } + var d = der.readString(asn1.Ber.OctetString, true); + der.readSequence(0xa1); - var hostParts = hostHeader.match(internals.hostHeaderRegex); - if (!hostParts) { - return null; - } + var Q = der.readString(asn1.Ber.BitString, true); + Q = utils.ecNormalize(Q); - return { - name: hostParts[1], - port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80)) - }; -}; + var key = { + type: 'ecdsa', + parts: [ + { name: 'curve', data: new Buffer(curveName) }, + { name: 'Q', data: Q }, + { name: 'd', data: d } + ] + }; + return (new PrivateKey(key)); +} -// Parse Content-Type header content +function readPkcs8ECDSAPublic(der) { + var curveName = readECDSACurve(der); + assert.string(curveName, 'a known elliptic curve'); -exports.parseContentType = function (header) { + var Q = der.readString(asn1.Ber.BitString, true); + Q = utils.ecNormalize(Q); - if (!header) { - return ''; - } + var key = { + type: 'ecdsa', + parts: [ + { name: 'curve', data: new Buffer(curveName) }, + { name: 'Q', data: Q } + ] + }; - return header.split(';')[0].trim().toLowerCase(); -}; + return (new Key(key)); +} +function writePkcs8(der, key) { + der.startSequence(); -// Convert node's to request configuration object + if (PrivateKey.isPrivateKey(key)) { + var sillyInt = new Buffer(1); + sillyInt[0] = 0x0; + der.writeBuffer(sillyInt, asn1.Ber.Integer); + } -exports.parseRequest = function (req, options) { + der.startSequence(); + switch (key.type) { + case 'rsa': + der.writeOID('1.2.840.113549.1.1.1'); + if (PrivateKey.isPrivateKey(key)) + writePkcs8RSAPrivate(key, der); + else + writePkcs8RSAPublic(key, der); + break; + case 'dsa': + der.writeOID('1.2.840.10040.4.1'); + if (PrivateKey.isPrivateKey(key)) + writePkcs8DSAPrivate(key, der); + else + writePkcs8DSAPublic(key, der); + break; + case 'ecdsa': + der.writeOID('1.2.840.10045.2.1'); + if (PrivateKey.isPrivateKey(key)) + writePkcs8ECDSAPrivate(key, der); + else + writePkcs8ECDSAPublic(key, der); + break; + default: + throw (new Error('Unsupported key type: ' + key.type)); + } - if (!req.headers) { - return req; - } + der.endSequence(); +} - // Obtain host and port information +function writePkcs8RSAPrivate(key, der) { + der.writeNull(); + der.endSequence(); - var host; - if (!options.host || - !options.port) { + der.startSequence(asn1.Ber.OctetString); + der.startSequence(); - host = exports.parseHost(req, options.hostHeaderName); - if (!host) { - return new Error('Invalid Host header'); - } - } + var version = new Buffer(1); + version[0] = 0; + der.writeBuffer(version, asn1.Ber.Integer); - var request = { - method: req.method, - url: req.url, - host: options.host || host.name, - port: options.port || host.port, - authorization: req.headers.authorization, - contentType: req.headers['content-type'] || '' - }; + der.writeBuffer(key.part.n.data, asn1.Ber.Integer); + der.writeBuffer(key.part.e.data, asn1.Ber.Integer); + der.writeBuffer(key.part.d.data, asn1.Ber.Integer); + der.writeBuffer(key.part.p.data, asn1.Ber.Integer); + der.writeBuffer(key.part.q.data, asn1.Ber.Integer); + if (!key.part.dmodp || !key.part.dmodq) + utils.addRSAMissing(key); + der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); + der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); + der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); - return request; -}; + der.endSequence(); + der.endSequence(); +} +function writePkcs8RSAPublic(key, der) { + der.writeNull(); + der.endSequence(); -exports.now = function (localtimeOffsetMsec) { + der.startSequence(asn1.Ber.BitString); + der.writeByte(0x00); - return Sntp.now() + (localtimeOffsetMsec || 0); -}; + der.startSequence(); + der.writeBuffer(key.part.n.data, asn1.Ber.Integer); + der.writeBuffer(key.part.e.data, asn1.Ber.Integer); + der.endSequence(); + der.endSequence(); +} -exports.nowSecs = function (localtimeOffsetMsec) { +function writePkcs8DSAPrivate(key, der) { + der.startSequence(); + der.writeBuffer(key.part.p.data, asn1.Ber.Integer); + der.writeBuffer(key.part.q.data, asn1.Ber.Integer); + der.writeBuffer(key.part.g.data, asn1.Ber.Integer); + der.endSequence(); - return Math.floor(exports.now(localtimeOffsetMsec) / 1000); -}; + der.endSequence(); + der.startSequence(asn1.Ber.OctetString); + der.writeBuffer(key.part.x.data, asn1.Ber.Integer); + der.endSequence(); +} -internals.authHeaderRegex = /^(\w+)(?:\s+(.*))?$/; // Header: scheme[ something] -internals.attributeRegex = /^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/; // !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9 +function writePkcs8DSAPublic(key, der) { + der.startSequence(); + der.writeBuffer(key.part.p.data, asn1.Ber.Integer); + der.writeBuffer(key.part.q.data, asn1.Ber.Integer); + der.writeBuffer(key.part.g.data, asn1.Ber.Integer); + der.endSequence(); + der.endSequence(); + der.startSequence(asn1.Ber.BitString); + der.writeByte(0x00); + der.writeBuffer(key.part.y.data, asn1.Ber.Integer); + der.endSequence(); +} -// Parse Hawk HTTP Authorization header - -exports.parseAuthorizationHeader = function (header, keys) { +function writeECDSACurve(key, der) { + var curve = algs.curves[key.curve]; + if (curve.pkcs8oid) { + /* This one has a name in pkcs#8, so just write the oid */ + der.writeOID(curve.pkcs8oid); - keys = keys || ['id', 'ts', 'nonce', 'hash', 'ext', 'mac', 'app', 'dlg']; + } else { + // ECParameters sequence + der.startSequence(); - if (!header) { - return Boom.unauthorized(null, 'Hawk'); - } + var version = new Buffer(1); + version.writeUInt8(1, 0); + der.writeBuffer(version, asn1.Ber.Integer); - if (header.length > exports.limits.maxMatchLength) { - return Boom.badRequest('Header length too long'); - } + // FieldID sequence + der.startSequence(); + der.writeOID('1.2.840.10045.1.1'); // prime-field + der.writeBuffer(curve.p, asn1.Ber.Integer); + der.endSequence(); - var headerParts = header.match(internals.authHeaderRegex); - if (!headerParts) { - return Boom.badRequest('Invalid header syntax'); - } + // Curve sequence + der.startSequence(); + var a = curve.p; + if (a[0] === 0x0) + a = a.slice(1); + der.writeBuffer(a, asn1.Ber.OctetString); + der.writeBuffer(curve.b, asn1.Ber.OctetString); + der.writeBuffer(curve.s, asn1.Ber.BitString); + der.endSequence(); - var scheme = headerParts[1]; - if (scheme.toLowerCase() !== 'hawk') { - return Boom.unauthorized(null, 'Hawk'); - } + der.writeBuffer(curve.G, asn1.Ber.OctetString); + der.writeBuffer(curve.n, asn1.Ber.Integer); + var h = curve.h; + if (!h) { + h = new Buffer(1); + h[0] = 1; + } + der.writeBuffer(h, asn1.Ber.Integer); - var attributesString = headerParts[2]; - if (!attributesString) { - return Boom.badRequest('Invalid header syntax'); - } + // ECParameters + der.endSequence(); + } +} - var attributes = {}; - var errorMessage = ''; - var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) { +function writePkcs8ECDSAPublic(key, der) { + writeECDSACurve(key, der); + der.endSequence(); - // Check valid attribute names + var Q = utils.ecNormalize(key.part.Q.data, true); + der.writeBuffer(Q, asn1.Ber.BitString); +} - if (keys.indexOf($1) === -1) { - errorMessage = 'Unknown attribute: ' + $1; - return; - } +function writePkcs8ECDSAPrivate(key, der) { + writeECDSACurve(key, der); + der.endSequence(); - // Allowed attribute value characters + der.startSequence(asn1.Ber.OctetString); + der.startSequence(); - if ($2.match(internals.attributeRegex) === null) { - errorMessage = 'Bad attribute value: ' + $1; - return; - } + var version = new Buffer(1); + version[0] = 1; + der.writeBuffer(version, asn1.Ber.Integer); - // Check for duplicates + der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); - if (attributes.hasOwnProperty($1)) { - errorMessage = 'Duplicate attribute: ' + $1; - return; - } + der.startSequence(0xa1); + var Q = utils.ecNormalize(key.part.Q.data, true); + der.writeBuffer(Q, asn1.Ber.BitString); + der.endSequence(); - attributes[$1] = $2; - return ''; - }); + der.endSequence(); + der.endSequence(); +} - if (verify !== '') { - return Boom.badRequest(errorMessage || 'Bad header format'); - } - return attributes; -}; +/***/ }), +/* 118 */ +/***/ (function(module, exports, __webpack_require__) { +// Copyright 2017 Joyent, Inc. -exports.unauthorized = function (message, attributes) { +module.exports = Identity; - return Boom.unauthorized(message, 'Hawk', attributes); -}; +var assert = __webpack_require__(11); +var algs = __webpack_require__(23); +var crypto = __webpack_require__(8); +var Fingerprint = __webpack_require__(116); +var Signature = __webpack_require__(45); +var errs = __webpack_require__(44); +var util = __webpack_require__(2); +var utils = __webpack_require__(17); +var asn1 = __webpack_require__(50); +/*JSSTYLED*/ +var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i; +var oids = {}; +oids.cn = '2.5.4.3'; +oids.o = '2.5.4.10'; +oids.ou = '2.5.4.11'; +oids.l = '2.5.4.7'; +oids.s = '2.5.4.8'; +oids.c = '2.5.4.6'; +oids.sn = '2.5.4.4'; +oids.dc = '0.9.2342.19200300.100.1.25'; +oids.uid = '0.9.2342.19200300.100.1.1'; +oids.mail = '0.9.2342.19200300.100.1.3'; -/***/ }), -/* 95 */ -/***/ (function(module, exports, __webpack_require__) { +var unoids = {}; +Object.keys(oids).forEach(function (k) { + unoids[oids[k]] = k; +}); -// Load modules +function Identity(opts) { + var self = this; + assert.object(opts, 'options'); + assert.arrayOfObject(opts.components, 'options.components'); + this.components = opts.components; + this.componentLookup = {}; + this.components.forEach(function (c) { + if (c.name && !c.oid) + c.oid = oids[c.name]; + if (c.oid && !c.name) + c.name = unoids[c.oid]; + if (self.componentLookup[c.name] === undefined) + self.componentLookup[c.name] = []; + self.componentLookup[c.name].push(c); + }); + if (this.componentLookup.cn && this.componentLookup.cn.length > 0) { + this.cn = this.componentLookup.cn[0].value; + } + assert.optionalString(opts.type, 'options.type'); + if (opts.type === undefined) { + if (this.components.length === 1 && + this.componentLookup.cn && + this.componentLookup.cn.length === 1 && + this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { + this.type = 'host'; + this.hostname = this.componentLookup.cn[0].value; -var Crypto = __webpack_require__(7); -var Path = __webpack_require__(1); -var Util = __webpack_require__(2); -var Escape = __webpack_require__(509); + } else if (this.componentLookup.dc && + this.components.length === this.componentLookup.dc.length) { + this.type = 'host'; + this.hostname = this.componentLookup.dc.map( + function (c) { + return (c.value); + }).join('.'); + } else if (this.componentLookup.uid && + this.components.length === + this.componentLookup.uid.length) { + this.type = 'user'; + this.uid = this.componentLookup.uid[0].value; -// Declare internals + } else if (this.componentLookup.cn && + this.componentLookup.cn.length === 1 && + this.componentLookup.cn[0].value.match(DNS_NAME_RE)) { + this.type = 'host'; + this.hostname = this.componentLookup.cn[0].value; -var internals = {}; + } else if (this.componentLookup.uid && + this.componentLookup.uid.length === 1) { + this.type = 'user'; + this.uid = this.componentLookup.uid[0].value; + } else if (this.componentLookup.mail && + this.componentLookup.mail.length === 1) { + this.type = 'email'; + this.email = this.componentLookup.mail[0].value; -// Clone object or array + } else if (this.componentLookup.cn && + this.componentLookup.cn.length === 1) { + this.type = 'user'; + this.uid = this.componentLookup.cn[0].value; -exports.clone = function (obj, seen) { + } else { + this.type = 'unknown'; + } + } else { + this.type = opts.type; + if (this.type === 'host') + this.hostname = opts.hostname; + else if (this.type === 'user') + this.uid = opts.uid; + else if (this.type === 'email') + this.email = opts.email; + else + throw (new Error('Unknown type ' + this.type)); + } +} - if (typeof obj !== 'object' || - obj === null) { +Identity.prototype.toString = function () { + return (this.components.map(function (c) { + return (c.name.toUpperCase() + '=' + c.value); + }).join(', ')); +}; - return obj; - } +/* + * These are from X.680 -- PrintableString allowed chars are in section 37.4 + * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to + * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006 + * (the basic ASCII character set). + */ +/* JSSTYLED */ +var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/; +/* JSSTYLED */ +var NOT_IA5 = /[^\x00-\x7f]/; - seen = seen || { orig: [], copy: [] }; +Identity.prototype.toAsn1 = function (der, tag) { + der.startSequence(tag); + this.components.forEach(function (c) { + der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set); + der.startSequence(); + der.writeOID(c.oid); + /* + * If we fit in a PrintableString, use that. Otherwise use an + * IA5String or UTF8String. + */ + if (c.value.match(NOT_IA5)) { + var v = new Buffer(c.value, 'utf8'); + der.writeBuffer(v, asn1.Ber.Utf8String); + } else if (c.value.match(NOT_PRINTABLE)) { + der.writeString(c.value, asn1.Ber.IA5String); + } else { + der.writeString(c.value, asn1.Ber.PrintableString); + } + der.endSequence(); + der.endSequence(); + }); + der.endSequence(); +}; - var lookup = seen.orig.indexOf(obj); - if (lookup !== -1) { - return seen.copy[lookup]; - } +function globMatch(a, b) { + if (a === '**' || b === '**') + return (true); + var aParts = a.split('.'); + var bParts = b.split('.'); + if (aParts.length !== bParts.length) + return (false); + for (var i = 0; i < aParts.length; ++i) { + if (aParts[i] === '*' || bParts[i] === '*') + continue; + if (aParts[i] !== bParts[i]) + return (false); + } + return (true); +} - var newObj; - var cloneDeep = false; +Identity.prototype.equals = function (other) { + if (!Identity.isIdentity(other, [1, 0])) + return (false); + if (other.components.length !== this.components.length) + return (false); + for (var i = 0; i < this.components.length; ++i) { + if (this.components[i].oid !== other.components[i].oid) + return (false); + if (!globMatch(this.components[i].value, + other.components[i].value)) { + return (false); + } + } + return (true); +}; - if (!Array.isArray(obj)) { - if (Buffer.isBuffer(obj)) { - newObj = new Buffer(obj); - } - else if (obj instanceof Date) { - newObj = new Date(obj.getTime()); - } - else if (obj instanceof RegExp) { - newObj = new RegExp(obj); - } - else { - var proto = Object.getPrototypeOf(obj); - if (proto && - proto.isImmutable) { +Identity.forHost = function (hostname) { + assert.string(hostname, 'hostname'); + return (new Identity({ + type: 'host', + hostname: hostname, + components: [ { name: 'cn', value: hostname } ] + })); +}; - newObj = obj; - } - else { - newObj = Object.create(proto); - cloneDeep = true; - } - } - } - else { - newObj = []; - cloneDeep = true; - } +Identity.forUser = function (uid) { + assert.string(uid, 'uid'); + return (new Identity({ + type: 'user', + uid: uid, + components: [ { name: 'uid', value: uid } ] + })); +}; - seen.orig.push(obj); - seen.copy.push(newObj); +Identity.forEmail = function (email) { + assert.string(email, 'email'); + return (new Identity({ + type: 'email', + email: email, + components: [ { name: 'mail', value: email } ] + })); +}; - if (cloneDeep) { - var keys = Object.getOwnPropertyNames(obj); - for (var i = 0, il = keys.length; i < il; ++i) { - var key = keys[i]; - var descriptor = Object.getOwnPropertyDescriptor(obj, key); - if (descriptor && - (descriptor.get || - descriptor.set)) { +Identity.parseDN = function (dn) { + assert.string(dn, 'dn'); + var parts = dn.split(','); + var cmps = parts.map(function (c) { + c = c.trim(); + var eqPos = c.indexOf('='); + var name = c.slice(0, eqPos).toLowerCase(); + var value = c.slice(eqPos + 1); + return ({ name: name, value: value }); + }); + return (new Identity({ components: cmps })); +}; - Object.defineProperty(newObj, key, descriptor); - } - else { - newObj[key] = exports.clone(obj[key], seen); - } - } - } +Identity.parseAsn1 = function (der, top) { + var components = []; + der.readSequence(top); + var end = der.offset + der.length; + while (der.offset < end) { + der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set); + var after = der.offset + der.length; + der.readSequence(); + var oid = der.readOID(); + var type = der.peek(); + var value; + switch (type) { + case asn1.Ber.PrintableString: + case asn1.Ber.IA5String: + case asn1.Ber.OctetString: + case asn1.Ber.T61String: + value = der.readString(type); + break; + case asn1.Ber.Utf8String: + value = der.readString(type, true); + value = value.toString('utf8'); + break; + case asn1.Ber.CharacterString: + case asn1.Ber.BMPString: + value = der.readString(type, true); + value = value.toString('utf16le'); + break; + default: + throw (new Error('Unknown asn1 type ' + type)); + } + components.push({ oid: oid, value: value }); + der._offset = after; + } + der._offset = end; + return (new Identity({ + components: components + })); +}; - return newObj; +Identity.isIdentity = function (obj, ver) { + return (utils.isCompatible(obj, Identity, ver)); }; +/* + * API versions for Identity: + * [1,0] -- initial ver + */ +Identity.prototype._sshpkApiVersion = [1, 0]; -// Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied -/*eslint-disable */ -exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) { -/*eslint-enable */ - exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object'); - exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object'); +Identity._oldVersionDetect = function (obj) { + return ([1, 0]); +}; - if (!source) { - return target; - } - if (Array.isArray(source)) { - exports.assert(Array.isArray(target), 'Cannot merge array onto an object'); - if (isMergeArrays === false) { // isMergeArrays defaults to true - target.length = 0; // Must not change target assignment - } +/***/ }), +/* 119 */ +/***/ (function(module, exports, __webpack_require__) { - for (var i = 0, il = source.length; i < il; ++i) { - target.push(exports.clone(source[i])); - } +"use strict"; - return target; - } +module.exports = x => { + if (typeof x !== 'string') { + throw new TypeError('Expected a string, got ' + typeof x); + } - var keys = Object.keys(source); - for (var k = 0, kl = keys.length; k < kl; ++k) { - var key = keys[k]; - var value = source[key]; - if (value && - typeof value === 'object') { + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (x.charCodeAt(0) === 0xFEFF) { + return x.slice(1); + } - if (!target[key] || - typeof target[key] !== 'object' || - (Array.isArray(target[key]) ^ Array.isArray(value)) || - value instanceof Date || - Buffer.isBuffer(value) || - value instanceof RegExp) { + return x; +}; - target[key] = exports.clone(value); - } - else { - exports.merge(target[key], value, isNullOverride, isMergeArrays); - } - } - else { - if (value !== null && - value !== undefined) { // Explicit to preserve empty strings - target[key] = value; - } - else if (isNullOverride !== false) { // Defaults to true - target[key] = value; - } - } - } +/***/ }), +/* 120 */ +/***/ (function(module, exports) { - return target; -}; +module.exports = require("buffer"); +/***/ }), +/* 121 */ +/***/ (function(module, exports, __webpack_require__) { -// Apply options to a copy of the defaults +"use strict"; -exports.applyToDefaults = function (defaults, options, isNullOverride) { - exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object'); - exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object'); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.Add = undefined; - if (!options) { // If no options, return null - return null; - } +var _asyncToGenerator2; - var copy = exports.clone(defaults); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - if (options === true) { // If options is set to true, use defaults - return copy; +let run = exports.run = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (!args.length) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('missingAddDependencies')); } - return exports.merge(copy, options, isNullOverride === true, false); -}; + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder, reporter); + yield (0, (_install || _load_install()).wrapLifecycle)(config, flags, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const install = new Add(args, flags, config, reporter, lockfile); + yield install.init(); + })); + }); -// Clone an object except for the listed keys which are shallow copied + return function run(_x, _x2, _x3, _x4) { + return _ref2.apply(this, arguments); + }; +})(); -exports.cloneWithShallow = function (source, keys) { +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; - if (!source || - typeof source !== 'object') { +var _lockfile; - return source; - } +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} - var storage = internals.store(source, keys); // Move shallow copy items to storage - var copy = exports.clone(source); // Deep copy the rest - internals.restore(copy, source, storage); // Shallow copy the stored items and restore - return copy; -}; +var _normalizePattern2; +function _load_normalizePattern() { + return _normalizePattern2 = __webpack_require__(30); +} -internals.store = function (source, keys) { +var _workspaceLayout; - var storage = {}; - for (var i = 0, il = keys.length; i < il; ++i) { - var key = keys[i]; - var value = exports.reach(source, key); - if (value !== undefined) { - storage[key] = value; - internals.reachSet(source, key, undefined); - } - } +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(80)); +} - return storage; -}; +var _index; +function _load_index() { + return _index = __webpack_require__(35); +} -internals.restore = function (copy, source, storage) { +var _list; - var keys = Object.keys(storage); - for (var i = 0, il = keys.length; i < il; ++i) { - var key = keys[i]; - internals.reachSet(copy, key, storage[key]); - internals.reachSet(source, key, storage[key]); - } -}; +function _load_list() { + return _list = __webpack_require__(256); +} +var _install; -internals.reachSet = function (obj, key, value) { +function _load_install() { + return _install = __webpack_require__(31); +} - var path = key.split('.'); - var ref = obj; - for (var i = 0, il = path.length; i < il; ++i) { - var segment = path[i]; - if (i + 1 === il) { - ref[segment] = value; - } +var _errors; - ref = ref[segment]; - } -}; +function _load_errors() { + return _errors = __webpack_require__(3); +} +var _constants; -// Apply options to defaults except for the listed keys which are shallow copied from option without merging +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} -exports.applyToDefaultsWithShallow = function (defaults, options, keys) { +var _fs; - exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object'); - exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object'); - exports.assert(keys && Array.isArray(keys), 'Invalid keys'); +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - if (!options) { // If no options, return null - return null; - } +var _invariant; - var copy = exports.cloneWithShallow(defaults, keys); +function _load_invariant() { + return _invariant = _interopRequireDefault(__webpack_require__(7)); +} - if (options === true) { // If options is set to true, use defaults - return copy; - } +var _path; - var storage = internals.store(options, keys); // Move shallow copy items to storage - exports.merge(copy, options, false, false); // Deep copy the rest - internals.restore(copy, options, storage); // Shallow copy the stored items and restore - return copy; -}; +function _load_path() { + return _path = _interopRequireDefault(__webpack_require__(0)); +} +var _semver; -// Deep object or array comparison +function _load_semver() { + return _semver = _interopRequireDefault(__webpack_require__(22)); +} -exports.deepEqual = function (obj, ref, options, seen) { +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - options = options || { prototype: true }; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var type = typeof obj; +class Add extends (_install || _load_install()).Install { + constructor(args, flags, config, reporter, lockfile) { + super(flags, config, reporter, lockfile); + this.args = args; + // only one flag is supported, so we can figure out which one was passed to `yarn add` + this.flagToOrigin = [flags.dev && 'devDependencies', flags.optional && 'optionalDependencies', flags.peer && 'peerDependencies', 'dependencies'].filter(Boolean).shift(); - if (type !== typeof ref) { - return false; + if (this.config.workspaceRootFolder && this.config.cwd === this.config.workspaceRootFolder) { + this.setIgnoreWorkspaces(true); + // flagsToOrgin defaults to being a hard `dependency` when no flags are passed (see above), + // so it incorrectly throws a warning when upgrading existing devDependencies in workspace root + // To allow for a successful upgrade, override flagsToOrigin when `existing` flag is passed by `upgrade` command + if (flags.existing) { + this.flagToOrigin = ''; + } } + } - if (type !== 'object' || - obj === null || - ref === null) { - - if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql - return obj !== 0 || 1 / obj === 1 / ref; // -0 / +0 - } + /** + * TODO + */ - return obj !== obj && ref !== ref; // NaN - } + prepareRequests(requests) { + const requestsWithArgs = requests.slice(); - seen = seen || []; - if (seen.indexOf(obj) !== -1) { - return true; // If previous comparison failed, it would have stopped execution + for (const pattern of this.args) { + requestsWithArgs.push({ + pattern, + registry: 'npm', + optional: false + }); } + return requestsWithArgs; + } - seen.push(obj); - - if (Array.isArray(obj)) { - if (!Array.isArray(ref)) { - return false; - } + /** + * returns version for a pattern based on Manifest + */ + getPatternVersion(pattern, pkg) { + var _flags = this.flags; + const exact = _flags.exact, + tilde = _flags.tilde; - if (!options.part && obj.length !== ref.length) { - return false; - } + var _normalizePattern = (0, (_normalizePattern2 || _load_normalizePattern()).normalizePattern)(pattern); - for (var i = 0, il = obj.length; i < il; ++i) { - if (options.part) { - var found = false; - for (var r = 0, rl = ref.length; r < rl; ++r) { - if (exports.deepEqual(obj[i], ref[r], options, seen)) { - found = true; - break; - } - } + const hasVersion = _normalizePattern.hasVersion, + range = _normalizePattern.range; - return found; - } + let version; - if (!exports.deepEqual(obj[i], ref[i], options, seen)) { - return false; - } - } + if ((0, (_index || _load_index()).getExoticResolver)(pattern)) { + // wasn't a name/range tuple so this is just a raw exotic pattern + version = pattern; + } else if (hasVersion && range && ((_semver || _load_semver()).default.satisfies(pkg.version, range) || (0, (_index || _load_index()).getExoticResolver)(range))) { + // if the user specified a range then use it verbatim + version = range; + } else { + let prefix; + if (tilde) { + prefix = '~'; + } else if (exact) { + prefix = ''; + } else { + prefix = String(this.config.getOption('save-prefix')) || '^'; + } - return true; + version = `${prefix}${pkg.version}`; } + return version; + } - if (Buffer.isBuffer(obj)) { - if (!Buffer.isBuffer(ref)) { - return false; - } - - if (obj.length !== ref.length) { - return false; - } + preparePatterns(patterns) { + const preparedPatterns = patterns.slice(); + for (const pattern of this.resolver.dedupePatterns(this.args)) { + const pkg = this.resolver.getResolvedPattern(pattern); + (0, (_invariant || _load_invariant()).default)(pkg, `missing package ${pattern}`); + const version = this.getPatternVersion(pattern, pkg); + const newPattern = `${pkg.name}@${version}`; + preparedPatterns.push(newPattern); + this.addedPatterns.push(newPattern); + if (newPattern === pattern) { + continue; + } + this.resolver.replacePattern(pattern, newPattern); + } + return preparedPatterns; + } - for (var j = 0, jl = obj.length; j < jl; ++j) { - if (obj[j] !== ref[j]) { - return false; - } - } + bailout(patterns, workspaceLayout) { + var _this = this; - return true; - } + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const lockfileCache = _this.lockfile.cache; + if (!lockfileCache) { + return false; + } + const match = yield _this.integrityChecker.check(patterns, lockfileCache, _this.flags, workspaceLayout); + const haveLockfile = yield (_fs || _load_fs()).exists((_path || _load_path()).default.join(_this.config.lockfileFolder, (_constants || _load_constants()).LOCKFILE_FILENAME)); + if (match.integrityFileMissing && haveLockfile) { + // Integrity file missing, force script installations + _this.scripts.setForce(true); + } + return false; + })(); + } - if (obj instanceof Date) { - return (ref instanceof Date && obj.getTime() === ref.getTime()); - } + /** + * Description + */ - if (obj instanceof RegExp) { - return (ref instanceof RegExp && obj.toString() === ref.toString()); - } + init() { + var _this2 = this; - if (options.prototype) { - if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) { - return false; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (_this2.ignoreWorkspaces) { + if (_this2.flagToOrigin === 'dependencies') { + throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('workspacesPreferDevDependencies')); } - } + } - var keys = Object.getOwnPropertyNames(obj); + _this2.addedPatterns = []; + const patterns = yield (_install || _load_install()).Install.prototype.init.call(_this2); + yield _this2.maybeOutputSaveTree(patterns); + yield _this2.savePackages(); + return patterns; + })(); + } - if (!options.part && keys.length !== Object.getOwnPropertyNames(ref).length) { - return false; - } + /** + * Description + */ - for (var k = 0, kl = keys.length; k < kl; ++k) { - var key = keys[k]; - var descriptor = Object.getOwnPropertyDescriptor(obj, key); - if (descriptor.get) { - if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), options, seen)) { - return false; - } - } - else if (!exports.deepEqual(obj[key], ref[key], options, seen)) { - return false; - } - } + fetchRequestFromCwd() { + return (_install || _load_install()).Install.prototype.fetchRequestFromCwd.call(this, this.args); + } - return true; -}; + /** + * Output a tree of any newly added dependencies. + */ + maybeOutputSaveTree(patterns) { + var _this3 = this; -// Remove duplicate items from array + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // don't limit the shown tree depth + const opts = { + reqDepth: 0 + }; -exports.unique = function (array, key) { + var _ref = yield (0, (_list || _load_list()).buildTree)(_this3.resolver, _this3.linker, patterns, opts, true, true); - var index = {}; - var result = []; + const trees = _ref.trees, + count = _ref.count; - for (var i = 0, il = array.length; i < il; ++i) { - var id = (key ? array[i][key] : array[i]); - if (index[id] !== true) { + _this3.reporter.success(count === 1 ? _this3.reporter.lang('savedNewDependency') : _this3.reporter.lang('savedNewDependencies', count)); + _this3.reporter.tree('newDependencies', trees); + })(); + } - result.push(array[i]); - index[id] = true; - } - } + /** + * Save added packages to manifest if any of the --save flags were used. + */ - return result; -}; + savePackages() { + var _this4 = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // fill rootPatternsToOrigin without `excludePatterns` + yield (_install || _load_install()).Install.prototype.fetchRequestFromCwd.call(_this4); + const patternOrigins = Object.keys(_this4.rootPatternsToOrigin); -// Convert array into object + // get all the different registry manifests in this folder + const manifests = yield _this4.config.getRootManifests(); -exports.mapToObject = function (array, key) { + // add new patterns to their appropriate registry manifest + for (const pattern of _this4.addedPatterns) { + const pkg = _this4.resolver.getResolvedPattern(pattern); + (0, (_invariant || _load_invariant()).default)(pkg, `missing package ${pattern}`); + const version = _this4.getPatternVersion(pattern, pkg); + const ref = pkg._reference; + (0, (_invariant || _load_invariant()).default)(ref, 'expected package reference'); + // lookup the package to determine dependency type; used during `yarn upgrade` + const depType = patternOrigins.reduce(function (acc, prev) { + if (prev.indexOf(`${pkg.name}@`) === 0) { + return _this4.rootPatternsToOrigin[prev]; + } + return acc; + }, null); - if (!array) { - return null; - } + // depType is calculated when `yarn upgrade` command is used + const target = depType || _this4.flagToOrigin; - var obj = {}; - for (var i = 0, il = array.length; i < il; ++i) { - if (key) { - if (array[i][key]) { - obj[array[i][key]] = true; - } - } - else { - obj[array[i]] = true; - } - } + // add it to manifest + const object = manifests[ref.registry].object; - return obj; -}; + object[target] = object[target] || {}; + object[target][pkg.name] = version; + } -// Find the common unique items in two arrays + yield _this4.config.saveRootManifests(manifests); + })(); + } +} -exports.intersect = function (array1, array2, justFirst) { +exports.Add = Add; +function hasWrapper(commander) { + return true; +} - if (!array1 || !array2) { - return []; - } +function setFlags(commander) { + commander.usage('add [packages ...] [flags]'); + commander.option('-D, --dev', 'save package to your `devDependencies`'); + commander.option('-P, --peer', 'save package to your `peerDependencies`'); + commander.option('-O, --optional', 'save package to your `optionalDependencies`'); + commander.option('-E, --exact', 'install exact version'); + commander.option('-T, --tilde', 'install most recent release with the same minor version'); +} - var common = []; - var hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1); - var found = {}; - for (var i = 0, il = array2.length; i < il; ++i) { - if (hash[array2[i]] && !found[array2[i]]) { - if (justFirst) { - return array2[i]; - } +/***/ }), +/* 122 */ +/***/ (function(module, exports, __webpack_require__) { - common.push(array2[i]); - found[array2[i]] = true; - } - } +"use strict"; - return (justFirst ? null : common); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); -// Test if the reference contains the values +var _asyncToGenerator2; -exports.contain = function (ref, values, options) { +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - /* - string -> string(s) - array -> item(s) - object -> key(s) - object -> object (key:value) - */ +var _index; - var valuePairs = null; - if (typeof ref === 'object' && - typeof values === 'object' && - !Array.isArray(ref) && - !Array.isArray(values)) { +function _load_index() { + return _index = _interopRequireDefault(__webpack_require__(167)); +} - valuePairs = values; - values = Object.keys(values); - } - else { - values = [].concat(values); - } +var _constants; - options = options || {}; // deep, once, only, part +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} - exports.assert(arguments.length >= 2, 'Insufficient arguments'); - exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object'); - exports.assert(values.length, 'Values array cannot be empty'); +var _fs; - var compare, compareFlags; - if (options.deep) { - compare = exports.deepEqual; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - var hasOnly = options.hasOwnProperty('only'), hasPart = options.hasOwnProperty('part'); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - compareFlags = { - prototype: hasOnly ? options.only : hasPart ? !options.part : false, - part: hasOnly ? !options.only : hasPart ? options.part : true - }; - } - else { - compare = function (a, b) { +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return a === b; - }; - } +const path = __webpack_require__(0); +/* eslint no-unused-vars: 0 */ - var misses = false; - var matches = new Array(values.length); - for (var i = 0, il = matches.length; i < il; ++i) { - matches[i] = 0; - } +class BaseFetcher { + constructor(dest, remote, config) { + this.reporter = config.reporter; + this.packageName = remote.packageName; + this.reference = remote.reference; + this.registry = remote.registry; + this.hash = remote.hash; + this.remote = remote; + this.config = config; + this.dest = dest; + } - if (typeof ref === 'string') { - var pattern = '('; - for (i = 0, il = values.length; i < il; ++i) { - var value = values[i]; - exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value'); - pattern += (i ? '|' : '') + exports.escapeRegex(value); - } + setupMirrorFromCache() { + // fetcher subclasses may use this to perform actions such as copying over a cached tarball to the offline + // mirror etc + return Promise.resolve(); + } - var regex = new RegExp(pattern + ')', 'g'); - var leftovers = ref.replace(regex, function ($0, $1) { + _fetch() { + return Promise.reject(new Error('Not implemented')); + } - var index = values.indexOf($1); - ++matches[index]; - return ''; // Remove from string - }); + fetch(defaultManifest) { + var _this = this; - misses = !!leftovers; - } - else if (Array.isArray(ref)) { - for (i = 0, il = ref.length; i < il; ++i) { - for (var j = 0, jl = values.length, matched = false; j < jl && matched === false; ++j) { - matched = compare(values[j], ref[i], compareFlags) && j; - } + const dest = this.dest; - if (matched !== false) { - ++matches[matched]; - } - else { - misses = true; - } - } - } - else { - var keys = Object.keys(ref); - for (i = 0, il = keys.length; i < il; ++i) { - var key = keys[i]; - var pos = values.indexOf(key); - if (pos !== -1) { - if (valuePairs && - !compare(valuePairs[key], ref[key], compareFlags)) { + return (_fs || _load_fs()).lockQueue.push(dest, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield (_fs || _load_fs()).mkdirp(dest); - return false; - } + // fetch package and get the hash - ++matches[pos]; - } - else { - misses = true; - } - } - } + var _ref2 = yield _this._fetch(); - var result = false; - for (i = 0, il = matches.length; i < il; ++i) { - result = result || !!matches[i]; - if ((options.once && matches[i] > 1) || - (!options.part && !matches[i])) { + const hash = _ref2.hash; - return false; + + const pkg = yield (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // load the new normalized manifest + try { + return yield _this.config.readManifest(dest, _this.registry); + } catch (e) { + if (e.code === 'ENOENT' && defaultManifest) { + return (0, (_index || _load_index()).default)(defaultManifest, dest, _this.config, false); + } else { + throw e; + } } - } + })(); - if (options.only && - misses) { + yield (_fs || _load_fs()).writeFile(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME), JSON.stringify({ + manifest: pkg, + artifacts: [], + remote: _this.remote, + registry: _this.registry, + hash + }, null, ' ')); - return false; - } + return { + hash, + dest, + package: pkg, + cached: false + }; + })); + } +} +exports.default = BaseFetcher; - return result; -}; +/***/ }), +/* 123 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -// Flatten array -exports.flatten = function (array, target) { +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hash = hash; +const crypto = __webpack_require__(8); +const stream = __webpack_require__(26); - var result = target || []; +function hash(content) { + let type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'md5'; - for (var i = 0, il = array.length; i < il; ++i) { - if (Array.isArray(array[i])) { - exports.flatten(array[i], result); - } - else { - result.push(array[i]); - } - } + return crypto.createHash(type).update(content).digest('hex'); +} - return result; -}; +class HashStream extends stream.Transform { + constructor(options) { + super(options); + this._hash = crypto.createHash('sha1'); + this._updated = false; + } + _transform(chunk, encoding, callback) { + this._updated = true; + this._hash.update(chunk); + callback(null, chunk); + } -// Convert an object key chain string ('a.b.c') to reference (object[a][b][c]) + getHash() { + return this._hash.digest('hex'); + } -exports.reach = function (obj, chain, options) { + test(sum) { + return this._updated && sum === this.getHash(); + } +} +exports.HashStream = HashStream; - if (chain === false || - chain === null || - typeof chain === 'undefined') { +/***/ }), +/* 124 */ +/***/ (function(module, exports, __webpack_require__) { - return obj; - } +// Load modules - options = options || {}; - if (typeof options === 'string') { - options = { separator: options }; - } +var Http = __webpack_require__(49); +var Hoek = __webpack_require__(132); - var path = chain.split(options.separator || '.'); - var ref = obj; - for (var i = 0, il = path.length; i < il; ++i) { - var key = path[i]; - if (key[0] === '-' && Array.isArray(ref)) { - key = key.slice(1, key.length); - key = ref.length - key; - } - if (!ref || - !ref.hasOwnProperty(key) || - (typeof ref !== 'object' && options.functions === false)) { // Only object and function can have properties +// Declare internals - exports.assert(!options.strict || i + 1 === il, 'Missing segment', key, 'in reach path ', chain); - exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain); - ref = options.default; - break; - } +var internals = {}; - ref = ref[key]; - } +exports.wrap = function (error, statusCode, message) { - return ref; + Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object'); + return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message)); }; -exports.reachTemplate = function (obj, template, options) { +exports.create = function (statusCode, message, data) { - return template.replace(/{([^}]+)}/g, function ($0, chain) { + return internals.create(statusCode, message, data, exports.create); +}; - var value = exports.reach(obj, chain, options); - return (value === undefined || value === null ? '' : value); - }); +internals.create = function (statusCode, message, data, ctor) { + + var error = new Error(message ? message : undefined); // Avoids settings null message + Error.captureStackTrace(error, ctor); // Filter the stack to our external API + error.data = data || null; + internals.initialize(error, statusCode); + return error; }; +internals.initialize = function (error, statusCode, message) { -exports.formatStack = function (stack) { + var numberCode = parseInt(statusCode, 10); + Hoek.assert(!isNaN(numberCode) && numberCode >= 400, 'First argument must be a number (400+):', statusCode); - var trace = []; - for (var i = 0, il = stack.length; i < il; ++i) { - var item = stack[i]; - trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]); + error.isBoom = true; + error.isServer = numberCode >= 500; + + if (!error.hasOwnProperty('data')) { + error.data = null; } - return trace; -}; + error.output = { + statusCode: numberCode, + payload: {}, + headers: {} + }; + error.reformat = internals.reformat; + error.reformat(); -exports.formatTrace = function (trace) { + if (!message && + !error.message) { - var display = []; + message = error.output.payload.error; + } - for (var i = 0, il = trace.length; i < il; ++i) { - var row = trace[i]; - display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')'); + if (message) { + error.message = (message + (error.message ? ': ' + error.message : '')); } - return display; + return error; }; -exports.callStack = function (slice) { - - // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - - var v8 = Error.prepareStackTrace; - Error.prepareStackTrace = function (err, stack) { +internals.reformat = function () { - return stack; - }; + this.output.payload.statusCode = this.output.statusCode; + this.output.payload.error = Http.STATUS_CODES[this.output.statusCode] || 'Unknown'; - var capture = {}; - Error.captureStackTrace(capture, arguments.callee); /*eslint no-caller:0 */ - var stack = capture.stack; + if (this.output.statusCode === 500) { + this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user + } + else if (this.message) { + this.output.payload.message = this.message; + } +}; - Error.prepareStackTrace = v8; - var trace = exports.formatStack(stack); +// 4xx Client Errors - if (slice) { - return trace.slice(slice); - } +exports.badRequest = function (message, data) { - return trace; + return internals.create(400, message, data, exports.badRequest); }; -exports.displayStack = function (slice) { +exports.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[]) - var trace = exports.callStack(slice === undefined ? 1 : slice + 1); + var err = internals.create(401, message, undefined, exports.unauthorized); - return exports.formatTrace(trace); -}; + if (!scheme) { + return err; + } + var wwwAuthenticate = ''; + var i = 0; + var il = 0; -exports.abortThrow = false; + if (typeof scheme === 'string') { + // function (message, scheme, attributes) -exports.abort = function (message, hideStack) { + wwwAuthenticate = scheme; - if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) { - throw new Error(message || 'Unknown error'); - } + if (attributes || message) { + err.output.payload.attributes = {}; + } - var stack = ''; - if (!hideStack) { - stack = exports.displayStack(1).join('\n\t'); - } - console.log('ABORT: ' + message + '\n\t' + stack); - process.exit(1); -}; + if (attributes) { + var names = Object.keys(attributes); + for (i = 0, il = names.length; i < il; ++i) { + var name = names[i]; + if (i) { + wwwAuthenticate += ','; + } + var value = attributes[name]; + if (value === null || + value === undefined) { // Value can be zero -exports.assert = function (condition /*, msg1, msg2, msg3 */) { + value = ''; + } + wwwAuthenticate += ' ' + name + '="' + Hoek.escapeHeaderAttribute(value.toString()) + '"'; + err.output.payload.attributes[name] = value; + } + } - if (condition) { - return; + if (message) { + if (attributes) { + wwwAuthenticate += ','; + } + wwwAuthenticate += ' error="' + Hoek.escapeHeaderAttribute(message) + '"'; + err.output.payload.attributes.error = message; + } + else { + err.isMissing = true; + } } + else { - if (arguments.length === 2 && arguments[1] instanceof Error) { - throw arguments[1]; - } + // function (message, wwwAuthenticate[]) - var msgs = []; - for (var i = 1, il = arguments.length; i < il; ++i) { - if (arguments[i] !== '') { - msgs.push(arguments[i]); // Avoids Array.slice arguments leak, allowing for V8 optimizations + var wwwArray = scheme; + for (i = 0, il = wwwArray.length; i < il; ++i) { + if (i) { + wwwAuthenticate += ', '; + } + + wwwAuthenticate += wwwArray[i]; } } - msgs = msgs.map(function (msg) { + err.output.headers['WWW-Authenticate'] = wwwAuthenticate; - return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg); - }); - throw new Error(msgs.join(' ') || 'Unknown error'); + return err; }; -exports.Timer = function () { +exports.forbidden = function (message, data) { - this.ts = 0; - this.reset(); + return internals.create(403, message, data, exports.forbidden); }; -exports.Timer.prototype.reset = function () { +exports.notFound = function (message, data) { - this.ts = Date.now(); + return internals.create(404, message, data, exports.notFound); }; -exports.Timer.prototype.elapsed = function () { +exports.methodNotAllowed = function (message, data) { - return Date.now() - this.ts; + return internals.create(405, message, data, exports.methodNotAllowed); }; -exports.Bench = function () { +exports.notAcceptable = function (message, data) { - this.ts = 0; - this.reset(); + return internals.create(406, message, data, exports.notAcceptable); }; -exports.Bench.prototype.reset = function () { +exports.proxyAuthRequired = function (message, data) { - this.ts = exports.Bench.now(); + return internals.create(407, message, data, exports.proxyAuthRequired); }; -exports.Bench.prototype.elapsed = function () { +exports.clientTimeout = function (message, data) { - return exports.Bench.now() - this.ts; + return internals.create(408, message, data, exports.clientTimeout); }; -exports.Bench.now = function () { +exports.conflict = function (message, data) { - var ts = process.hrtime(); - return (ts[0] * 1e3) + (ts[1] / 1e6); + return internals.create(409, message, data, exports.conflict); }; -// Escape string for Regex construction - -exports.escapeRegex = function (string) { +exports.resourceGone = function (message, data) { - // Escape ^$.*+-?=!:|\/()[]{}, - return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); + return internals.create(410, message, data, exports.resourceGone); }; -// Base64url (RFC 4648) encode - -exports.base64urlEncode = function (value, encoding) { +exports.lengthRequired = function (message, data) { - var buf = (Buffer.isBuffer(value) ? value : new Buffer(value, encoding || 'binary')); - return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, ''); + return internals.create(411, message, data, exports.lengthRequired); }; -// Base64url (RFC 4648) decode +exports.preconditionFailed = function (message, data) { -exports.base64urlDecode = function (value, encoding) { + return internals.create(412, message, data, exports.preconditionFailed); +}; - if (value && - !/^[\w\-]*$/.test(value)) { - return new Error('Invalid character'); - } +exports.entityTooLarge = function (message, data) { - try { - var buf = new Buffer(value, 'base64'); - return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary')); - } - catch (err) { - return err; - } + return internals.create(413, message, data, exports.entityTooLarge); }; -// Escape attribute value for use in HTTP header +exports.uriTooLong = function (message, data) { -exports.escapeHeaderAttribute = function (attribute) { + return internals.create(414, message, data, exports.uriTooLong); +}; - // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, " - exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')'); +exports.unsupportedMediaType = function (message, data) { - return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash + return internals.create(415, message, data, exports.unsupportedMediaType); }; -exports.escapeHtml = function (string) { +exports.rangeNotSatisfiable = function (message, data) { - return Escape.escapeHtml(string); + return internals.create(416, message, data, exports.rangeNotSatisfiable); }; -exports.escapeJavaScript = function (string) { +exports.expectationFailed = function (message, data) { - return Escape.escapeJavaScript(string); + return internals.create(417, message, data, exports.expectationFailed); }; +exports.badData = function (message, data) { -exports.nextTick = function (callback) { + return internals.create(422, message, data, exports.badData); +}; - return function () { - var args = arguments; - process.nextTick(function () { +exports.preconditionRequired = function (message, data) { - callback.apply(null, args); - }); - }; + return internals.create(428, message, data, exports.preconditionRequired); }; -exports.once = function (method) { +exports.tooManyRequests = function (message, data) { - if (method._hoekOnce) { - return method; - } + return internals.create(429, message, data, exports.tooManyRequests); +}; - var once = false; - var wrapped = function () { - if (!once) { - once = true; - method.apply(null, arguments); - } - }; +// 5xx Server Errors - wrapped._hoekOnce = true; +exports.internal = function (message, data, statusCode) { - return wrapped; + return internals.serverError(message, data, statusCode, exports.internal); }; +internals.serverError = function (message, data, statusCode, ctor) { -exports.isAbsolutePath = function (path, platform) { - - if (!path) { - return false; - } - - if (Path.isAbsolute) { // node >= 0.11 - return Path.isAbsolute(path); + var error; + if (data instanceof Error) { + error = exports.wrap(data, statusCode, message); + } else { + error = internals.create(statusCode || 500, message, undefined, ctor); + error.data = data; } - platform = platform || process.platform; - - // Unix + return error; +}; - if (platform !== 'win32') { - return path[0] === '/'; - } - // Windows +exports.notImplemented = function (message, data) { - return !!/^(?:[a-zA-Z]:[\\\/])|(?:[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/])/.test(path); // C:\ or \\something\something + return internals.serverError(message, data, 501, exports.notImplemented); }; -exports.isInteger = function (value) { +exports.badGateway = function (message, data) { - return (typeof value === 'number' && - parseFloat(value) === parseInt(value, 10) && - !isNaN(value)); + return internals.serverError(message, data, 502, exports.badGateway); }; -exports.ignore = function () { }; +exports.serverTimeout = function (message, data) { + return internals.serverError(message, data, 503, exports.serverTimeout); +}; -exports.inherits = Util.inherits; +exports.gatewayTimeout = function (message, data) { -exports.format = Util.format; + return internals.serverError(message, data, 504, exports.gatewayTimeout); +}; -exports.transform = function (source, transform, options) { +exports.badImplementation = function (message, data) { - exports.assert(source === null || source === undefined || typeof source === 'object' || Array.isArray(source), 'Invalid source object: must be null, undefined, an object, or an array'); + var err = internals.serverError(message, data, 500, exports.badImplementation); + err.isDeveloperError = true; + return err; +}; - if (Array.isArray(source)) { - var results = []; - for (var i = 0, il = source.length; i < il; ++i) { - results.push(exports.transform(source[i], transform, options)); - } - return results; - } - var result = {}; - var keys = Object.keys(transform); +/***/ }), +/* 125 */ +/***/ (function(module, exports, __webpack_require__) { - for (var k = 0, kl = keys.length; k < kl; ++k) { - var key = keys[k]; - var path = key.split('.'); - var sourcePath = transform[key]; +// fallback for non-array-like ES3 and non-enumerable old V8 strings +var cof = __webpack_require__(41); +module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ + return cof(it) == 'String' ? it.split('') : Object(it); +}; - exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings'); +/***/ }), +/* 126 */ +/***/ (function(module, exports, __webpack_require__) { - var segment; - var res = result; +// check on default Array iterator +var Iterators = __webpack_require__(32) + , ITERATOR = __webpack_require__(9)('iterator') + , ArrayProto = Array.prototype; - while (path.length > 1) { - segment = path.shift(); - if (!res[segment]) { - res[segment] = {}; - } - res = res[segment]; - } - segment = path.shift(); - res[segment] = exports.reach(source, sourcePath, options); - } +module.exports = function(it){ + return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); +}; - return result; +/***/ }), +/* 127 */ +/***/ (function(module, exports, __webpack_require__) { + +// call something on iterator step with safe closing on error +var anObject = __webpack_require__(27); +module.exports = function(iterator, fn, value, entries){ + try { + return entries ? fn(anObject(value)[0], value[1]) : fn(value); + // 7.4.6 IteratorClose(iterator, completion) + } catch(e){ + var ret = iterator['return']; + if(ret !== undefined)anObject(ret.call(iterator)); + throw e; + } }; +/***/ }), +/* 128 */ +/***/ (function(module, exports, __webpack_require__) { -exports.uniqueFilename = function (path, extension) { +var ITERATOR = __webpack_require__(9)('iterator') + , SAFE_CLOSING = false; - if (extension) { - extension = extension[0] !== '.' ? '.' + extension : extension; - } - else { - extension = ''; - } +try { + var riter = [7][ITERATOR](); + riter['return'] = function(){ SAFE_CLOSING = true; }; + Array.from(riter, function(){ throw 2; }); +} catch(e){ /* empty */ } - path = Path.resolve(path); - var name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension; - return Path.join(path, name); +module.exports = function(exec, skipClosing){ + if(!skipClosing && !SAFE_CLOSING)return false; + var safe = false; + try { + var arr = [7] + , iter = arr[ITERATOR](); + iter.next = function(){ return {done: safe = true}; }; + arr[ITERATOR] = function(){ return iter; }; + exec(arr); + } catch(e){ /* empty */ } + return safe; }; +/***/ }), +/* 129 */ +/***/ (function(module, exports, __webpack_require__) { -exports.stringify = function () { +// 19.1.2.14 / 15.2.3.14 Object.keys(O) +var $keys = __webpack_require__(191) + , enumBugKeys = __webpack_require__(100); - try { - return JSON.stringify.apply(null, arguments); - } - catch (err) { - return '[Cannot display object: ' + err.message + ']'; - } +module.exports = Object.keys || function keys(O){ + return $keys(O, enumBugKeys); }; +/***/ }), +/* 130 */ +/***/ (function(module, exports, __webpack_require__) { -exports.shallow = function (source) { +// Basic Javascript Elliptic Curve implementation +// Ported loosely from BouncyCastle's Java EC code +// Only Fp curves implemented for now - var target = {}; - var keys = Object.keys(source); - for (var i = 0, il = keys.length; i < il; ++i) { - var key = keys[i]; - target[key] = source[key]; - } +// Requires jsbn.js and jsbn2.js +var BigInteger = __webpack_require__(56).BigInteger +var Barrett = BigInteger.prototype.Barrett - return target; -}; +// ---------------- +// ECFieldElementFp +// constructor +function ECFieldElementFp(q,x) { + this.x = x; + // TODO if(x.compareTo(q) >= 0) error + this.q = q; +} -/***/ }), -/* 96 */ -/***/ (function(module, exports, __webpack_require__) { +function feFpEquals(other) { + if(other == this) return true; + return (this.q.equals(other.q) && this.x.equals(other.x)); +} -// Copyright 2012 Joyent, Inc. All rights reserved. +function feFpToBigInteger() { + return this.x; +} -var assert = __webpack_require__(97); -var sshpk = __webpack_require__(165); -var util = __webpack_require__(2); +function feFpNegate() { + return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)); +} -var HASH_ALGOS = { - 'sha1': true, - 'sha256': true, - 'sha512': true -}; +function feFpAdd(b) { + return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)); +} -var PK_ALGOS = { - 'rsa': true, - 'dsa': true, - 'ecdsa': true -}; +function feFpSubtract(b) { + return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)); +} -function HttpSignatureError(message, caller) { - if (Error.captureStackTrace) - Error.captureStackTrace(this, caller || HttpSignatureError); +function feFpMultiply(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)); +} - this.message = message; - this.name = caller.name; +function feFpSquare() { + return new ECFieldElementFp(this.q, this.x.square().mod(this.q)); } -util.inherits(HttpSignatureError, Error); -function InvalidAlgorithmError(message) { - HttpSignatureError.call(this, message, InvalidAlgorithmError); +function feFpDivide(b) { + return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)); } -util.inherits(InvalidAlgorithmError, HttpSignatureError); -function validateAlgorithm(algorithm) { - var alg = algorithm.toLowerCase().split('-'); +ECFieldElementFp.prototype.equals = feFpEquals; +ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger; +ECFieldElementFp.prototype.negate = feFpNegate; +ECFieldElementFp.prototype.add = feFpAdd; +ECFieldElementFp.prototype.subtract = feFpSubtract; +ECFieldElementFp.prototype.multiply = feFpMultiply; +ECFieldElementFp.prototype.square = feFpSquare; +ECFieldElementFp.prototype.divide = feFpDivide; - if (alg.length !== 2) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + - 'valid algorithm')); - } +// ---------------- +// ECPointFp - if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { - throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + - 'are not supported')); - } +// constructor +function ECPointFp(curve,x,y,z) { + this.curve = curve; + this.x = x; + this.y = y; + // Projective coordinates: either zinv == null or z * zinv == 1 + // z and zinv are just BigIntegers, not fieldElements + if(z == null) { + this.z = BigInteger.ONE; + } + else { + this.z = z; + } + this.zinv = null; + //TODO: compression flag +} - if (!HASH_ALGOS[alg[1]]) { - throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + - 'supported hash algorithm')); - } +function pointFpGetX() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.x.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); +} - return (alg); +function pointFpGetY() { + if(this.zinv == null) { + this.zinv = this.z.modInverse(this.curve.q); + } + var r = this.y.toBigInteger().multiply(this.zinv); + this.curve.reduce(r); + return this.curve.fromBigInteger(r); } -///--- API +function pointFpEquals(other) { + if(other == this) return true; + if(this.isInfinity()) return other.isInfinity(); + if(other.isInfinity()) return this.isInfinity(); + var u, v; + // u = Y2 * Z1 - Y1 * Z2 + u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q); + if(!u.equals(BigInteger.ZERO)) return false; + // v = X2 * Z1 - X1 * Z2 + v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q); + return v.equals(BigInteger.ZERO); +} -module.exports = { +function pointFpIsInfinity() { + if((this.x == null) && (this.y == null)) return true; + return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO); +} - HASH_ALGOS: HASH_ALGOS, - PK_ALGOS: PK_ALGOS, +function pointFpNegate() { + return new ECPointFp(this.curve, this.x, this.y.negate(), this.z); +} - HttpSignatureError: HttpSignatureError, - InvalidAlgorithmError: InvalidAlgorithmError, +function pointFpAdd(b) { + if(this.isInfinity()) return b; + if(b.isInfinity()) return this; - validateAlgorithm: validateAlgorithm, + // u = Y2 * Z1 - Y1 * Z2 + var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q); + // v = X2 * Z1 - X1 * Z2 + var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q); - /** - * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. - * - * The intent of this module is to interoperate with OpenSSL only, - * specifically the node crypto module's `verify` method. - * - * @param {String} key an OpenSSH public key. - * @return {String} PEM encoded form of the RSA public key. - * @throws {TypeError} on bad input. - * @throws {Error} on invalid ssh key formatted data. - */ - sshKeyToPEM: function sshKeyToPEM(key) { - assert.string(key, 'ssh_key'); + if(BigInteger.ZERO.equals(v)) { + if(BigInteger.ZERO.equals(u)) { + return this.twice(); // this == b, so double + } + return this.curve.getInfinity(); // this = -b, so infinity + } - var k = sshpk.parseKey(key, 'ssh'); - return (k.toString('pem')); - }, + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + var x2 = b.x.toBigInteger(); + var y2 = b.y.toBigInteger(); + var v2 = v.square(); + var v3 = v2.multiply(v); + var x1v2 = x1.multiply(v2); + var zu2 = u.square().multiply(this.z); - /** - * Generates an OpenSSH fingerprint from an ssh public key. - * - * @param {String} key an OpenSSH public key. - * @return {String} key fingerprint. - * @throws {TypeError} on bad input. - * @throws {Error} if what you passed doesn't look like an ssh public key. - */ - fingerprint: function fingerprint(key) { - assert.string(key, 'ssh_key'); + // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) + var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q); + // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 + var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q); + // z3 = v^3 * z1 * z2 + var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q); - var k = sshpk.parseKey(key, 'ssh'); - return (k.fingerprint('md5').toString('hex')); - }, + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); +} - /** - * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) - * - * The reverse of the above function. - */ - pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { - assert.equal('string', typeof (pem), 'typeof pem'); +function pointFpTwice() { + if(this.isInfinity()) return this; + if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity(); - var k = sshpk.parseKey(pem, 'pem'); - k.comment = comment; - return (k.toString('ssh')); - } -}; + // TODO: optimized handling of constants + var THREE = new BigInteger("3"); + var x1 = this.x.toBigInteger(); + var y1 = this.y.toBigInteger(); + var y1z1 = y1.multiply(this.z); + var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q); + var a = this.curve.a.toBigInteger(); -/***/ }), -/* 97 */ -/***/ (function(module, exports, __webpack_require__) { + // w = 3 * x1^2 + a * z1^2 + var w = x1.square().multiply(THREE); + if(!BigInteger.ZERO.equals(a)) { + w = w.add(this.z.square().multiply(a)); + } + w = w.mod(this.curve.q); + //this.curve.reduce(w); + // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) + var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q); + // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 + var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q); + // z3 = 8 * (y1 * z1)^3 + var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q); -// Copyright (c) 2012, Mark Cavage. All rights reserved. -// Copyright 2015 Joyent, Inc. + return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3); +} -var assert = __webpack_require__(22); -var Stream = __webpack_require__(20).Stream; -var util = __webpack_require__(2); +// Simple NAF (Non-Adjacent Form) multiplication algorithm +// TODO: modularize the multiplication algorithm +function pointFpMultiply(k) { + if(this.isInfinity()) return this; + if(k.signum() == 0) return this.curve.getInfinity(); + var e = k; + var h = e.multiply(new BigInteger("3")); -///--- Globals + var neg = this.negate(); + var R = this; -/* JSSTYLED */ -var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; + var i; + for(i = h.bitLength() - 2; i > 0; --i) { + R = R.twice(); + var hBit = h.testBit(i); + var eBit = e.testBit(i); -///--- Internal + if (hBit != eBit) { + R = R.add(hBit ? this : neg); + } + } -function _capitalize(str) { - return (str.charAt(0).toUpperCase() + str.slice(1)); + return R; } -function _toss(name, expected, oper, arg, actual) { - throw new assert.AssertionError({ - message: util.format('%s (%s) is required', name, expected), - actual: (actual === undefined) ? typeof (arg) : actual(arg), - expected: expected, - operator: oper || '===', - stackStartFunction: _toss.caller - }); +// Compute this*j + x*k (simultaneous multiplication) +function pointFpMultiplyTwo(j,x,k) { + var i; + if(j.bitLength() > k.bitLength()) + i = j.bitLength() - 1; + else + i = k.bitLength() - 1; + + var R = this.curve.getInfinity(); + var both = this.add(x); + while(i >= 0) { + R = R.twice(); + if(j.testBit(i)) { + if(k.testBit(i)) { + R = R.add(both); + } + else { + R = R.add(this); + } + } + else { + if(k.testBit(i)) { + R = R.add(x); + } + } + --i; + } + + return R; } -function _getClass(arg) { - return (Object.prototype.toString.call(arg).slice(8, -1)); +ECPointFp.prototype.getX = pointFpGetX; +ECPointFp.prototype.getY = pointFpGetY; +ECPointFp.prototype.equals = pointFpEquals; +ECPointFp.prototype.isInfinity = pointFpIsInfinity; +ECPointFp.prototype.negate = pointFpNegate; +ECPointFp.prototype.add = pointFpAdd; +ECPointFp.prototype.twice = pointFpTwice; +ECPointFp.prototype.multiply = pointFpMultiply; +ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo; + +// ---------------- +// ECCurveFp + +// constructor +function ECCurveFp(q,a,b) { + this.q = q; + this.a = this.fromBigInteger(a); + this.b = this.fromBigInteger(b); + this.infinity = new ECPointFp(this, null, null); + this.reducer = new Barrett(this.q); } -function noop() { - // Why even bother with asserts? +function curveFpGetQ() { + return this.q; } +function curveFpGetA() { + return this.a; +} -///--- Exports +function curveFpGetB() { + return this.b; +} -var types = { - bool: { - check: function (arg) { return typeof (arg) === 'boolean'; } - }, - func: { - check: function (arg) { return typeof (arg) === 'function'; } - }, - string: { - check: function (arg) { return typeof (arg) === 'string'; } - }, - object: { - check: function (arg) { - return typeof (arg) === 'object' && arg !== null; - } - }, - number: { - check: function (arg) { - return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); - } - }, - buffer: { - check: function (arg) { return Buffer.isBuffer(arg); }, - operator: 'Buffer.isBuffer' - }, - array: { - check: function (arg) { return Array.isArray(arg); }, - operator: 'Array.isArray' - }, - stream: { - check: function (arg) { return arg instanceof Stream; }, - operator: 'instanceof', - actual: _getClass - }, - date: { - check: function (arg) { return arg instanceof Date; }, - operator: 'instanceof', - actual: _getClass - }, - regexp: { - check: function (arg) { return arg instanceof RegExp; }, - operator: 'instanceof', - actual: _getClass - }, - uuid: { - check: function (arg) { - return typeof (arg) === 'string' && UUID_REGEXP.test(arg); - }, - operator: 'isUUID' - } -}; +function curveFpEquals(other) { + if(other == this) return true; + return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)); +} -function _setExports(ndebug) { - var keys = Object.keys(types); - var out; +function curveFpGetInfinity() { + return this.infinity; +} - /* re-export standard assert */ - if (process.env.NODE_NDEBUG) { - out = noop; - } else { - out = function (arg, msg) { - if (!arg) { - _toss(msg, 'true', arg); - } - }; - } +function curveFpFromBigInteger(x) { + return new ECFieldElementFp(this.q, x); +} - /* standard checks */ - keys.forEach(function (k) { - if (ndebug) { - out[k] = noop; - return; - } - var type = types[k]; - out[k] = function (arg, msg) { - if (!type.check(arg)) { - _toss(msg, k, type.operator, arg, type.actual); - } - }; - }); +function curveReduce(x) { + this.reducer.reduce(x); +} - /* optional checks */ - keys.forEach(function (k) { - var name = 'optional' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; - } - var type = types[k]; - out[name] = function (arg, msg) { - if (arg === undefined || arg === null) { - return; - } - if (!type.check(arg)) { - _toss(msg, k, type.operator, arg, type.actual); - } - }; - }); +// for now, work with hex strings because they're easier in JS +function curveFpDecodePointHex(s) { + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + case 3: + // point compression not supported yet + return null; + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); - /* arrayOf checks */ - keys.forEach(function (k) { - var name = 'arrayOf' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); + + default: // unsupported + return null; + } +} + +function curveFpEncodePointHex(p) { + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var yHex = p.getY().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) { + xHex = "0" + xHex; + } + while (yHex.length < oLen) { + yHex = "0" + yHex; + } + return "04" + xHex + yHex; +} + +ECCurveFp.prototype.getQ = curveFpGetQ; +ECCurveFp.prototype.getA = curveFpGetA; +ECCurveFp.prototype.getB = curveFpGetB; +ECCurveFp.prototype.equals = curveFpEquals; +ECCurveFp.prototype.getInfinity = curveFpGetInfinity; +ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger; +ECCurveFp.prototype.reduce = curveReduce; +//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex; +ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex; + +// from: https://github.com/kaielvin/jsbn-ec-point-compression +ECCurveFp.prototype.decodePointHex = function(s) +{ + var yIsEven; + switch(parseInt(s.substr(0,2), 16)) { // first byte + case 0: + return this.infinity; + case 2: + yIsEven = false; + case 3: + if(yIsEven == undefined) yIsEven = true; + var len = s.length - 2; + var xHex = s.substr(2, len); + var x = this.fromBigInteger(new BigInteger(xHex,16)); + var alpha = x.multiply(x.square().add(this.getA())).add(this.getB()); + var beta = alpha.sqrt(); + + if (beta == null) throw "Invalid point compression"; + + var betaValue = beta.toBigInteger(); + if (betaValue.testBit(0) != yIsEven) + { + // Use the other root + beta = this.fromBigInteger(this.getQ().subtract(betaValue)); + } + return new ECPointFp(this,x,beta); + case 4: + case 6: + case 7: + var len = (s.length - 2) / 2; + var xHex = s.substr(2, len); + var yHex = s.substr(len+2, len); + + return new ECPointFp(this, + this.fromBigInteger(new BigInteger(xHex, 16)), + this.fromBigInteger(new BigInteger(yHex, 16))); + + default: // unsupported + return null; + } +} +ECCurveFp.prototype.encodeCompressedPointHex = function(p) +{ + if (p.isInfinity()) return "00"; + var xHex = p.getX().toBigInteger().toString(16); + var oLen = this.getQ().toString(16).length; + if ((oLen % 2) != 0) oLen++; + while (xHex.length < oLen) + xHex = "0" + xHex; + var yPrefix; + if(p.getY().toBigInteger().isEven()) yPrefix = "02"; + else yPrefix = "03"; + + return yPrefix + xHex; +} + + +ECFieldElementFp.prototype.getR = function() +{ + if(this.r != undefined) return this.r; + + this.r = null; + var bitLength = this.q.bitLength(); + if (bitLength > 128) + { + var firstWord = this.q.shiftRight(bitLength - 64); + if (firstWord.intValue() == -1) + { + this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q); } - var type = types[k]; - var expected = '[' + k + ']'; - out[name] = function (arg, msg) { - if (!Array.isArray(arg)) { - _toss(msg, expected, type.operator, arg, type.actual); - } - var i; - for (i = 0; i < arg.length; i++) { - if (!type.check(arg[i])) { - _toss(msg, expected, type.operator, arg, type.actual); - } + } + return this.r; +} +ECFieldElementFp.prototype.modMult = function(x1,x2) +{ + return this.modReduce(x1.multiply(x2)); +} +ECFieldElementFp.prototype.modReduce = function(x) +{ + if (this.getR() != null) + { + var qLen = q.bitLength(); + while (x.bitLength() > (qLen + 1)) + { + var u = x.shiftRight(qLen); + var v = x.subtract(u.shiftLeft(qLen)); + if (!this.getR().equals(BigInteger.ONE)) + { + u = u.multiply(this.getR()); } - }; - }); + x = u.add(v); + } + while (x.compareTo(q) >= 0) + { + x = x.subtract(q); + } + } + else + { + x = x.mod(q); + } + return x; +} +ECFieldElementFp.prototype.sqrt = function() +{ + if (!this.q.testBit(0)) throw "unsupported"; - /* optionalArrayOf checks */ - keys.forEach(function (k) { - var name = 'optionalArrayOf' + _capitalize(k); - if (ndebug) { - out[name] = noop; - return; + // p mod 4 == 3 + if (this.q.testBit(1)) + { + var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q)); + return z.square().equals(this) ? z : null; + } + + // p mod 4 == 1 + var qMinusOne = this.q.subtract(BigInteger.ONE); + + var legendreExponent = qMinusOne.shiftRight(1); + if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE))) + { + return null; + } + + var u = qMinusOne.shiftRight(2); + var k = u.shiftLeft(1).add(BigInteger.ONE); + + var Q = this.x; + var fourQ = modDouble(modDouble(Q)); + + var U, V; + do + { + var P; + do + { + P = new BigInteger(this.q.bitLength(), new SecureRandom()); } - var type = types[k]; - var expected = '[' + k + ']'; - out[name] = function (arg, msg) { - if (arg === undefined || arg === null) { - return; - } - if (!Array.isArray(arg)) { - _toss(msg, expected, type.operator, arg, type.actual); - } - var i; - for (i = 0; i < arg.length; i++) { - if (!type.check(arg[i])) { - _toss(msg, expected, type.operator, arg, type.actual); - } + while (P.compareTo(this.q) >= 0 + || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne))); + + var result = this.lucasSequence(P, Q, k); + U = result[0]; + V = result[1]; + + if (this.modMult(V, V).equals(fourQ)) + { + // Integer division by 2, mod q + if (V.testBit(0)) + { + V = V.add(q); } - }; - }); - /* re-export built-in assertions */ - Object.keys(assert).forEach(function (k) { - if (k === 'AssertionError') { - out[k] = assert[k]; - return; + V = V.shiftRight(1); + + return new ECFieldElementFp(q,V); } - if (ndebug) { - out[k] = noop; - return; + } + while (U.equals(BigInteger.ONE) || U.equals(qMinusOne)); + + return null; +} +ECFieldElementFp.prototype.lucasSequence = function(P,Q,k) +{ + var n = k.bitLength(); + var s = k.getLowestSetBit(); + + var Uh = BigInteger.ONE; + var Vl = BigInteger.TWO; + var Vh = P; + var Ql = BigInteger.ONE; + var Qh = BigInteger.ONE; + + for (var j = n - 1; j >= s + 1; --j) + { + Ql = this.modMult(Ql, Qh); + + if (k.testBit(j)) + { + Qh = this.modMult(Ql, Q); + Uh = this.modMult(Uh, Vh); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); } - out[k] = assert[k]; - }); + else + { + Qh = Ql; + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + } + } - /* export ourselves (for unit tests _only_) */ - out._setExports = _setExports; + Ql = this.modMult(Ql, Qh); + Qh = this.modMult(Ql, Q); + Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql)); + Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); + Ql = this.modMult(Ql, Qh); - return out; + for (var j = 1; j <= s; ++j) + { + Uh = this.modMult(Uh, Vl); + Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); + Ql = this.modMult(Ql, Ql); + } + + return [ Uh, Vl ]; } -module.exports = _setExports(process.env.NODE_NDEBUG); +var exports = { + ECCurveFp: ECCurveFp, + ECPointFp: ECPointFp, + ECFieldElementFp: ECFieldElementFp +} + +module.exports = exports /***/ }), -/* 98 */ +/* 131 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Load modules -var chalk = __webpack_require__(15); -var figures = __webpack_require__(149); +var Sntp = __webpack_require__(315); +var Boom = __webpack_require__(124); -/** - * Separator object - * Used to space/separate choices group - * @constructor - * @param {String} line Separation line content (facultative) - */ -var Separator = module.exports = function (line) { - this.type = 'separator'; - this.line = chalk.dim(line || new Array(15).join(figures.line)); -}; +// Declare internals -/** - * Helper function returning false if object is a separator - * @param {Object} obj object to test against - * @return {Boolean} `false` if object is a separator - */ +var internals = {}; -Separator.exclude = function (obj) { - return obj.type !== 'separator'; + +exports.version = function () { + + return __webpack_require__(524).version; }; -/** - * Stringify separator - * @return {String} the separator display string - */ -Separator.prototype.toString = function () { - return this.line; +exports.limits = { + maxMatchLength: 4096 // Limit the length of uris and headers to avoid a DoS attack on string matching }; -/***/ }), -/* 99 */ -/***/ (function(module, exports, __webpack_require__) { +// Extract host and port from request -"use strict"; +// $1 $2 +internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/; // (IPv4, hostname)|(IPv6) -var _ = __webpack_require__(21); -var chalk = __webpack_require__(15); +exports.parseHost = function (req, hostHeaderName) { -/** - * The paginator keep trakcs of a pointer index in a list and return - * a subset of the choices if the list is too long. - */ + hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host'); + var hostHeader = req.headers[hostHeaderName]; + if (!hostHeader) { + return null; + } -var Paginator = module.exports = function () { - this.pointer = 0; - this.lastIndex = 0; + if (hostHeader.length > exports.limits.maxMatchLength) { + return null; + } + + var hostParts = hostHeader.match(internals.hostHeaderRegex); + if (!hostParts) { + return null; + } + + return { + name: hostParts[1], + port: (hostParts[2] ? hostParts[2] : (req.connection && req.connection.encrypted ? 443 : 80)) + }; }; -Paginator.prototype.paginate = function (output, active, pageSize) { - pageSize = pageSize || 7; - var middleOfList = Math.floor(pageSize / 2); - var lines = output.split('\n'); - // Make sure there's enough lines to paginate - if (lines.length <= pageSize) { - return output; - } +// Parse Content-Type header content - // Move the pointer only when the user go down and limit it to the middle of the list - if (this.pointer < middleOfList && this.lastIndex < active && active - this.lastIndex < pageSize) { - this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex); - } - this.lastIndex = active; +exports.parseContentType = function (header) { - // Duplicate the lines so it give an infinite list look - var infinite = _.flatten([lines, lines, lines]); - var topIndex = Math.max(0, active + lines.length - this.pointer); + if (!header) { + return ''; + } - var section = infinite.splice(topIndex, pageSize).join('\n'); - return section + '\n' + chalk.dim('(Move up and down to reveal more choices)'); + return header.split(';')[0].trim().toLowerCase(); }; -/***/ }), -/* 100 */ -/***/ (function(module, exports) { +// Convert node's to request configuration object -/*! - * is-extglob <https://github.com/jonschlinkert/is-extglob> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ +exports.parseRequest = function (req, options) { -module.exports = function isExtglob(str) { - return typeof str === 'string' - && /[@?!+*]\(/.test(str); + if (!req.headers) { + return req; + } + + // Obtain host and port information + + var host; + if (!options.host || + !options.port) { + + host = exports.parseHost(req, options.hostHeaderName); + if (!host) { + return new Error('Invalid Host header'); + } + } + + var request = { + method: req.method, + url: req.url, + host: options.host || host.name, + port: options.port || host.port, + authorization: req.headers.authorization, + contentType: req.headers['content-type'] || '' + }; + + return request; }; -/***/ }), -/* 101 */ -/***/ (function(module, exports, __webpack_require__) { +exports.now = function (localtimeOffsetMsec) { -/*! - * is-glob <https://github.com/jonschlinkert/is-glob> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ + return Sntp.now() + (localtimeOffsetMsec || 0); +}; -var isExtglob = __webpack_require__(100); -module.exports = function isGlob(str) { - return typeof str === 'string' - && (/[*!?{}(|)[\]]/.test(str) - || isExtglob(str)); +exports.nowSecs = function (localtimeOffsetMsec) { + + return Math.floor(exports.now(localtimeOffsetMsec) / 1000); }; -/***/ }), -/* 102 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +internals.authHeaderRegex = /^(\w+)(?:\s+(.*))?$/; // Header: scheme[ something] +internals.attributeRegex = /^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~]+$/; // !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9 -/** - * @fileOverview - * Core operations on curve 25519 required for the higher level modules. - */ -/* - * Copyright (c) 2007, 2013, 2014 Michele Bini - * Copyright (c) 2014 Mega Limited - * under the MIT License. - * - * Authors: Guy K. Kloss, Michele Bini - * - * You should have received a copy of the license along with this program. - */ +// Parse Hawk HTTP Authorization header -var crypto = __webpack_require__(7); +exports.parseAuthorizationHeader = function (header, keys) { - /** - * @exports jodid25519/core - * Core operations on curve 25519 required for the higher level modules. - * - * @description - * Core operations on curve 25519 required for the higher level modules. - * - * <p> - * This core code is extracted from Michele Bini's curve255.js implementation, - * which is used as a base for Curve25519 ECDH and Ed25519 EdDSA operations. - * </p> - */ - var ns = {}; + keys = keys || ['id', 'ts', 'nonce', 'hash', 'ext', 'mac', 'app', 'dlg']; - function _setbit(n, c, v) { - var i = c >> 4; - var a = n[i]; - a = a + (1 << (c & 0xf)) * v; - n[i] = a; + if (!header) { + return Boom.unauthorized(null, 'Hawk'); } - function _getbit(n, c) { - return (n[c >> 4] >> (c & 0xf)) & 1; + if (header.length > exports.limits.maxMatchLength) { + return Boom.badRequest('Header length too long'); } - function _ZERO() { - return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + var headerParts = header.match(internals.authHeaderRegex); + if (!headerParts) { + return Boom.badRequest('Invalid header syntax'); } - function _ONE() { - return [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + var scheme = headerParts[1]; + if (scheme.toLowerCase() !== 'hawk') { + return Boom.unauthorized(null, 'Hawk'); } - // Basepoint. - function _BASE() { - return [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + var attributesString = headerParts[2]; + if (!attributesString) { + return Boom.badRequest('Invalid header syntax'); } - // return -1, 0, +1 when a is less than, equal, or greater than b - function _bigintcmp(a, b) { - // The following code is a bit tricky to avoid code branching - var c, abs_r, mask; - var r = 0; - for (c = 15; c >= 0; c--) { - var x = a[c]; - var y = b[c]; - r = r + (x - y) * (1 - r * r); - // http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs - // correct for [-294967295, 294967295] - mask = r >> 31; - abs_r = (r + mask) ^ mask; - // http://stackoverflow.com/questions/596467/how-do-i-convert-a-number-to-an-integer-in-javascript - // this rounds towards zero - r = ~~((r << 1) / (abs_r + 1)); + var attributes = {}; + var errorMessage = ''; + var verify = attributesString.replace(/(\w+)="([^"\\]*)"\s*(?:,\s*|$)/g, function ($0, $1, $2) { + + // Check valid attribute names + + if (keys.indexOf($1) === -1) { + errorMessage = 'Unknown attribute: ' + $1; + return; } - return r; - } - function _bigintadd(a, b) { - var r = []; - var v; - r[0] = (v = a[0] + b[0]) & 0xffff; - r[1] = (v = (v >>> 16) + a[1] + b[1]) & 0xffff; - r[2] = (v = (v >>> 16) + a[2] + b[2]) & 0xffff; - r[3] = (v = (v >>> 16) + a[3] + b[3]) & 0xffff; - r[4] = (v = (v >>> 16) + a[4] + b[4]) & 0xffff; - r[5] = (v = (v >>> 16) + a[5] + b[5]) & 0xffff; - r[6] = (v = (v >>> 16) + a[6] + b[6]) & 0xffff; - r[7] = (v = (v >>> 16) + a[7] + b[7]) & 0xffff; - r[8] = (v = (v >>> 16) + a[8] + b[8]) & 0xffff; - r[9] = (v = (v >>> 16) + a[9] + b[9]) & 0xffff; - r[10] = (v = (v >>> 16) + a[10] + b[10]) & 0xffff; - r[11] = (v = (v >>> 16) + a[11] + b[11]) & 0xffff; - r[12] = (v = (v >>> 16) + a[12] + b[12]) & 0xffff; - r[13] = (v = (v >>> 16) + a[13] + b[13]) & 0xffff; - r[14] = (v = (v >>> 16) + a[14] + b[14]) & 0xffff; - r[15] = (v >>> 16) + a[15] + b[15]; - return r; - } + // Allowed attribute value characters - function _bigintsub(a, b) { - var r = []; - var v; - r[0] = (v = 0x80000 + a[0] - b[0]) & 0xffff; - r[1] = (v = (v >>> 16) + 0x7fff8 + a[1] - b[1]) & 0xffff; - r[2] = (v = (v >>> 16) + 0x7fff8 + a[2] - b[2]) & 0xffff; - r[3] = (v = (v >>> 16) + 0x7fff8 + a[3] - b[3]) & 0xffff; - r[4] = (v = (v >>> 16) + 0x7fff8 + a[4] - b[4]) & 0xffff; - r[5] = (v = (v >>> 16) + 0x7fff8 + a[5] - b[5]) & 0xffff; - r[6] = (v = (v >>> 16) + 0x7fff8 + a[6] - b[6]) & 0xffff; - r[7] = (v = (v >>> 16) + 0x7fff8 + a[7] - b[7]) & 0xffff; - r[8] = (v = (v >>> 16) + 0x7fff8 + a[8] - b[8]) & 0xffff; - r[9] = (v = (v >>> 16) + 0x7fff8 + a[9] - b[9]) & 0xffff; - r[10] = (v = (v >>> 16) + 0x7fff8 + a[10] - b[10]) & 0xffff; - r[11] = (v = (v >>> 16) + 0x7fff8 + a[11] - b[11]) & 0xffff; - r[12] = (v = (v >>> 16) + 0x7fff8 + a[12] - b[12]) & 0xffff; - r[13] = (v = (v >>> 16) + 0x7fff8 + a[13] - b[13]) & 0xffff; - r[14] = (v = (v >>> 16) + 0x7fff8 + a[14] - b[14]) & 0xffff; - r[15] = (v >>> 16) - 8 + a[15] - b[15]; - return r; - } + if ($2.match(internals.attributeRegex) === null) { + errorMessage = 'Bad attribute value: ' + $1; + return; + } - function _sqr8h(a7, a6, a5, a4, a3, a2, a1, a0) { - // 'division by 0x10000' can not be replaced by '>> 16' because - // more than 32 bits of precision are needed similarly - // 'multiplication by 2' cannot be replaced by '<< 1' - var r = []; - var v; - r[0] = (v = a0 * a0) & 0xffff; - r[1] = (v = (0 | (v / 0x10000)) + 2 * a0 * a1) & 0xffff; - r[2] = (v = (0 | (v / 0x10000)) + 2 * a0 * a2 + a1 * a1) & 0xffff; - r[3] = (v = (0 | (v / 0x10000)) + 2 * a0 * a3 + 2 * a1 * a2) & 0xffff; - r[4] = (v = (0 | (v / 0x10000)) + 2 * a0 * a4 + 2 * a1 * a3 + a2 - * a2) & 0xffff; - r[5] = (v = (0 | (v / 0x10000)) + 2 * a0 * a5 + 2 * a1 * a4 + 2 - * a2 * a3) & 0xffff; - r[6] = (v = (0 | (v / 0x10000)) + 2 * a0 * a6 + 2 * a1 * a5 + 2 - * a2 * a4 + a3 * a3) & 0xffff; - r[7] = (v = (0 | (v / 0x10000)) + 2 * a0 * a7 + 2 * a1 * a6 + 2 - * a2 * a5 + 2 * a3 * a4) & 0xffff; - r[8] = (v = (0 | (v / 0x10000)) + 2 * a1 * a7 + 2 * a2 * a6 + 2 - * a3 * a5 + a4 * a4) & 0xffff; - r[9] = (v = (0 | (v / 0x10000)) + 2 * a2 * a7 + 2 * a3 * a6 + 2 - * a4 * a5) & 0xffff; - r[10] = (v = (0 | (v / 0x10000)) + 2 * a3 * a7 + 2 * a4 * a6 - + a5 * a5) & 0xffff; - r[11] = (v = (0 | (v / 0x10000)) + 2 * a4 * a7 + 2 * a5 * a6) & 0xffff; - r[12] = (v = (0 | (v / 0x10000)) + 2 * a5 * a7 + a6 * a6) & 0xffff; - r[13] = (v = (0 | (v / 0x10000)) + 2 * a6 * a7) & 0xffff; - r[14] = (v = (0 | (v / 0x10000)) + a7 * a7) & 0xffff; - r[15] = 0 | (v / 0x10000); - return r; - } + // Check for duplicates - function _sqrmodp(a) { - var x = _sqr8h(a[15], a[14], a[13], a[12], a[11], a[10], a[9], - a[8]); - var z = _sqr8h(a[7], a[6], a[5], a[4], a[3], a[2], a[1], a[0]); - var y = _sqr8h(a[15] + a[7], a[14] + a[6], a[13] + a[5], a[12] - + a[4], - a[11] + a[3], a[10] + a[2], a[9] + a[1], a[8] - + a[0]); - var r = []; - var v; - r[0] = (v = 0x800000 + z[0] + (y[8] - x[8] - z[8] + x[0] - 0x80) - * 38) & 0xffff; - r[1] = (v = 0x7fff80 + (v >>> 16) + z[1] - + (y[9] - x[9] - z[9] + x[1]) * 38) & 0xffff; - r[2] = (v = 0x7fff80 + (v >>> 16) + z[2] - + (y[10] - x[10] - z[10] + x[2]) * 38) & 0xffff; - r[3] = (v = 0x7fff80 + (v >>> 16) + z[3] - + (y[11] - x[11] - z[11] + x[3]) * 38) & 0xffff; - r[4] = (v = 0x7fff80 + (v >>> 16) + z[4] - + (y[12] - x[12] - z[12] + x[4]) * 38) & 0xffff; - r[5] = (v = 0x7fff80 + (v >>> 16) + z[5] - + (y[13] - x[13] - z[13] + x[5]) * 38) & 0xffff; - r[6] = (v = 0x7fff80 + (v >>> 16) + z[6] - + (y[14] - x[14] - z[14] + x[6]) * 38) & 0xffff; - r[7] = (v = 0x7fff80 + (v >>> 16) + z[7] - + (y[15] - x[15] - z[15] + x[7]) * 38) & 0xffff; - r[8] = (v = 0x7fff80 + (v >>> 16) + z[8] + y[0] - x[0] - z[0] - + x[8] * 38) & 0xffff; - r[9] = (v = 0x7fff80 + (v >>> 16) + z[9] + y[1] - x[1] - z[1] - + x[9] * 38) & 0xffff; - r[10] = (v = 0x7fff80 + (v >>> 16) + z[10] + y[2] - x[2] - z[2] - + x[10] * 38) & 0xffff; - r[11] = (v = 0x7fff80 + (v >>> 16) + z[11] + y[3] - x[3] - z[3] - + x[11] * 38) & 0xffff; - r[12] = (v = 0x7fff80 + (v >>> 16) + z[12] + y[4] - x[4] - z[4] - + x[12] * 38) & 0xffff; - r[13] = (v = 0x7fff80 + (v >>> 16) + z[13] + y[5] - x[5] - z[5] - + x[13] * 38) & 0xffff; - r[14] = (v = 0x7fff80 + (v >>> 16) + z[14] + y[6] - x[6] - z[6] - + x[14] * 38) & 0xffff; - r[15] = 0x7fff80 + (v >>> 16) + z[15] + y[7] - x[7] - z[7] - + x[15] * 38; - _reduce(r); - return r; - } + if (attributes.hasOwnProperty($1)) { + errorMessage = 'Duplicate attribute: ' + $1; + return; + } - function _mul8h(a7, a6, a5, a4, a3, a2, a1, a0, b7, b6, b5, b4, b3, - b2, b1, b0) { - // 'division by 0x10000' can not be replaced by '>> 16' because - // more than 32 bits of precision are needed - var r = []; - var v; - r[0] = (v = a0 * b0) & 0xffff; - r[1] = (v = (0 | (v / 0x10000)) + a0 * b1 + a1 * b0) & 0xffff; - r[2] = (v = (0 | (v / 0x10000)) + a0 * b2 + a1 * b1 + a2 * b0) & 0xffff; - r[3] = (v = (0 | (v / 0x10000)) + a0 * b3 + a1 * b2 + a2 * b1 - + a3 * b0) & 0xffff; - r[4] = (v = (0 | (v / 0x10000)) + a0 * b4 + a1 * b3 + a2 * b2 - + a3 * b1 + a4 * b0) & 0xffff; - r[5] = (v = (0 | (v / 0x10000)) + a0 * b5 + a1 * b4 + a2 * b3 - + a3 * b2 + a4 * b1 + a5 * b0) & 0xffff; - r[6] = (v = (0 | (v / 0x10000)) + a0 * b6 + a1 * b5 + a2 * b4 - + a3 * b3 + a4 * b2 + a5 * b1 + a6 * b0) & 0xffff; - r[7] = (v = (0 | (v / 0x10000)) + a0 * b7 + a1 * b6 + a2 * b5 - + a3 * b4 + a4 * b3 + a5 * b2 + a6 * b1 + a7 * b0) & 0xffff; - r[8] = (v = (0 | (v / 0x10000)) + a1 * b7 + a2 * b6 + a3 * b5 - + a4 * b4 + a5 * b3 + a6 * b2 + a7 * b1) & 0xffff; - r[9] = (v = (0 | (v / 0x10000)) + a2 * b7 + a3 * b6 + a4 * b5 - + a5 * b4 + a6 * b3 + a7 * b2) & 0xffff; - r[10] = (v = (0 | (v / 0x10000)) + a3 * b7 + a4 * b6 + a5 * b5 - + a6 * b4 + a7 * b3) & 0xffff; - r[11] = (v = (0 | (v / 0x10000)) + a4 * b7 + a5 * b6 + a6 * b5 - + a7 * b4) & 0xffff; - r[12] = (v = (0 | (v / 0x10000)) + a5 * b7 + a6 * b6 + a7 * b5) & 0xffff; - r[13] = (v = (0 | (v / 0x10000)) + a6 * b7 + a7 * b6) & 0xffff; - r[14] = (v = (0 | (v / 0x10000)) + a7 * b7) & 0xffff; - r[15] = (0 | (v / 0x10000)); - return r; - } + attributes[$1] = $2; + return ''; + }); - function _mulmodp(a, b) { - // Karatsuba multiplication scheme: x*y = (b^2+b)*x1*y1 - - // b*(x1-x0)*(y1-y0) + (b+1)*x0*y0 - var x = _mul8h(a[15], a[14], a[13], a[12], a[11], a[10], a[9], - a[8], b[15], b[14], b[13], b[12], b[11], b[10], - b[9], b[8]); - var z = _mul8h(a[7], a[6], a[5], a[4], a[3], a[2], a[1], a[0], - b[7], b[6], b[5], b[4], b[3], b[2], b[1], b[0]); - var y = _mul8h(a[15] + a[7], a[14] + a[6], a[13] + a[5], a[12] - + a[4], - a[11] + a[3], a[10] + a[2], a[9] + a[1], a[8] - + a[0], - b[15] + b[7], b[14] + b[6], b[13] + b[5], b[12] - + b[4], - b[11] + b[3], b[10] + b[2], b[9] + b[1], b[8] - + b[0]); - var r = []; - var v; - r[0] = (v = 0x800000 + z[0] + (y[8] - x[8] - z[8] + x[0] - 0x80) - * 38) & 0xffff; - r[1] = (v = 0x7fff80 + (v >>> 16) + z[1] - + (y[9] - x[9] - z[9] + x[1]) * 38) & 0xffff; - r[2] = (v = 0x7fff80 + (v >>> 16) + z[2] - + (y[10] - x[10] - z[10] + x[2]) * 38) & 0xffff; - r[3] = (v = 0x7fff80 + (v >>> 16) + z[3] - + (y[11] - x[11] - z[11] + x[3]) * 38) & 0xffff; - r[4] = (v = 0x7fff80 + (v >>> 16) + z[4] - + (y[12] - x[12] - z[12] + x[4]) * 38) & 0xffff; - r[5] = (v = 0x7fff80 + (v >>> 16) + z[5] - + (y[13] - x[13] - z[13] + x[5]) * 38) & 0xffff; - r[6] = (v = 0x7fff80 + (v >>> 16) + z[6] - + (y[14] - x[14] - z[14] + x[6]) * 38) & 0xffff; - r[7] = (v = 0x7fff80 + (v >>> 16) + z[7] - + (y[15] - x[15] - z[15] + x[7]) * 38) & 0xffff; - r[8] = (v = 0x7fff80 + (v >>> 16) + z[8] + y[0] - x[0] - z[0] - + x[8] * 38) & 0xffff; - r[9] = (v = 0x7fff80 + (v >>> 16) + z[9] + y[1] - x[1] - z[1] - + x[9] * 38) & 0xffff; - r[10] = (v = 0x7fff80 + (v >>> 16) + z[10] + y[2] - x[2] - z[2] - + x[10] * 38) & 0xffff; - r[11] = (v = 0x7fff80 + (v >>> 16) + z[11] + y[3] - x[3] - z[3] - + x[11] * 38) & 0xffff; - r[12] = (v = 0x7fff80 + (v >>> 16) + z[12] + y[4] - x[4] - z[4] - + x[12] * 38) & 0xffff; - r[13] = (v = 0x7fff80 + (v >>> 16) + z[13] + y[5] - x[5] - z[5] - + x[13] * 38) & 0xffff; - r[14] = (v = 0x7fff80 + (v >>> 16) + z[14] + y[6] - x[6] - z[6] - + x[14] * 38) & 0xffff; - r[15] = 0x7fff80 + (v >>> 16) + z[15] + y[7] - x[7] - z[7] - + x[15] * 38; - _reduce(r); - return r; + if (verify !== '') { + return Boom.badRequest(errorMessage || 'Bad header format'); } - function _reduce(arr) { - var aCopy = arr.slice(0); - var choice = [arr, aCopy]; - var v = arr[15]; - // Use the dummy copy instead of just returning to be more constant time. - var a = choice[(v < 0x8000) & 1]; - a[15] = v & 0x7fff; - // >32-bits of precision are required here so '/ 0x8000' can not be - // replaced by the arithmetic equivalent '>>> 15' - v = (0 | (v / 0x8000)) * 19; - a[0] = (v += a[0]) & 0xffff; - v = v >>> 16; - a[1] = (v += a[1]) & 0xffff; - v = v >>> 16; - a[2] = (v += a[2]) & 0xffff; - v = v >>> 16; - a[3] = (v += a[3]) & 0xffff; - v = v >>> 16; - a[4] = (v += a[4]) & 0xffff; - v = v >>> 16; - a[5] = (v += a[5]) & 0xffff; - v = v >>> 16; - a[6] = (v += a[6]) & 0xffff; - v = v >>> 16; - a[7] = (v += a[7]) & 0xffff; - v = v >>> 16; - a[8] = (v += a[8]) & 0xffff; - v = v >>> 16; - a[9] = (v += a[9]) & 0xffff; - v = v >>> 16; - a[10] = (v += a[10]) & 0xffff; - v = v >>> 16; - a[11] = (v += a[11]) & 0xffff; - v = v >>> 16; - a[12] = (v += a[12]) & 0xffff; - v = v >>> 16; - a[13] = (v += a[13]) & 0xffff; - v = v >>> 16; - a[14] = (v += a[14]) & 0xffff; - v = v >>> 16; - a[15] += v; - } + return attributes; +}; - function _addmodp(a, b) { - var r = []; - var v; - r[0] = (v = ((0 | (a[15] >>> 15)) + (0 | (b[15] >>> 15))) * 19 - + a[0] + b[0]) & 0xffff; - r[1] = (v = (v >>> 16) + a[1] + b[1]) & 0xffff; - r[2] = (v = (v >>> 16) + a[2] + b[2]) & 0xffff; - r[3] = (v = (v >>> 16) + a[3] + b[3]) & 0xffff; - r[4] = (v = (v >>> 16) + a[4] + b[4]) & 0xffff; - r[5] = (v = (v >>> 16) + a[5] + b[5]) & 0xffff; - r[6] = (v = (v >>> 16) + a[6] + b[6]) & 0xffff; - r[7] = (v = (v >>> 16) + a[7] + b[7]) & 0xffff; - r[8] = (v = (v >>> 16) + a[8] + b[8]) & 0xffff; - r[9] = (v = (v >>> 16) + a[9] + b[9]) & 0xffff; - r[10] = (v = (v >>> 16) + a[10] + b[10]) & 0xffff; - r[11] = (v = (v >>> 16) + a[11] + b[11]) & 0xffff; - r[12] = (v = (v >>> 16) + a[12] + b[12]) & 0xffff; - r[13] = (v = (v >>> 16) + a[13] + b[13]) & 0xffff; - r[14] = (v = (v >>> 16) + a[14] + b[14]) & 0xffff; - r[15] = (v >>> 16) + (a[15] & 0x7fff) + (b[15] & 0x7fff); - return r; - } - function _submodp(a, b) { - var r = []; - var v; - r[0] = (v = 0x80000 - + ((0 | (a[15] >>> 15)) - (0 | (b[15] >>> 15)) - 1) - * 19 + a[0] - b[0]) & 0xffff; - r[1] = (v = (v >>> 16) + 0x7fff8 + a[1] - b[1]) & 0xffff; - r[2] = (v = (v >>> 16) + 0x7fff8 + a[2] - b[2]) & 0xffff; - r[3] = (v = (v >>> 16) + 0x7fff8 + a[3] - b[3]) & 0xffff; - r[4] = (v = (v >>> 16) + 0x7fff8 + a[4] - b[4]) & 0xffff; - r[5] = (v = (v >>> 16) + 0x7fff8 + a[5] - b[5]) & 0xffff; - r[6] = (v = (v >>> 16) + 0x7fff8 + a[6] - b[6]) & 0xffff; - r[7] = (v = (v >>> 16) + 0x7fff8 + a[7] - b[7]) & 0xffff; - r[8] = (v = (v >>> 16) + 0x7fff8 + a[8] - b[8]) & 0xffff; - r[9] = (v = (v >>> 16) + 0x7fff8 + a[9] - b[9]) & 0xffff; - r[10] = (v = (v >>> 16) + 0x7fff8 + a[10] - b[10]) & 0xffff; - r[11] = (v = (v >>> 16) + 0x7fff8 + a[11] - b[11]) & 0xffff; - r[12] = (v = (v >>> 16) + 0x7fff8 + a[12] - b[12]) & 0xffff; - r[13] = (v = (v >>> 16) + 0x7fff8 + a[13] - b[13]) & 0xffff; - r[14] = (v = (v >>> 16) + 0x7fff8 + a[14] - b[14]) & 0xffff; - r[15] = (v >>> 16) + 0x7ff8 + (a[15] & 0x7fff) - - (b[15] & 0x7fff); - return r; - } +exports.unauthorized = function (message, attributes) { - function _invmodp(a) { - var c = a; - var i = 250; - while (--i) { - a = _sqrmodp(a); - a = _mulmodp(a, c); - } - a = _sqrmodp(a); - a = _sqrmodp(a); - a = _mulmodp(a, c); - a = _sqrmodp(a); - a = _sqrmodp(a); - a = _mulmodp(a, c); - a = _sqrmodp(a); - a = _mulmodp(a, c); - return a; - } + return Boom.unauthorized(message, 'Hawk', attributes); +}; - function _mulasmall(a) { - // 'division by 0x10000' can not be replaced by '>> 16' because - // more than 32 bits of precision are needed - var m = 121665; - var r = []; - var v; - r[0] = (v = a[0] * m) & 0xffff; - r[1] = (v = (0 | (v / 0x10000)) + a[1] * m) & 0xffff; - r[2] = (v = (0 | (v / 0x10000)) + a[2] * m) & 0xffff; - r[3] = (v = (0 | (v / 0x10000)) + a[3] * m) & 0xffff; - r[4] = (v = (0 | (v / 0x10000)) + a[4] * m) & 0xffff; - r[5] = (v = (0 | (v / 0x10000)) + a[5] * m) & 0xffff; - r[6] = (v = (0 | (v / 0x10000)) + a[6] * m) & 0xffff; - r[7] = (v = (0 | (v / 0x10000)) + a[7] * m) & 0xffff; - r[8] = (v = (0 | (v / 0x10000)) + a[8] * m) & 0xffff; - r[9] = (v = (0 | (v / 0x10000)) + a[9] * m) & 0xffff; - r[10] = (v = (0 | (v / 0x10000)) + a[10] * m) & 0xffff; - r[11] = (v = (0 | (v / 0x10000)) + a[11] * m) & 0xffff; - r[12] = (v = (0 | (v / 0x10000)) + a[12] * m) & 0xffff; - r[13] = (v = (0 | (v / 0x10000)) + a[13] * m) & 0xffff; - r[14] = (v = (0 | (v / 0x10000)) + a[14] * m) & 0xffff; - r[15] = (0 | (v / 0x10000)) + a[15] * m; - _reduce(r); - return r; - } - function _dbl(x, z) { - var x_2, z_2, m, n, o; - m = _sqrmodp(_addmodp(x, z)); - n = _sqrmodp(_submodp(x, z)); - o = _submodp(m, n); - x_2 = _mulmodp(n, m); - z_2 = _mulmodp(_addmodp(_mulasmall(o), m), o); - return [x_2, z_2]; - } - function _sum(x, z, x_p, z_p, x_1) { - var x_3, z_3, p, q; - p = _mulmodp(_submodp(x, z), _addmodp(x_p, z_p)); - q = _mulmodp(_addmodp(x, z), _submodp(x_p, z_p)); - x_3 = _sqrmodp(_addmodp(p, q)); - z_3 = _mulmodp(_sqrmodp(_submodp(p, q)), x_1); - return [x_3, z_3]; - } +/***/ }), +/* 132 */ +/***/ (function(module, exports, __webpack_require__) { - function _generateKey(curve25519) { - var buffer = crypto.randomBytes(32); +// Load modules - // For Curve25519 DH keys, we need to apply some bit mask on generated - // keys: - // * clear bit 0, 1, 2 of first byte - // * clear bit 7 of last byte - // * set bit 6 of last byte - if (curve25519 === true) { - buffer[0] &= 0xf8; - buffer[31] = (buffer[31] & 0x7f) | 0x40; - } - var result = []; - for (var i = 0; i < buffer.length; i++) { - result.push(String.fromCharCode(buffer[i])); - } - return result.join(''); - } +var Crypto = __webpack_require__(8); +var Path = __webpack_require__(0); +var Util = __webpack_require__(2); +var Escape = __webpack_require__(525); - // Expose some functions to the outside through this name space. - // Note: This is not part of the public API. - ns.getbit = _getbit; - ns.setbit = _setbit; - ns.addmodp = _addmodp; - ns.invmodp = _invmodp; - ns.mulmodp = _mulmodp; - ns.reduce = _reduce; - ns.dbl = _dbl; - ns.sum = _sum; - ns.ZERO = _ZERO; - ns.ONE = _ONE; - ns.BASE = _BASE; - ns.bigintadd = _bigintadd; - ns.bigintsub = _bigintsub; - ns.bigintcmp = _bigintcmp; - ns.mulmodp = _mulmodp; - ns.sqrmodp = _sqrmodp; - ns.generateKey = _generateKey; +// Declare internals -module.exports = ns; +var internals = {}; -/***/ }), -/* 103 */ -/***/ (function(module, exports, __webpack_require__) { +// Clone object or array -"use strict"; +exports.clone = function (obj, seen) { -/** - * @fileOverview - * A collection of general utility functions.. - */ + if (typeof obj !== 'object' || + obj === null) { -/* - * Copyright (c) 2011, 2012, 2014 Ron Garret - * Copyright (c) 2007, 2013, 2014 Michele Bini - * Copyright (c) 2014 Mega Limited - * under the MIT License. - * - * Authors: Guy K. Kloss, Michele Bini, Ron Garret - * - * You should have received a copy of the license along with this program. - */ + return obj; + } -var core = __webpack_require__(102); + seen = seen || { orig: [], copy: [] }; - /** - * @exports jodid25519/utils - * A collection of general utility functions.. - * - * @description - * A collection of general utility functions.. - */ - var ns = {}; + var lookup = seen.orig.indexOf(obj); + if (lookup !== -1) { + return seen.copy[lookup]; + } - var _HEXCHARS = "0123456789abcdef"; + var newObj; + var cloneDeep = false; - function _hexencode(vector) { - var result = []; - for (var i = vector.length - 1; i >= 0; i--) { - var value = vector[i]; - result.push(_HEXCHARS.substr((value >>> 12) & 0x0f, 1)); - result.push(_HEXCHARS.substr((value >>> 8) & 0x0f, 1)); - result.push(_HEXCHARS.substr((value >>> 4) & 0x0f, 1)); - result.push(_HEXCHARS.substr(value & 0x0f, 1)); + if (!Array.isArray(obj)) { + if (Buffer.isBuffer(obj)) { + newObj = new Buffer(obj); } - return result.join(''); - } + else if (obj instanceof Date) { + newObj = new Date(obj.getTime()); + } + else if (obj instanceof RegExp) { + newObj = new RegExp(obj); + } + else { + var proto = Object.getPrototypeOf(obj); + if (proto && + proto.isImmutable) { - function _hexdecode(vector) { - var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; - for (var i = vector.length - 1, l = 0; i >= 0; i -= 4) { - result[l] = (_HEXCHARS.indexOf(vector.charAt(i))) - | (_HEXCHARS.indexOf(vector.charAt(i - 1)) << 4) - | (_HEXCHARS.indexOf(vector.charAt(i - 2)) << 8) - | (_HEXCHARS.indexOf(vector.charAt(i - 3)) << 12); - l++; + newObj = obj; + } + else { + newObj = Object.create(proto); + cloneDeep = true; + } } - return result; + } + else { + newObj = []; + cloneDeep = true; } - var _BASE32CHARS = "abcdefghijklmnopqrstuvwxyz234567"; - - var _BASE32VALUES = (function () { - var result = {}; - for (var i = 0; i < _BASE32CHARS.length; i++) { - result[_BASE32CHARS.charAt(i)] = i; - } - return result; - })(); - - function _base32encode(n) { - var c; - var r = ""; - for (c = 0; c < 255; c += 5) { - r = _BASE32CHARS.substr(core.getbit(n, c) - + (core.getbit(n, c + 1) << 1) - + (core.getbit(n, c + 2) << 2) - + (core.getbit(n, c + 3) << 3) - + (core.getbit(n, c + 4) << 4), 1) - + r; - } - return r; - } + seen.orig.push(obj); + seen.copy.push(newObj); - function _base32decode(n) { - var c = 0; - var r = core.ZERO(); - var l = n.length; - for (c = 0; (l > 0) && (c < 255); c += 5) { - l--; - var v = _BASE32VALUES[n.substr(l, 1)]; - core.setbit(r, c, v & 1); - v >>= 1; - core.setbit(r, c + 1, v & 1); - v >>= 1; - core.setbit(r, c + 2, v & 1); - v >>= 1; - core.setbit(r, c + 3, v & 1); - v >>= 1; - core.setbit(r, c + 4, v & 1); - } - return r; - } + if (cloneDeep) { + var keys = Object.getOwnPropertyNames(obj); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var descriptor = Object.getOwnPropertyDescriptor(obj, key); + if (descriptor && + (descriptor.get || + descriptor.set)) { - function _map(f, l) { - var result = new Array(l.length); - for (var i = 0; i < l.length; i++) { - result[i] = f(l[i]); + Object.defineProperty(newObj, key, descriptor); + } + else { + newObj[key] = exports.clone(obj[key], seen); + } } - return result; } - function _chr(n) { - return String.fromCharCode(n); - } + return newObj; +}; - function _ord(c) { - return c.charCodeAt(0); - } - function _bytes2string(bytes) { - return _map(_chr, bytes).join(''); - } +// Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied +/*eslint-disable */ +exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) { +/*eslint-enable */ + exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object'); + exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object'); - function _string2bytes(s) { - return _map(_ord, s); + if (!source) { + return target; } + if (Array.isArray(source)) { + exports.assert(Array.isArray(target), 'Cannot merge array onto an object'); + if (isMergeArrays === false) { // isMergeArrays defaults to true + target.length = 0; // Must not change target assignment + } - // Expose some functions to the outside through this name space. - - /** - * Encodes an array of unsigned 8-bit integers to a hex string. - * - * @function - * @param vector {array} - * Array containing the byte values. - * @returns {string} - * String containing vector in a hexadecimal representation. - */ - ns.hexEncode = _hexencode; + for (var i = 0, il = source.length; i < il; ++i) { + target.push(exports.clone(source[i])); + } + return target; + } - /** - * Decodes a hex string to an array of unsigned 8-bit integers. - * - * @function - * @param vector {string} - * String containing vector in a hexadecimal representation. - * @returns {array} - * Array containing the byte values. - */ - ns.hexDecode = _hexdecode; + var keys = Object.keys(source); + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var value = source[key]; + if (value && + typeof value === 'object') { + if (!target[key] || + typeof target[key] !== 'object' || + (Array.isArray(target[key]) ^ Array.isArray(value)) || + value instanceof Date || + Buffer.isBuffer(value) || + value instanceof RegExp) { - /** - * Encodes an array of unsigned 8-bit integers using base32 encoding. - * - * @function - * @param vector {array} - * Array containing the byte values. - * @returns {string} - * String containing vector in a hexadecimal representation. - */ - ns.base32encode = _base32encode; + target[key] = exports.clone(value); + } + else { + exports.merge(target[key], value, isNullOverride, isMergeArrays); + } + } + else { + if (value !== null && + value !== undefined) { // Explicit to preserve empty strings + target[key] = value; + } + else if (isNullOverride !== false) { // Defaults to true + target[key] = value; + } + } + } - /** - * Decodes a base32 encoded string to an array of unsigned 8-bit integers. - * - * @function - * @param vector {string} - * String containing vector in a hexadecimal representation. - * @returns {array} - * Array containing the byte values. - */ - ns.base32decode = _base32decode; + return target; +}; - /** - * Converts an unsigned 8-bit integer array representation to a byte string. - * - * @function - * @param vector {array} - * Array containing the byte values. - * @returns {string} - * Byte string representation of vector. - */ - ns.bytes2string = _bytes2string; +// Apply options to a copy of the defaults +exports.applyToDefaults = function (defaults, options, isNullOverride) { - /** - * Converts a byte string representation to an array of unsigned - * 8-bit integers. - * - * @function - * @param vector {array} - * Array containing the byte values. - * @returns {string} - * Byte string representation of vector. - */ - ns.string2bytes = _string2bytes; + exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object'); + exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object'); -module.exports = ns; + if (!options) { // If no options, return null + return null; + } + var copy = exports.clone(defaults); -/***/ }), -/* 104 */ -/***/ (function(module, exports, __webpack_require__) { + if (options === true) { // If options is set to true, use defaults + return copy; + } -var wrappy = __webpack_require__(167) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + return exports.merge(copy, options, isNullOverride === true, false); +}; -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) +// Clone an object except for the listed keys which are shallow copied -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} +exports.cloneWithShallow = function (source, keys) { -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} + if (!source || + typeof source !== 'object') { + return source; + } -/***/ }), -/* 105 */ -/***/ (function(module, exports, __webpack_require__) { + var storage = internals.store(source, keys); // Move shallow copy items to storage + var copy = exports.clone(source); // Deep copy the rest + internals.restore(copy, source, storage); // Shallow copy the stored items and restore + return copy; +}; -"use strict"; +internals.store = function (source, keys) { -var isPromise = __webpack_require__(541); + var storage = {}; + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var value = exports.reach(source, key); + if (value !== undefined) { + storage[key] = value; + internals.reachSet(source, key, undefined); + } + } -/** - * Return a function that will run a function asynchronously or synchronously - * - * example: - * runAsync(wrappedFunction, callback)(...args); - * - * @param {Function} func Function to run - * @param {Function} cb Callback function passed the `func` returned value - * @return {Function(arguments)} Arguments to pass to `func`. This function will in turn - * return a Promise (Node >= 0.12) or call the callbacks. - */ + return storage; +}; -var runAsync = module.exports = function (func, cb) { - cb = cb || function () {}; - return function () { - var async = false; - var args = arguments; +internals.restore = function (copy, source, storage) { - var promise = new Promise(function (resolve, reject) { - var answer = func.apply({ - async: function () { - async = true; - return function (err, value) { - if (err) { - reject(err); - } else { - resolve(value); - } - }; - } - }, Array.prototype.slice.call(args)); + var keys = Object.keys(storage); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + internals.reachSet(copy, key, storage[key]); + internals.reachSet(source, key, storage[key]); + } +}; - if (!async) { - if (isPromise(answer)) { - answer.then(resolve, reject); - } else { - resolve(answer); - } - } - }); - promise.then(cb.bind(null, null), cb); +internals.reachSet = function (obj, key, value) { - return promise; - } -}; + var path = key.split('.'); + var ref = obj; + for (var i = 0, il = path.length; i < il; ++i) { + var segment = path[i]; + if (i + 1 === il) { + ref[segment] = value; + } -runAsync.cb = function (func, cb) { - return runAsync(function () { - var args = Array.prototype.slice.call(arguments); - if (args.length === func.length - 1) { - args.push(this.async()); + ref = ref[segment]; } - return func.apply(this, args); - }, cb); }; -/***/ }), -/* 106 */ -/***/ (function(module, exports, __webpack_require__) { +// Apply options to defaults except for the listed keys which are shallow copied from option without merging -var Rx = __webpack_require__(30); -__webpack_require__(603); -__webpack_require__(604); -__webpack_require__(605); -__webpack_require__(259); -__webpack_require__(606); -__webpack_require__(607); -__webpack_require__(608); -__webpack_require__(609); -__webpack_require__(260); -__webpack_require__(610); -__webpack_require__(611); +exports.applyToDefaultsWithShallow = function (defaults, options, keys) { -module.exports = Rx; + exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object'); + exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object'); + exports.assert(keys && Array.isArray(keys), 'Invalid keys'); + if (!options) { // If no options, return null + return null; + } -/***/ }), -/* 107 */ -/***/ (function(module, exports, __webpack_require__) { + var copy = exports.cloneWithShallow(defaults, keys); -// Copyright 2015 Joyent, Inc. + if (options === true) { // If options is set to true, use defaults + return copy; + } -module.exports = { - read: read, - readSSHPrivate: readSSHPrivate, - write: write + var storage = internals.store(options, keys); // Move shallow copy items to storage + exports.merge(copy, options, false, false); // Deep copy the rest + internals.restore(copy, options, storage); // Shallow copy the stored items and restore + return copy; }; -var assert = __webpack_require__(9); -var asn1 = __webpack_require__(34); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); -var crypto = __webpack_require__(7); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var pem = __webpack_require__(41); -var rfc4253 = __webpack_require__(48); -var SSHBuffer = __webpack_require__(108); -var errors = __webpack_require__(32); +// Deep object or array comparison -var bcrypt; +exports.deepEqual = function (obj, ref, options, seen) { -function read(buf, options) { - return (pem.read(buf, options)); -} + options = options || { prototype: true }; -var MAGIC = 'openssh-key-v1'; + var type = typeof obj; -function readSSHPrivate(type, buf, options) { - buf = new SSHBuffer({buffer: buf}); + if (type !== typeof ref) { + return false; + } - var magic = buf.readCString(); - assert.strictEqual(magic, MAGIC, 'bad magic string'); + if (type !== 'object' || + obj === null || + ref === null) { - var cipher = buf.readString(); - var kdf = buf.readString(); - var kdfOpts = buf.readBuffer(); + if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql + return obj !== 0 || 1 / obj === 1 / ref; // -0 / +0 + } - var nkeys = buf.readInt(); - if (nkeys !== 1) { - throw (new Error('OpenSSH-format key file contains ' + - 'multiple keys: this is unsupported.')); - } + return obj !== obj && ref !== ref; // NaN + } - var pubKey = buf.readBuffer(); + seen = seen || []; + if (seen.indexOf(obj) !== -1) { + return true; // If previous comparison failed, it would have stopped execution + } - if (type === 'public') { - assert.ok(buf.atEnd(), 'excess bytes left after key'); - return (rfc4253.read(pubKey)); - } + seen.push(obj); - var privKeyBlob = buf.readBuffer(); - assert.ok(buf.atEnd(), 'excess bytes left after key'); + if (Array.isArray(obj)) { + if (!Array.isArray(ref)) { + return false; + } - var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts }); - switch (kdf) { - case 'none': - if (cipher !== 'none') { - throw (new Error('OpenSSH-format key uses KDF "none" ' + - 'but specifies a cipher other than "none"')); - } - break; - case 'bcrypt': - var salt = kdfOptsBuf.readBuffer(); - var rounds = kdfOptsBuf.readInt(); - var cinf = utils.opensshCipherInfo(cipher); - if (bcrypt === undefined) { - bcrypt = __webpack_require__(210); - } + if (!options.part && obj.length !== ref.length) { + return false; + } - if (typeof (options.passphrase) === 'string') { - options.passphrase = new Buffer(options.passphrase, - 'utf-8'); - } - if (!Buffer.isBuffer(options.passphrase)) { - throw (new errors.KeyEncryptedError( - options.filename, 'OpenSSH')); - } + for (var i = 0, il = obj.length; i < il; ++i) { + if (options.part) { + var found = false; + for (var r = 0, rl = ref.length; r < rl; ++r) { + if (exports.deepEqual(obj[i], ref[r], options, seen)) { + found = true; + break; + } + } - var pass = new Uint8Array(options.passphrase); - var salti = new Uint8Array(salt); - /* Use the pbkdf to derive both the key and the IV. */ - var out = new Uint8Array(cinf.keySize + cinf.blockSize); - var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, - out, out.length, rounds); - if (res !== 0) { - throw (new Error('bcrypt_pbkdf function returned ' + - 'failure, parameters invalid')); - } - out = new Buffer(out); - var ckey = out.slice(0, cinf.keySize); - var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); - var cipherStream = crypto.createDecipheriv(cinf.opensslName, - ckey, iv); - cipherStream.setAutoPadding(false); - var chunk, chunks = []; - cipherStream.once('error', function (e) { - if (e.toString().indexOf('bad decrypt') !== -1) { - throw (new Error('Incorrect passphrase ' + - 'supplied, could not decrypt key')); - } - throw (e); - }); - cipherStream.write(privKeyBlob); - cipherStream.end(); - while ((chunk = cipherStream.read()) !== null) - chunks.push(chunk); - privKeyBlob = Buffer.concat(chunks); - break; - default: - throw (new Error( - 'OpenSSH-format key uses unknown KDF "' + kdf + '"')); - } + return found; + } - buf = new SSHBuffer({buffer: privKeyBlob}); + if (!exports.deepEqual(obj[i], ref[i], options, seen)) { + return false; + } + } - var checkInt1 = buf.readInt(); - var checkInt2 = buf.readInt(); - if (checkInt1 !== checkInt2) { - throw (new Error('Incorrect passphrase supplied, could not ' + - 'decrypt key')); - } + return true; + } - var ret = {}; - var key = rfc4253.readInternal(ret, 'private', buf.remainder()); + if (Buffer.isBuffer(obj)) { + if (!Buffer.isBuffer(ref)) { + return false; + } - buf.skip(ret.consumed); + if (obj.length !== ref.length) { + return false; + } - var comment = buf.readString(); - key.comment = comment; + for (var j = 0, jl = obj.length; j < jl; ++j) { + if (obj[j] !== ref[j]) { + return false; + } + } - return (key); -} + return true; + } -function write(key, options) { - var pubKey; - if (PrivateKey.isPrivateKey(key)) - pubKey = key.toPublic(); - else - pubKey = key; - - var cipher = 'none'; - var kdf = 'none'; - var kdfopts = new Buffer(0); - var cinf = { blockSize: 8 }; - var passphrase; - if (options !== undefined) { - passphrase = options.passphrase; - if (typeof (passphrase) === 'string') - passphrase = new Buffer(passphrase, 'utf-8'); - if (passphrase !== undefined) { - assert.buffer(passphrase, 'options.passphrase'); - assert.optionalString(options.cipher, 'options.cipher'); - cipher = options.cipher; - if (cipher === undefined) - cipher = 'aes128-ctr'; - cinf = utils.opensshCipherInfo(cipher); - kdf = 'bcrypt'; - } - } + if (obj instanceof Date) { + return (ref instanceof Date && obj.getTime() === ref.getTime()); + } - var privBuf; - if (PrivateKey.isPrivateKey(key)) { - privBuf = new SSHBuffer({}); - var checkInt = crypto.randomBytes(4).readUInt32BE(0); - privBuf.writeInt(checkInt); - privBuf.writeInt(checkInt); - privBuf.write(key.toBuffer('rfc4253')); - privBuf.writeString(key.comment || ''); + if (obj instanceof RegExp) { + return (ref instanceof RegExp && obj.toString() === ref.toString()); + } - var n = 1; - while (privBuf._offset % cinf.blockSize !== 0) - privBuf.writeChar(n++); - privBuf = privBuf.toBuffer(); - } + if (options.prototype) { + if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) { + return false; + } + } - switch (kdf) { - case 'none': - break; - case 'bcrypt': - var salt = crypto.randomBytes(16); - var rounds = 16; - var kdfssh = new SSHBuffer({}); - kdfssh.writeBuffer(salt); - kdfssh.writeInt(rounds); - kdfopts = kdfssh.toBuffer(); + var keys = Object.getOwnPropertyNames(obj); - if (bcrypt === undefined) { - bcrypt = __webpack_require__(210); - } - var pass = new Uint8Array(passphrase); - var salti = new Uint8Array(salt); - /* Use the pbkdf to derive both the key and the IV. */ - var out = new Uint8Array(cinf.keySize + cinf.blockSize); - var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, - out, out.length, rounds); - if (res !== 0) { - throw (new Error('bcrypt_pbkdf function returned ' + - 'failure, parameters invalid')); - } - out = new Buffer(out); - var ckey = out.slice(0, cinf.keySize); - var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); + if (!options.part && keys.length !== Object.getOwnPropertyNames(ref).length) { + return false; + } - var cipherStream = crypto.createCipheriv(cinf.opensslName, - ckey, iv); - cipherStream.setAutoPadding(false); - var chunk, chunks = []; - cipherStream.once('error', function (e) { - throw (e); - }); - cipherStream.write(privBuf); - cipherStream.end(); - while ((chunk = cipherStream.read()) !== null) - chunks.push(chunk); - privBuf = Buffer.concat(chunks); - break; - default: - throw (new Error('Unsupported kdf ' + kdf)); - } + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var descriptor = Object.getOwnPropertyDescriptor(obj, key); + if (descriptor.get) { + if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), options, seen)) { + return false; + } + } + else if (!exports.deepEqual(obj[key], ref[key], options, seen)) { + return false; + } + } - var buf = new SSHBuffer({}); + return true; +}; - buf.writeCString(MAGIC); - buf.writeString(cipher); /* cipher */ - buf.writeString(kdf); /* kdf */ - buf.writeBuffer(kdfopts); /* kdfoptions */ - buf.writeInt(1); /* nkeys */ - buf.writeBuffer(pubKey.toBuffer('rfc4253')); +// Remove duplicate items from array - if (privBuf) - buf.writeBuffer(privBuf); +exports.unique = function (array, key) { - buf = buf.toBuffer(); + var index = {}; + var result = []; - var header; - if (PrivateKey.isPrivateKey(key)) - header = 'OPENSSH PRIVATE KEY'; - else - header = 'OPENSSH PUBLIC KEY'; + for (var i = 0, il = array.length; i < il; ++i) { + var id = (key ? array[i][key] : array[i]); + if (index[id] !== true) { - var tmp = buf.toString('base64'); - var len = tmp.length + (tmp.length / 70) + - 18 + 16 + header.length*2 + 10; - buf = new Buffer(len); - var o = 0; - o += buf.write('-----BEGIN ' + header + '-----\n', o); - for (var i = 0; i < tmp.length; ) { - var limit = i + 70; - if (limit > tmp.length) - limit = tmp.length; - o += buf.write(tmp.slice(i, limit), o); - buf[o++] = 10; - i = limit; - } - o += buf.write('-----END ' + header + '-----\n', o); + result.push(array[i]); + index[id] = true; + } + } - return (buf.slice(0, o)); -} + return result; +}; -/***/ }), -/* 108 */ -/***/ (function(module, exports, __webpack_require__) { +// Convert array into object -// Copyright 2015 Joyent, Inc. +exports.mapToObject = function (array, key) { -module.exports = SSHBuffer; + if (!array) { + return null; + } -var assert = __webpack_require__(9); + var obj = {}; + for (var i = 0, il = array.length; i < il; ++i) { + if (key) { + if (array[i][key]) { + obj[array[i][key]] = true; + } + } + else { + obj[array[i]] = true; + } + } -function SSHBuffer(opts) { - assert.object(opts, 'options'); - if (opts.buffer !== undefined) - assert.buffer(opts.buffer, 'options.buffer'); + return obj; +}; - this._size = opts.buffer ? opts.buffer.length : 1024; - this._buffer = opts.buffer || (new Buffer(this._size)); - this._offset = 0; -} -SSHBuffer.prototype.toBuffer = function () { - return (this._buffer.slice(0, this._offset)); -}; +// Find the common unique items in two arrays -SSHBuffer.prototype.atEnd = function () { - return (this._offset >= this._buffer.length); -}; +exports.intersect = function (array1, array2, justFirst) { -SSHBuffer.prototype.remainder = function () { - return (this._buffer.slice(this._offset)); -}; + if (!array1 || !array2) { + return []; + } -SSHBuffer.prototype.skip = function (n) { - this._offset += n; -}; + var common = []; + var hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1); + var found = {}; + for (var i = 0, il = array2.length; i < il; ++i) { + if (hash[array2[i]] && !found[array2[i]]) { + if (justFirst) { + return array2[i]; + } -SSHBuffer.prototype.expand = function () { - this._size *= 2; - var buf = new Buffer(this._size); - this._buffer.copy(buf, 0); - this._buffer = buf; -}; + common.push(array2[i]); + found[array2[i]] = true; + } + } -SSHBuffer.prototype.readPart = function () { - return ({data: this.readBuffer()}); + return (justFirst ? null : common); }; -SSHBuffer.prototype.readBuffer = function () { - var len = this._buffer.readUInt32BE(this._offset); - this._offset += 4; - assert.ok(this._offset + len <= this._buffer.length, - 'length out of bounds at +0x' + this._offset.toString(16) + - ' (data truncated?)'); - var buf = this._buffer.slice(this._offset, this._offset + len); - this._offset += len; - return (buf); -}; -SSHBuffer.prototype.readString = function () { - return (this.readBuffer().toString()); -}; +// Test if the reference contains the values -SSHBuffer.prototype.readCString = function () { - var offset = this._offset; - while (offset < this._buffer.length && - this._buffer[offset] !== 0x00) - offset++; - assert.ok(offset < this._buffer.length, 'c string does not terminate'); - var str = this._buffer.slice(this._offset, offset).toString(); - this._offset = offset + 1; - return (str); -}; +exports.contain = function (ref, values, options) { -SSHBuffer.prototype.readInt = function () { - var v = this._buffer.readUInt32BE(this._offset); - this._offset += 4; - return (v); -}; + /* + string -> string(s) + array -> item(s) + object -> key(s) + object -> object (key:value) + */ -SSHBuffer.prototype.readInt64 = function () { - assert.ok(this._offset + 8 < this._buffer.length, - 'buffer not long enough to read Int64'); - var v = this._buffer.slice(this._offset, this._offset + 8); - this._offset += 8; - return (v); -}; + var valuePairs = null; + if (typeof ref === 'object' && + typeof values === 'object' && + !Array.isArray(ref) && + !Array.isArray(values)) { -SSHBuffer.prototype.readChar = function () { - var v = this._buffer[this._offset++]; - return (v); -}; + valuePairs = values; + values = Object.keys(values); + } + else { + values = [].concat(values); + } -SSHBuffer.prototype.writeBuffer = function (buf) { - while (this._offset + 4 + buf.length > this._size) - this.expand(); - this._buffer.writeUInt32BE(buf.length, this._offset); - this._offset += 4; - buf.copy(this._buffer, this._offset); - this._offset += buf.length; -}; + options = options || {}; // deep, once, only, part -SSHBuffer.prototype.writeString = function (str) { - this.writeBuffer(new Buffer(str, 'utf8')); -}; + exports.assert(arguments.length >= 2, 'Insufficient arguments'); + exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object'); + exports.assert(values.length, 'Values array cannot be empty'); -SSHBuffer.prototype.writeCString = function (str) { - while (this._offset + 1 + str.length > this._size) - this.expand(); - this._buffer.write(str, this._offset); - this._offset += str.length; - this._buffer[this._offset++] = 0; -}; + var compare, compareFlags; + if (options.deep) { + compare = exports.deepEqual; -SSHBuffer.prototype.writeInt = function (v) { - while (this._offset + 4 > this._size) - this.expand(); - this._buffer.writeUInt32BE(v, this._offset); - this._offset += 4; -}; + var hasOnly = options.hasOwnProperty('only'), hasPart = options.hasOwnProperty('part'); -SSHBuffer.prototype.writeInt64 = function (v) { - assert.buffer(v, 'value'); - if (v.length > 8) { - var lead = v.slice(0, v.length - 8); - for (var i = 0; i < lead.length; ++i) { - assert.strictEqual(lead[i], 0, - 'must fit in 64 bits of precision'); - } - v = v.slice(v.length - 8, v.length); - } - while (this._offset + 8 > this._size) - this.expand(); - v.copy(this._buffer, this._offset); - this._offset += 8; -}; + compareFlags = { + prototype: hasOnly ? options.only : hasPart ? !options.part : false, + part: hasOnly ? !options.only : hasPart ? options.part : true + }; + } + else { + compare = function (a, b) { -SSHBuffer.prototype.writeChar = function (v) { - while (this._offset + 1 > this._size) - this.expand(); - this._buffer[this._offset++] = v; -}; + return a === b; + }; + } -SSHBuffer.prototype.writePart = function (p) { - this.writeBuffer(p.data); -}; + var misses = false; + var matches = new Array(values.length); + for (var i = 0, il = matches.length; i < il; ++i) { + matches[i] = 0; + } -SSHBuffer.prototype.write = function (buf) { - while (this._offset + buf.length > this._size) - this.expand(); - buf.copy(this._buffer, this._offset); - this._offset += buf.length; -}; + if (typeof ref === 'string') { + var pattern = '('; + for (i = 0, il = values.length; i < il; ++i) { + var value = values[i]; + exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value'); + pattern += (i ? '|' : '') + exports.escapeRegex(value); + } + var regex = new RegExp(pattern + ')', 'g'); + var leftovers = ref.replace(regex, function ($0, $1) { -/***/ }), -/* 109 */ -/***/ (function(module, exports, __webpack_require__) { + var index = values.indexOf($1); + ++matches[index]; + return ''; // Remove from string + }); -var chownr = __webpack_require__(407) -var tar = __webpack_require__(270) -var pump = __webpack_require__(248) -var mkdirp = __webpack_require__(160) -var fs = __webpack_require__(6) -var path = __webpack_require__(1) -var os = __webpack_require__(113) + misses = !!leftovers; + } + else if (Array.isArray(ref)) { + for (i = 0, il = ref.length; i < il; ++i) { + for (var j = 0, jl = values.length, matched = false; j < jl && matched === false; ++j) { + matched = compare(values[j], ref[i], compareFlags) && j; + } -var win32 = os.platform() === 'win32' + if (matched !== false) { + ++matches[matched]; + } + else { + misses = true; + } + } + } + else { + var keys = Object.keys(ref); + for (i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + var pos = values.indexOf(key); + if (pos !== -1) { + if (valuePairs && + !compare(valuePairs[key], ref[key], compareFlags)) { -var noop = function () {} + return false; + } -var echo = function (name) { - return name -} + ++matches[pos]; + } + else { + misses = true; + } + } + } -var normalize = !win32 ? echo : function (name) { - return name.replace(/\\/g, '/').replace(/:/g, '_') -} + var result = false; + for (i = 0, il = matches.length; i < il; ++i) { + result = result || !!matches[i]; + if ((options.once && matches[i] > 1) || + (!options.part && !matches[i])) { -var statAll = function (fs, stat, cwd, ignore, entries, sort) { - var queue = entries || ['.'] + return false; + } + } - return function loop (callback) { - if (!queue.length) return callback() - var next = queue.shift() - var nextAbs = path.join(cwd, next) + if (options.only && + misses) { - stat(nextAbs, function (err, stat) { - if (err) return callback(err) + return false; + } - if (!stat.isDirectory()) return callback(null, next, stat) + return result; +}; - fs.readdir(nextAbs, function (err, files) { - if (err) return callback(err) - if (sort) files.sort() - for (var i = 0; i < files.length; i++) { - if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) - } +// Flatten array - callback(null, next, stat) - }) - }) - } -} +exports.flatten = function (array, target) { -var strip = function (map, level) { - return function (header) { - header.name = header.name.split('/').slice(level).join('/') + var result = target || []; - var linkname = header.linkname - if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { - header.linkname = linkname.split('/').slice(level).join('/') + for (var i = 0, il = array.length; i < il; ++i) { + if (Array.isArray(array[i])) { + exports.flatten(array[i], result); + } + else { + result.push(array[i]); + } } - return map(header) - } -} - -exports.pack = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} + return result; +}; - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) - var strict = opts.strict !== false - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var pack = opts.pack || tar.pack() - if (opts.strip) map = strip(map, opts.strip) +// Convert an object key chain string ('a.b.c') to reference (object[a][b][c]) - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) - } +exports.reach = function (obj, chain, options) { - var onsymlink = function (filename, header) { - xfs.readlink(path.join(cwd, filename), function (err, linkname) { - if (err) return pack.destroy(err) - header.linkname = normalize(linkname) - pack.entry(header, onnextentry) - }) - } + if (chain === false || + chain === null || + typeof chain === 'undefined') { - var onstat = function (err, filename, stat) { - if (err) return pack.destroy(err) - if (!filename) return pack.finalize() + return obj; + } - if (stat.isSocket()) return onnextentry() // tar does not support sockets... + options = options || {}; + if (typeof options === 'string') { + options = { separator: options }; + } - var header = { - name: normalize(filename), - mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, - mtime: stat.mtime, - size: stat.size, - type: 'file', - uid: stat.uid, - gid: stat.gid - } + var path = chain.split(options.separator || '.'); + var ref = obj; + for (var i = 0, il = path.length; i < il; ++i) { + var key = path[i]; + if (key[0] === '-' && Array.isArray(ref)) { + key = key.slice(1, key.length); + key = ref.length - key; + } - if (stat.isDirectory()) { - header.size = 0 - header.type = 'directory' - header = map(header) || header - return pack.entry(header, onnextentry) - } + if (!ref || + !ref.hasOwnProperty(key) || + (typeof ref !== 'object' && options.functions === false)) { // Only object and function can have properties - if (stat.isSymbolicLink()) { - header.size = 0 - header.type = 'symlink' - header = map(header) || header - return onsymlink(filename, header) + exports.assert(!options.strict || i + 1 === il, 'Missing segment', key, 'in reach path ', chain); + exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain); + ref = options.default; + break; + } + + ref = ref[key]; } - // TODO: add fifo etc... + return ref; +}; - header = map(header) || header - if (!stat.isFile()) { - if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) - return onnextentry() +exports.reachTemplate = function (obj, template, options) { + + return template.replace(/{([^}]+)}/g, function ($0, chain) { + + var value = exports.reach(obj, chain, options); + return (value === undefined || value === null ? '' : value); + }); +}; + + +exports.formatStack = function (stack) { + + var trace = []; + for (var i = 0, il = stack.length; i < il; ++i) { + var item = stack[i]; + trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]); } - var entry = pack.entry(header, onnextentry) - if (!entry) return + return trace; +}; - var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header) - rs.on('error', function (err) { // always forward errors on destroy - entry.destroy(err) - }) +exports.formatTrace = function (trace) { - pump(rs, entry) - } + var display = []; - var onnextentry = function (err) { - if (err) return pack.destroy(err) - statNext(onstat) - } + for (var i = 0, il = trace.length; i < il; ++i) { + var row = trace[i]; + display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')'); + } - onnextentry() + return display; +}; - return pack -} -var head = function (list) { - return list.length ? list[list.length - 1] : null -} +exports.callStack = function (slice) { -var processGetuid = function () { - return process.getuid ? process.getuid() : -1 -} + // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi -var processUmask = function () { - return process.umask ? process.umask() : 0 -} + var v8 = Error.prepareStackTrace; + Error.prepareStackTrace = function (err, stack) { -exports.extract = function (cwd, opts) { - if (!cwd) cwd = '.' - if (!opts) opts = {} + return stack; + }; - var xfs = opts.fs || fs - var ignore = opts.ignore || opts.filter || noop - var map = opts.map || noop - var mapStream = opts.mapStream || echo - var own = opts.chown !== false && !win32 && processGetuid() === 0 - var extract = opts.extract || tar.extract() - var stack = [] - var now = new Date() - var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() - var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 - var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 - var strict = opts.strict !== false + var capture = {}; + Error.captureStackTrace(capture, arguments.callee); /*eslint no-caller:0 */ + var stack = capture.stack; - if (opts.strip) map = strip(map, opts.strip) + Error.prepareStackTrace = v8; - if (opts.readable) { - dmode |= parseInt(555, 8) - fmode |= parseInt(444, 8) - } - if (opts.writable) { - dmode |= parseInt(333, 8) - fmode |= parseInt(222, 8) - } + var trace = exports.formatStack(stack); - var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry - var top - while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() - if (!top) return cb() - xfs.utimes(top[0], now, top[1], cb) - } + if (slice) { + return trace.slice(slice); + } - var utimes = function (name, header, cb) { - if (opts.utimes === false) return cb() + return trace; +}; - if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) - if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? - xfs.utimes(name, now, header.mtime, function (err) { - if (err) return cb(err) - utimesParent(name, cb) - }) - } +exports.displayStack = function (slice) { - var chperm = function (name, header, cb) { - var link = header.type === 'symlink' - var chmod = link ? xfs.lchmod : xfs.chmod - var chown = link ? xfs.lchown : xfs.chown + var trace = exports.callStack(slice === undefined ? 1 : slice + 1); - if (!chmod) return cb() + return exports.formatTrace(trace); +}; - var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask - chmod(name, mode, function (err) { - if (err) return cb(err) - if (!own) return cb() - if (!chown) return cb() - chown(name, header.uid, header.gid, cb) - }) - } - extract.on('entry', function (header, stream, next) { - header = map(header) || header - header.name = normalize(header.name) - var name = path.join(cwd, path.join('/', header.name)) +exports.abortThrow = false; - if (ignore(name, header)) { - stream.resume() - return next() - } - var stat = function (err) { - if (err) return next(err) - utimes(name, header, function (err) { - if (err) return next(err) - if (win32) return next() - chperm(name, header, next) - }) +exports.abort = function (message, hideStack) { + + if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) { + throw new Error(message || 'Unknown error'); } - var onsymlink = function () { - if (win32) return next() // skip symlinks on win for now before it can be tested - xfs.unlink(name, function () { - xfs.symlink(header.linkname, name, stat) - }) + var stack = ''; + if (!hideStack) { + stack = exports.displayStack(1).join('\n\t'); } + console.log('ABORT: ' + message + '\n\t' + stack); + process.exit(1); +}; - var onlink = function () { - if (win32) return next() // skip links on win for now before it can be tested - xfs.unlink(name, function () { - var srcpath = path.resolve(cwd, header.linkname) - xfs.link(srcpath, name, function (err) { - if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { - stream = xfs.createReadStream(srcpath) - return onfile() - } +exports.assert = function (condition /*, msg1, msg2, msg3 */) { - stat(err) - }) - }) + if (condition) { + return; } - var onfile = function () { - var ws = xfs.createWriteStream(name) - var rs = mapStream(stream, header) - - ws.on('error', function (err) { // always forward errors on destroy - rs.destroy(err) - }) - - pump(rs, ws, function (err) { - if (err) return next(err) - ws.on('close', stat) - }) + if (arguments.length === 2 && arguments[1] instanceof Error) { + throw arguments[1]; } - if (header.type === 'directory') { - stack.push([name, header.mtime]) - return mkdirfix(name, { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, stat) + var msgs = []; + for (var i = 1, il = arguments.length; i < il; ++i) { + if (arguments[i] !== '') { + msgs.push(arguments[i]); // Avoids Array.slice arguments leak, allowing for V8 optimizations + } } - mkdirfix(path.dirname(name), { - fs: xfs, own: own, uid: header.uid, gid: header.gid - }, function (err) { - if (err) return next(err) + msgs = msgs.map(function (msg) { - switch (header.type) { - case 'file': return onfile() - case 'link': return onlink() - case 'symlink': return onsymlink() - } + return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg); + }); + throw new Error(msgs.join(' ') || 'Unknown error'); +}; - if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) - stream.resume() - next() - }) - }) +exports.Timer = function () { - return extract -} + this.ts = 0; + this.reset(); +}; -function mkdirfix (name, opts, cb) { - mkdirp(name, {fs: opts.xfs}, function (err, made) { - if (!err && made && opts.own) { - chownr(made, opts.uid, opts.gid, cb) - } else { - cb(err) - } - }) -} +exports.Timer.prototype.reset = function () { -/***/ }), -/* 110 */ -/***/ (function(module, exports, __webpack_require__) { + this.ts = Date.now(); +}; -(function(nacl) { -'use strict'; -// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. -// Public domain. -// -// Implementation derived from TweetNaCl version 20140427. -// See for details: http://tweetnacl.cr.yp.to/ +exports.Timer.prototype.elapsed = function () { -var gf = function(init) { - var i, r = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; - return r; + return Date.now() - this.ts; }; -// Pluggable, initialized in high-level API below. -var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; -var _0 = new Uint8Array(16); -var _9 = new Uint8Array(32); _9[0] = 9; +exports.Bench = function () { -var gf0 = gf(), - gf1 = gf([1]), - _121665 = gf([0xdb41, 1]), - D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), - D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), - X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), - Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), - I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + this.ts = 0; + this.reset(); +}; -function ts64(x, i, h, l) { - x[i] = (h >> 24) & 0xff; - x[i+1] = (h >> 16) & 0xff; - x[i+2] = (h >> 8) & 0xff; - x[i+3] = h & 0xff; - x[i+4] = (l >> 24) & 0xff; - x[i+5] = (l >> 16) & 0xff; - x[i+6] = (l >> 8) & 0xff; - x[i+7] = l & 0xff; -} -function vn(x, xi, y, yi, n) { - var i,d = 0; - for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; - return (1 & ((d - 1) >>> 8)) - 1; -} +exports.Bench.prototype.reset = function () { -function crypto_verify_16(x, xi, y, yi) { - return vn(x,xi,y,yi,16); -} + this.ts = exports.Bench.now(); +}; -function crypto_verify_32(x, xi, y, yi) { - return vn(x,xi,y,yi,32); -} -function core_salsa20(o, p, k, c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; +exports.Bench.prototype.elapsed = function () { - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; + return exports.Bench.now() - this.ts; +}; - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); +exports.Bench.now = function () { - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); + var ts = process.hrtime(); + return (ts[0] * 1e3) + (ts[1] / 1e6); +}; - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); +// Escape string for Regex construction - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); +exports.escapeRegex = function (string) { - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); + // Escape ^$.*+-?=!:|\/()[]{}, + return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&'); +}; - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; +// Base64url (RFC 4648) encode - o[ 4] = x1 >>> 0 & 0xff; - o[ 5] = x1 >>> 8 & 0xff; - o[ 6] = x1 >>> 16 & 0xff; - o[ 7] = x1 >>> 24 & 0xff; +exports.base64urlEncode = function (value, encoding) { - o[ 8] = x2 >>> 0 & 0xff; - o[ 9] = x2 >>> 8 & 0xff; - o[10] = x2 >>> 16 & 0xff; - o[11] = x2 >>> 24 & 0xff; + var buf = (Buffer.isBuffer(value) ? value : new Buffer(value, encoding || 'binary')); + return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, ''); +}; - o[12] = x3 >>> 0 & 0xff; - o[13] = x3 >>> 8 & 0xff; - o[14] = x3 >>> 16 & 0xff; - o[15] = x3 >>> 24 & 0xff; - o[16] = x4 >>> 0 & 0xff; - o[17] = x4 >>> 8 & 0xff; - o[18] = x4 >>> 16 & 0xff; - o[19] = x4 >>> 24 & 0xff; +// Base64url (RFC 4648) decode - o[20] = x5 >>> 0 & 0xff; - o[21] = x5 >>> 8 & 0xff; - o[22] = x5 >>> 16 & 0xff; - o[23] = x5 >>> 24 & 0xff; +exports.base64urlDecode = function (value, encoding) { - o[24] = x6 >>> 0 & 0xff; - o[25] = x6 >>> 8 & 0xff; - o[26] = x6 >>> 16 & 0xff; - o[27] = x6 >>> 24 & 0xff; + if (value && + !/^[\w\-]*$/.test(value)) { - o[28] = x7 >>> 0 & 0xff; - o[29] = x7 >>> 8 & 0xff; - o[30] = x7 >>> 16 & 0xff; - o[31] = x7 >>> 24 & 0xff; + return new Error('Invalid character'); + } - o[32] = x8 >>> 0 & 0xff; - o[33] = x8 >>> 8 & 0xff; - o[34] = x8 >>> 16 & 0xff; - o[35] = x8 >>> 24 & 0xff; + try { + var buf = new Buffer(value, 'base64'); + return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary')); + } + catch (err) { + return err; + } +}; - o[36] = x9 >>> 0 & 0xff; - o[37] = x9 >>> 8 & 0xff; - o[38] = x9 >>> 16 & 0xff; - o[39] = x9 >>> 24 & 0xff; - o[40] = x10 >>> 0 & 0xff; - o[41] = x10 >>> 8 & 0xff; - o[42] = x10 >>> 16 & 0xff; - o[43] = x10 >>> 24 & 0xff; +// Escape attribute value for use in HTTP header - o[44] = x11 >>> 0 & 0xff; - o[45] = x11 >>> 8 & 0xff; - o[46] = x11 >>> 16 & 0xff; - o[47] = x11 >>> 24 & 0xff; +exports.escapeHeaderAttribute = function (attribute) { - o[48] = x12 >>> 0 & 0xff; - o[49] = x12 >>> 8 & 0xff; - o[50] = x12 >>> 16 & 0xff; - o[51] = x12 >>> 24 & 0xff; - - o[52] = x13 >>> 0 & 0xff; - o[53] = x13 >>> 8 & 0xff; - o[54] = x13 >>> 16 & 0xff; - o[55] = x13 >>> 24 & 0xff; - - o[56] = x14 >>> 0 & 0xff; - o[57] = x14 >>> 8 & 0xff; - o[58] = x14 >>> 16 & 0xff; - o[59] = x14 >>> 24 & 0xff; + // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, " - o[60] = x15 >>> 0 & 0xff; - o[61] = x15 >>> 8 & 0xff; - o[62] = x15 >>> 16 & 0xff; - o[63] = x15 >>> 24 & 0xff; -} + exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')'); -function core_hsalsa20(o,p,k,c) { - var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, - j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, - j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, - j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, - j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, - j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, - j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, - j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, - j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, - j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, - j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, - j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, - j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, - j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, - j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, - j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash +}; - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, - x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, - x15 = j15, u; - for (var i = 0; i < 20; i += 2) { - u = x0 + x12 | 0; - x4 ^= u<<7 | u>>>(32-7); - u = x4 + x0 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x4 | 0; - x12 ^= u<<13 | u>>>(32-13); - u = x12 + x8 | 0; - x0 ^= u<<18 | u>>>(32-18); +exports.escapeHtml = function (string) { - u = x5 + x1 | 0; - x9 ^= u<<7 | u>>>(32-7); - u = x9 + x5 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x9 | 0; - x1 ^= u<<13 | u>>>(32-13); - u = x1 + x13 | 0; - x5 ^= u<<18 | u>>>(32-18); + return Escape.escapeHtml(string); +}; - u = x10 + x6 | 0; - x14 ^= u<<7 | u>>>(32-7); - u = x14 + x10 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x14 | 0; - x6 ^= u<<13 | u>>>(32-13); - u = x6 + x2 | 0; - x10 ^= u<<18 | u>>>(32-18); - u = x15 + x11 | 0; - x3 ^= u<<7 | u>>>(32-7); - u = x3 + x15 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x3 | 0; - x11 ^= u<<13 | u>>>(32-13); - u = x11 + x7 | 0; - x15 ^= u<<18 | u>>>(32-18); +exports.escapeJavaScript = function (string) { - u = x0 + x3 | 0; - x1 ^= u<<7 | u>>>(32-7); - u = x1 + x0 | 0; - x2 ^= u<<9 | u>>>(32-9); - u = x2 + x1 | 0; - x3 ^= u<<13 | u>>>(32-13); - u = x3 + x2 | 0; - x0 ^= u<<18 | u>>>(32-18); + return Escape.escapeJavaScript(string); +}; - u = x5 + x4 | 0; - x6 ^= u<<7 | u>>>(32-7); - u = x6 + x5 | 0; - x7 ^= u<<9 | u>>>(32-9); - u = x7 + x6 | 0; - x4 ^= u<<13 | u>>>(32-13); - u = x4 + x7 | 0; - x5 ^= u<<18 | u>>>(32-18); - u = x10 + x9 | 0; - x11 ^= u<<7 | u>>>(32-7); - u = x11 + x10 | 0; - x8 ^= u<<9 | u>>>(32-9); - u = x8 + x11 | 0; - x9 ^= u<<13 | u>>>(32-13); - u = x9 + x8 | 0; - x10 ^= u<<18 | u>>>(32-18); +exports.nextTick = function (callback) { - u = x15 + x14 | 0; - x12 ^= u<<7 | u>>>(32-7); - u = x12 + x15 | 0; - x13 ^= u<<9 | u>>>(32-9); - u = x13 + x12 | 0; - x14 ^= u<<13 | u>>>(32-13); - u = x14 + x13 | 0; - x15 ^= u<<18 | u>>>(32-18); - } + return function () { - o[ 0] = x0 >>> 0 & 0xff; - o[ 1] = x0 >>> 8 & 0xff; - o[ 2] = x0 >>> 16 & 0xff; - o[ 3] = x0 >>> 24 & 0xff; + var args = arguments; + process.nextTick(function () { - o[ 4] = x5 >>> 0 & 0xff; - o[ 5] = x5 >>> 8 & 0xff; - o[ 6] = x5 >>> 16 & 0xff; - o[ 7] = x5 >>> 24 & 0xff; + callback.apply(null, args); + }); + }; +}; - o[ 8] = x10 >>> 0 & 0xff; - o[ 9] = x10 >>> 8 & 0xff; - o[10] = x10 >>> 16 & 0xff; - o[11] = x10 >>> 24 & 0xff; - o[12] = x15 >>> 0 & 0xff; - o[13] = x15 >>> 8 & 0xff; - o[14] = x15 >>> 16 & 0xff; - o[15] = x15 >>> 24 & 0xff; +exports.once = function (method) { - o[16] = x6 >>> 0 & 0xff; - o[17] = x6 >>> 8 & 0xff; - o[18] = x6 >>> 16 & 0xff; - o[19] = x6 >>> 24 & 0xff; + if (method._hoekOnce) { + return method; + } - o[20] = x7 >>> 0 & 0xff; - o[21] = x7 >>> 8 & 0xff; - o[22] = x7 >>> 16 & 0xff; - o[23] = x7 >>> 24 & 0xff; + var once = false; + var wrapped = function () { - o[24] = x8 >>> 0 & 0xff; - o[25] = x8 >>> 8 & 0xff; - o[26] = x8 >>> 16 & 0xff; - o[27] = x8 >>> 24 & 0xff; + if (!once) { + once = true; + method.apply(null, arguments); + } + }; - o[28] = x9 >>> 0 & 0xff; - o[29] = x9 >>> 8 & 0xff; - o[30] = x9 >>> 16 & 0xff; - o[31] = x9 >>> 24 & 0xff; -} + wrapped._hoekOnce = true; -function crypto_core_salsa20(out,inp,k,c) { - core_salsa20(out,inp,k,c); -} + return wrapped; +}; -function crypto_core_hsalsa20(out,inp,k,c) { - core_hsalsa20(out,inp,k,c); -} -var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - // "expand 32-byte k" +exports.isAbsolutePath = function (path, platform) { -function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; + if (!path) { + return false; } - b -= 64; - cpos += 64; - mpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; - } - return 0; -} -function crypto_stream_salsa20(c,cpos,b,n,k) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b >= 64) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < 64; i++) c[cpos+i] = x[i]; - u = 1; - for (i = 8; i < 16; i++) { - u = u + (z[i] & 0xff) | 0; - z[i] = u & 0xff; - u >>>= 8; + if (Path.isAbsolute) { // node >= 0.11 + return Path.isAbsolute(path); } - b -= 64; - cpos += 64; - } - if (b > 0) { - crypto_core_salsa20(x,z,k,sigma); - for (i = 0; i < b; i++) c[cpos+i] = x[i]; - } - return 0; -} -function crypto_stream(c,cpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20(c,cpos,d,sn,s); -} + platform = platform || process.platform; -function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s,n,k,sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i+16]; - return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); -} + // Unix -/* -* Port of Andrew Moon's Poly1305-donna-16. Public domain. -* https://github.com/floodyberry/poly1305-donna -*/ + if (platform !== 'win32') { + return path[0] === '/'; + } -var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; + // Windows - var t0, t1, t2, t3, t4, t5, t6, t7; + return !!/^(?:[a-zA-Z]:[\\\/])|(?:[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/])/.test(path); // C:\ or \\something\something +}; - t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; - t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; - t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; - this.r[5] = ((t4 >>> 1)) & 0x1ffe; - t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; - t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - this.r[9] = ((t7 >>> 5)) & 0x007f; - this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; - this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; - this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; - this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; - this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; - this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; - this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; - this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +exports.isInteger = function (value) { + + return (typeof value === 'number' && + parseFloat(value) === parseInt(value, 10) && + !isNaN(value)); }; -poly1305.prototype.blocks = function(m, mpos, bytes) { - var hibit = this.fin ? 0 : (1 << 11); - var t0, t1, t2, t3, t4, t5, t6, t7, c; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - var h0 = this.h[0], - h1 = this.h[1], - h2 = this.h[2], - h3 = this.h[3], - h4 = this.h[4], - h5 = this.h[5], - h6 = this.h[6], - h7 = this.h[7], - h8 = this.h[8], - h9 = this.h[9]; +exports.ignore = function () { }; - var r0 = this.r[0], - r1 = this.r[1], - r2 = this.r[2], - r3 = this.r[3], - r4 = this.r[4], - r5 = this.r[5], - r6 = this.r[6], - r7 = this.r[7], - r8 = this.r[8], - r9 = this.r[9]; - while (bytes >= 16) { - t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; - t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; - t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; - t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; - t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; - h5 += ((t4 >>> 1)) & 0x1fff; - t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; - t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; - t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; - h9 += ((t7 >>> 5)) | hibit; +exports.inherits = Util.inherits; - c = 0; - d0 = c; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h2 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c = (d0 >>> 13); d0 &= 0x1fff; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c += (d0 >>> 13); d0 &= 0x1fff; +exports.format = Util.format; - d1 = c; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h2 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c = (d1 >>> 13); d1 &= 0x1fff; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c += (d1 >>> 13); d1 &= 0x1fff; - d2 = c; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h2 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c = (d2 >>> 13); d2 &= 0x1fff; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c += (d2 >>> 13); d2 &= 0x1fff; +exports.transform = function (source, transform, options) { - d3 = c; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h2 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c = (d3 >>> 13); d3 &= 0x1fff; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c += (d3 >>> 13); d3 &= 0x1fff; + exports.assert(source === null || source === undefined || typeof source === 'object' || Array.isArray(source), 'Invalid source object: must be null, undefined, an object, or an array'); - d4 = c; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h2 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c = (d4 >>> 13); d4 &= 0x1fff; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c += (d4 >>> 13); d4 &= 0x1fff; + if (Array.isArray(source)) { + var results = []; + for (var i = 0, il = source.length; i < il; ++i) { + results.push(exports.transform(source[i], transform, options)); + } + return results; + } - d5 = c; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h2 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c = (d5 >>> 13); d5 &= 0x1fff; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c += (d5 >>> 13); d5 &= 0x1fff; + var result = {}; + var keys = Object.keys(transform); - d6 = c; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h2 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c = (d6 >>> 13); d6 &= 0x1fff; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c += (d6 >>> 13); d6 &= 0x1fff; + for (var k = 0, kl = keys.length; k < kl; ++k) { + var key = keys[k]; + var path = key.split('.'); + var sourcePath = transform[key]; - d7 = c; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h2 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c = (d7 >>> 13); d7 &= 0x1fff; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c += (d7 >>> 13); d7 &= 0x1fff; + exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings'); - d8 = c; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h2 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c = (d8 >>> 13); d8 &= 0x1fff; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c += (d8 >>> 13); d8 &= 0x1fff; + var segment; + var res = result; - d9 = c; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h2 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c = (d9 >>> 13); d9 &= 0x1fff; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c += (d9 >>> 13); d9 &= 0x1fff; + while (path.length > 1) { + segment = path.shift(); + if (!res[segment]) { + res[segment] = {}; + } + res = res[segment]; + } + segment = path.shift(); + res[segment] = exports.reach(source, sourcePath, options); + } - c = (((c << 2) + c)) | 0; - c = (c + d0) | 0; - d0 = c & 0x1fff; - c = (c >>> 13); - d1 += c; + return result; +}; - h0 = d0; - h1 = d1; - h2 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; - mpos += 16; - bytes -= 16; - } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h2; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; -}; +exports.uniqueFilename = function (path, extension) { -poly1305.prototype.finish = function(mac, macpos) { - var g = new Uint16Array(10); - var c, mask, f, i; + if (extension) { + extension = extension[0] !== '.' ? '.' + extension : extension; + } + else { + extension = ''; + } - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); - } + path = Path.resolve(path); + var name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension; + return Path.join(path, name); +}; - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - for (i = 2; i < 10; i++) { - this.h[i] += c; - c = this.h[i] >>> 13; - this.h[i] &= 0x1fff; - } - this.h[0] += (c * 5); - c = this.h[0] >>> 13; - this.h[0] &= 0x1fff; - this.h[1] += c; - c = this.h[1] >>> 13; - this.h[1] &= 0x1fff; - this.h[2] += c; - g[0] = this.h[0] + 5; - c = g[0] >>> 13; - g[0] &= 0x1fff; - for (i = 1; i < 10; i++) { - g[i] = this.h[i] + c; - c = g[i] >>> 13; - g[i] &= 0x1fff; - } - g[9] -= (1 << 13); +exports.stringify = function () { - mask = (c ^ 1) - 1; - for (i = 0; i < 10; i++) g[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; + try { + return JSON.stringify.apply(null, arguments); + } + catch (err) { + return '[Cannot display object: ' + err.message + ']'; + } +}; - this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; - this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; - this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; - this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; - this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; - this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; - this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; - this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; - f = this.h[0] + this.pad[0]; - this.h[0] = f & 0xffff; - for (i = 1; i < 8; i++) { - f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; - this.h[i] = f & 0xffff; - } +exports.shallow = function (source) { - mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; - mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; - mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; - mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; - mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; - mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; - mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; - mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; - mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; - mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; - mac[macpos+10] = (this.h[5] >>> 0) & 0xff; - mac[macpos+11] = (this.h[5] >>> 8) & 0xff; - mac[macpos+12] = (this.h[6] >>> 0) & 0xff; - mac[macpos+13] = (this.h[6] >>> 8) & 0xff; - mac[macpos+14] = (this.h[7] >>> 0) & 0xff; - mac[macpos+15] = (this.h[7] >>> 8) & 0xff; + var target = {}; + var keys = Object.keys(source); + for (var i = 0, il = keys.length; i < il; ++i) { + var key = keys[i]; + target[key] = source[key]; + } + + return target; }; -poly1305.prototype.update = function(m, mpos, bytes) { - var i, want; - if (this.leftover) { - want = (16 - this.leftover); - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; - } +/***/ }), +/* 133 */ +/***/ (function(module, exports, __webpack_require__) { - if (bytes >= 16) { - want = bytes - (bytes % 16); - this.blocks(m, mpos, want); - mpos += want; - bytes -= want; - } +// Copyright 2012 Joyent, Inc. All rights reserved. - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m[mpos+i]; - this.leftover += bytes; - } +var assert = __webpack_require__(134); +var sshpk = __webpack_require__(226); +var util = __webpack_require__(2); + +var HASH_ALGOS = { + 'sha1': true, + 'sha256': true, + 'sha512': true }; -function crypto_onetimeauth(out, outpos, m, mpos, n, k) { - var s = new poly1305(k); - s.update(m, mpos, n); - s.finish(out, outpos); - return 0; -} +var PK_ALGOS = { + 'rsa': true, + 'dsa': true, + 'ecdsa': true +}; -function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { - var x = new Uint8Array(16); - crypto_onetimeauth(x,0,m,mpos,n,k); - return crypto_verify_16(h,hpos,x,0); -} +function HttpSignatureError(message, caller) { + if (Error.captureStackTrace) + Error.captureStackTrace(this, caller || HttpSignatureError); -function crypto_secretbox(c,m,d,n,k) { - var i; - if (d < 32) return -1; - crypto_stream_xor(c,0,m,0,d,n,k); - crypto_onetimeauth(c, 16, c, 32, d - 32, c); - for (i = 0; i < 16; i++) c[i] = 0; - return 0; + this.message = message; + this.name = caller.name; } +util.inherits(HttpSignatureError, Error); -function crypto_secretbox_open(m,c,d,n,k) { - var i; - var x = new Uint8Array(32); - if (d < 32) return -1; - crypto_stream(x,0,32,n,k); - if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; - crypto_stream_xor(m,0,c,0,d,n,k); - for (i = 0; i < 32; i++) m[i] = 0; - return 0; +function InvalidAlgorithmError(message) { + HttpSignatureError.call(this, message, InvalidAlgorithmError); } +util.inherits(InvalidAlgorithmError, HttpSignatureError); -function set25519(r, a) { - var i; - for (i = 0; i < 16; i++) r[i] = a[i]|0; -} +function validateAlgorithm(algorithm) { + var alg = algorithm.toLowerCase().split('-'); -function car25519(o) { - var i, v, c = 1; - for (i = 0; i < 16; i++) { - v = o[i] + c + 65535; - c = Math.floor(v / 65536); - o[i] = v - c * 65536; + if (alg.length !== 2) { + throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + + 'valid algorithm')); } - o[0] += c-1 + 37 * (c-1); -} -function sel25519(p, q, b) { - var t, c = ~(b-1); - for (var i = 0; i < 16; i++) { - t = c & (p[i] ^ q[i]); - p[i] ^= t; - q[i] ^= t; + if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { + throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + + 'are not supported')); } -} -function pack25519(o, n) { - var i, j, b; - var m = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m[0] = t[0] - 0xffed; - for (i = 1; i < 15; i++) { - m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); - m[i-1] &= 0xffff; - } - m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); - b = (m[15]>>16) & 1; - m[14] &= 0xffff; - sel25519(t, m, 1-b); - } - for (i = 0; i < 16; i++) { - o[2*i] = t[i] & 0xff; - o[2*i+1] = t[i]>>8; + if (!HASH_ALGOS[alg[1]]) { + throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + + 'supported hash algorithm')); } -} -function neq25519(a, b) { - var c = new Uint8Array(32), d = new Uint8Array(32); - pack25519(c, a); - pack25519(d, b); - return crypto_verify_32(c, 0, d, 0); + return (alg); } -function par25519(a) { - var d = new Uint8Array(32); - pack25519(d, a); - return d[0] & 1; +///--- API + +module.exports = { + + HASH_ALGOS: HASH_ALGOS, + PK_ALGOS: PK_ALGOS, + + HttpSignatureError: HttpSignatureError, + InvalidAlgorithmError: InvalidAlgorithmError, + + validateAlgorithm: validateAlgorithm, + + /** + * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. + * + * The intent of this module is to interoperate with OpenSSL only, + * specifically the node crypto module's `verify` method. + * + * @param {String} key an OpenSSH public key. + * @return {String} PEM encoded form of the RSA public key. + * @throws {TypeError} on bad input. + * @throws {Error} on invalid ssh key formatted data. + */ + sshKeyToPEM: function sshKeyToPEM(key) { + assert.string(key, 'ssh_key'); + + var k = sshpk.parseKey(key, 'ssh'); + return (k.toString('pem')); + }, + + + /** + * Generates an OpenSSH fingerprint from an ssh public key. + * + * @param {String} key an OpenSSH public key. + * @return {String} key fingerprint. + * @throws {TypeError} on bad input. + * @throws {Error} if what you passed doesn't look like an ssh public key. + */ + fingerprint: function fingerprint(key) { + assert.string(key, 'ssh_key'); + + var k = sshpk.parseKey(key, 'ssh'); + return (k.fingerprint('md5').toString('hex')); + }, + + /** + * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) + * + * The reverse of the above function. + */ + pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { + assert.equal('string', typeof (pem), 'typeof pem'); + + var k = sshpk.parseKey(pem, 'pem'); + k.comment = comment; + return (k.toString('ssh')); + } +}; + + +/***/ }), +/* 134 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright (c) 2012, Mark Cavage. All rights reserved. +// Copyright 2015 Joyent, Inc. + +var assert = __webpack_require__(18); +var Stream = __webpack_require__(26).Stream; +var util = __webpack_require__(2); + + +///--- Globals + +/* JSSTYLED */ +var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; + + +///--- Internal + +function _capitalize(str) { + return (str.charAt(0).toUpperCase() + str.slice(1)); } -function unpack25519(o, n) { - var i; - for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); - o[15] &= 0x7fff; +function _toss(name, expected, oper, arg, actual) { + throw new assert.AssertionError({ + message: util.format('%s (%s) is required', name, expected), + actual: (actual === undefined) ? typeof (arg) : actual(arg), + expected: expected, + operator: oper || '===', + stackStartFunction: _toss.caller + }); } -function A(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +function _getClass(arg) { + return (Object.prototype.toString.call(arg).slice(8, -1)); } -function Z(o, a, b) { - for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +function noop() { + // Why even bother with asserts? } -function M(o, a, b) { - var v, c, - t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, - t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, - t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, - t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, - b0 = b[0], - b1 = b[1], - b2 = b[2], - b3 = b[3], - b4 = b[4], - b5 = b[5], - b6 = b[6], - b7 = b[7], - b8 = b[8], - b9 = b[9], - b10 = b[10], - b11 = b[11], - b12 = b[12], - b13 = b[13], - b14 = b[14], - b15 = b[15]; - v = a[0]; - t0 += v * b0; - t1 += v * b1; - t2 += v * b2; - t3 += v * b3; - t4 += v * b4; - t5 += v * b5; - t6 += v * b6; - t7 += v * b7; - t8 += v * b8; - t9 += v * b9; - t10 += v * b10; - t11 += v * b11; - t12 += v * b12; - t13 += v * b13; - t14 += v * b14; - t15 += v * b15; - v = a[1]; - t1 += v * b0; - t2 += v * b1; - t3 += v * b2; - t4 += v * b3; - t5 += v * b4; - t6 += v * b5; - t7 += v * b6; - t8 += v * b7; - t9 += v * b8; - t10 += v * b9; - t11 += v * b10; - t12 += v * b11; - t13 += v * b12; - t14 += v * b13; - t15 += v * b14; - t16 += v * b15; - v = a[2]; - t2 += v * b0; - t3 += v * b1; - t4 += v * b2; - t5 += v * b3; - t6 += v * b4; - t7 += v * b5; - t8 += v * b6; - t9 += v * b7; - t10 += v * b8; - t11 += v * b9; - t12 += v * b10; - t13 += v * b11; - t14 += v * b12; - t15 += v * b13; - t16 += v * b14; - t17 += v * b15; - v = a[3]; - t3 += v * b0; - t4 += v * b1; - t5 += v * b2; - t6 += v * b3; - t7 += v * b4; - t8 += v * b5; - t9 += v * b6; - t10 += v * b7; - t11 += v * b8; - t12 += v * b9; - t13 += v * b10; - t14 += v * b11; - t15 += v * b12; - t16 += v * b13; - t17 += v * b14; - t18 += v * b15; - v = a[4]; - t4 += v * b0; - t5 += v * b1; - t6 += v * b2; - t7 += v * b3; - t8 += v * b4; - t9 += v * b5; - t10 += v * b6; - t11 += v * b7; - t12 += v * b8; - t13 += v * b9; - t14 += v * b10; - t15 += v * b11; - t16 += v * b12; - t17 += v * b13; - t18 += v * b14; - t19 += v * b15; - v = a[5]; - t5 += v * b0; - t6 += v * b1; - t7 += v * b2; - t8 += v * b3; - t9 += v * b4; - t10 += v * b5; - t11 += v * b6; - t12 += v * b7; - t13 += v * b8; - t14 += v * b9; - t15 += v * b10; - t16 += v * b11; - t17 += v * b12; - t18 += v * b13; - t19 += v * b14; - t20 += v * b15; - v = a[6]; - t6 += v * b0; - t7 += v * b1; - t8 += v * b2; - t9 += v * b3; - t10 += v * b4; - t11 += v * b5; - t12 += v * b6; - t13 += v * b7; - t14 += v * b8; - t15 += v * b9; - t16 += v * b10; - t17 += v * b11; - t18 += v * b12; - t19 += v * b13; - t20 += v * b14; - t21 += v * b15; - v = a[7]; - t7 += v * b0; - t8 += v * b1; - t9 += v * b2; - t10 += v * b3; - t11 += v * b4; - t12 += v * b5; - t13 += v * b6; - t14 += v * b7; - t15 += v * b8; - t16 += v * b9; - t17 += v * b10; - t18 += v * b11; - t19 += v * b12; - t20 += v * b13; - t21 += v * b14; - t22 += v * b15; - v = a[8]; - t8 += v * b0; - t9 += v * b1; - t10 += v * b2; - t11 += v * b3; - t12 += v * b4; - t13 += v * b5; - t14 += v * b6; - t15 += v * b7; - t16 += v * b8; - t17 += v * b9; - t18 += v * b10; - t19 += v * b11; - t20 += v * b12; - t21 += v * b13; - t22 += v * b14; - t23 += v * b15; - v = a[9]; - t9 += v * b0; - t10 += v * b1; - t11 += v * b2; - t12 += v * b3; - t13 += v * b4; - t14 += v * b5; - t15 += v * b6; - t16 += v * b7; - t17 += v * b8; - t18 += v * b9; - t19 += v * b10; - t20 += v * b11; - t21 += v * b12; - t22 += v * b13; - t23 += v * b14; - t24 += v * b15; - v = a[10]; - t10 += v * b0; - t11 += v * b1; - t12 += v * b2; - t13 += v * b3; - t14 += v * b4; - t15 += v * b5; - t16 += v * b6; - t17 += v * b7; - t18 += v * b8; - t19 += v * b9; - t20 += v * b10; - t21 += v * b11; - t22 += v * b12; - t23 += v * b13; - t24 += v * b14; - t25 += v * b15; - v = a[11]; - t11 += v * b0; - t12 += v * b1; - t13 += v * b2; - t14 += v * b3; - t15 += v * b4; - t16 += v * b5; - t17 += v * b6; - t18 += v * b7; - t19 += v * b8; - t20 += v * b9; - t21 += v * b10; - t22 += v * b11; - t23 += v * b12; - t24 += v * b13; - t25 += v * b14; - t26 += v * b15; - v = a[12]; - t12 += v * b0; - t13 += v * b1; - t14 += v * b2; - t15 += v * b3; - t16 += v * b4; - t17 += v * b5; - t18 += v * b6; - t19 += v * b7; - t20 += v * b8; - t21 += v * b9; - t22 += v * b10; - t23 += v * b11; - t24 += v * b12; - t25 += v * b13; - t26 += v * b14; - t27 += v * b15; - v = a[13]; - t13 += v * b0; - t14 += v * b1; - t15 += v * b2; - t16 += v * b3; - t17 += v * b4; - t18 += v * b5; - t19 += v * b6; - t20 += v * b7; - t21 += v * b8; - t22 += v * b9; - t23 += v * b10; - t24 += v * b11; - t25 += v * b12; - t26 += v * b13; - t27 += v * b14; - t28 += v * b15; - v = a[14]; - t14 += v * b0; - t15 += v * b1; - t16 += v * b2; - t17 += v * b3; - t18 += v * b4; - t19 += v * b5; - t20 += v * b6; - t21 += v * b7; - t22 += v * b8; - t23 += v * b9; - t24 += v * b10; - t25 += v * b11; - t26 += v * b12; - t27 += v * b13; - t28 += v * b14; - t29 += v * b15; - v = a[15]; - t15 += v * b0; - t16 += v * b1; - t17 += v * b2; - t18 += v * b3; - t19 += v * b4; - t20 += v * b5; - t21 += v * b6; - t22 += v * b7; - t23 += v * b8; - t24 += v * b9; - t25 += v * b10; - t26 += v * b11; - t27 += v * b12; - t28 += v * b13; - t29 += v * b14; - t30 += v * b15; +///--- Exports - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - // t15 left as is +var types = { + bool: { + check: function (arg) { return typeof (arg) === 'boolean'; } + }, + func: { + check: function (arg) { return typeof (arg) === 'function'; } + }, + string: { + check: function (arg) { return typeof (arg) === 'string'; } + }, + object: { + check: function (arg) { + return typeof (arg) === 'object' && arg !== null; + } + }, + number: { + check: function (arg) { + return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); + } + }, + buffer: { + check: function (arg) { return Buffer.isBuffer(arg); }, + operator: 'Buffer.isBuffer' + }, + array: { + check: function (arg) { return Array.isArray(arg); }, + operator: 'Array.isArray' + }, + stream: { + check: function (arg) { return arg instanceof Stream; }, + operator: 'instanceof', + actual: _getClass + }, + date: { + check: function (arg) { return arg instanceof Date; }, + operator: 'instanceof', + actual: _getClass + }, + regexp: { + check: function (arg) { return arg instanceof RegExp; }, + operator: 'instanceof', + actual: _getClass + }, + uuid: { + check: function (arg) { + return typeof (arg) === 'string' && UUID_REGEXP.test(arg); + }, + operator: 'isUUID' + } +}; - // first car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); +function _setExports(ndebug) { + var keys = Object.keys(types); + var out; - // second car - c = 1; - v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; - v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; - v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; - v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; - v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; - v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; - v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; - v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; - v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; - v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; - v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; - v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; - v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; - v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; - v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; - v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; - t0 += c-1 + 37 * (c-1); + /* re-export standard assert */ + if (process.env.NODE_NDEBUG) { + out = noop; + } else { + out = function (arg, msg) { + if (!arg) { + _toss(msg, 'true', arg); + } + }; + } - o[ 0] = t0; - o[ 1] = t1; - o[ 2] = t2; - o[ 3] = t3; - o[ 4] = t4; - o[ 5] = t5; - o[ 6] = t6; - o[ 7] = t7; - o[ 8] = t8; - o[ 9] = t9; - o[10] = t10; - o[11] = t11; - o[12] = t12; - o[13] = t13; - o[14] = t14; - o[15] = t15; -} + /* standard checks */ + keys.forEach(function (k) { + if (ndebug) { + out[k] = noop; + return; + } + var type = types[k]; + out[k] = function (arg, msg) { + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); -function S(o, a) { - M(o, a, a); -} + /* optional checks */ + keys.forEach(function (k) { + var name = 'optional' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!type.check(arg)) { + _toss(msg, k, type.operator, arg, type.actual); + } + }; + }); -function inv25519(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 253; a >= 0; a--) { - S(c, c); - if(a !== 2 && a !== 4) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} + /* arrayOf checks */ + keys.forEach(function (k) { + var name = 'arrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); -function pow2523(o, i) { - var c = gf(); - var a; - for (a = 0; a < 16; a++) c[a] = i[a]; - for (a = 250; a >= 0; a--) { - S(c, c); - if(a !== 1) M(c, c, i); - } - for (a = 0; a < 16; a++) o[a] = c[a]; -} + /* optionalArrayOf checks */ + keys.forEach(function (k) { + var name = 'optionalArrayOf' + _capitalize(k); + if (ndebug) { + out[name] = noop; + return; + } + var type = types[k]; + var expected = '[' + k + ']'; + out[name] = function (arg, msg) { + if (arg === undefined || arg === null) { + return; + } + if (!Array.isArray(arg)) { + _toss(msg, expected, type.operator, arg, type.actual); + } + var i; + for (i = 0; i < arg.length; i++) { + if (!type.check(arg[i])) { + _toss(msg, expected, type.operator, arg, type.actual); + } + } + }; + }); -function crypto_scalarmult(q, n, p) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r, i; - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31]=(n[31]&127)|64; - z[0]&=248; - unpack25519(x,p); - for (i = 0; i < 16; i++) { - b[i]=x[i]; - d[i]=a[i]=c[i]=0; - } - a[0]=d[0]=1; - for (i=254; i>=0; --i) { - r=(z[i>>>3]>>>(i&7))&1; - sel25519(a,b,r); - sel25519(c,d,r); - A(e,a,c); - Z(a,a,c); - A(c,b,d); - Z(b,b,d); - S(d,e); - S(f,a); - M(a,c,a); - M(c,b,e); - A(e,a,c); - Z(a,a,c); - S(b,a); - Z(c,d,f); - M(a,c,_121665); - A(a,a,d); - M(c,c,a); - M(a,d,f); - M(d,b,x); - S(b,e); - sel25519(a,b,r); - sel25519(c,d,r); - } - for (i = 0; i < 16; i++) { - x[i+16]=a[i]; - x[i+32]=c[i]; - x[i+48]=b[i]; - x[i+64]=d[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32,x32); - M(x16,x16,x32); - pack25519(q,x16); - return 0; -} + /* re-export built-in assertions */ + Object.keys(assert).forEach(function (k) { + if (k === 'AssertionError') { + out[k] = assert[k]; + return; + } + if (ndebug) { + out[k] = noop; + return; + } + out[k] = assert[k]; + }); -function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); -} + /* export ourselves (for unit tests _only_) */ + out._setExports = _setExports; -function crypto_box_keypair(y, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y, x); + return out; } -function crypto_box_beforenm(k, y, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y); - return crypto_core_hsalsa20(k, _0, s, sigma); -} +module.exports = _setExports(process.env.NODE_NDEBUG); -var crypto_box_afternm = crypto_secretbox; -var crypto_box_open_afternm = crypto_secretbox_open; -function crypto_box(c, m, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_afternm(c, m, d, n, k); -} +/***/ }), +/* 135 */ +/***/ (function(module, exports, __webpack_require__) { -function crypto_box_open(m, c, d, n, y, x) { - var k = new Uint8Array(32); - crypto_box_beforenm(k, y, x); - return crypto_box_open_afternm(m, c, d, n, k); -} +"use strict"; -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; +var chalk = __webpack_require__(20); +var figures = __webpack_require__(206); -function crypto_hashblocks_hl(hh, hl, m, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), - bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, - bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, - th, tl, i, j, h, l, a, b, c, d; +/** + * Separator object + * Used to space/separate choices group + * @constructor + * @param {String} line Separation line content (facultative) + */ - var ah0 = hh[0], - ah1 = hh[1], - ah2 = hh[2], - ah3 = hh[3], - ah4 = hh[4], - ah5 = hh[5], - ah6 = hh[6], - ah7 = hh[7], +var Separator = module.exports = function (line) { + this.type = 'separator'; + this.line = chalk.dim(line || new Array(15).join(figures.line)); +}; - al0 = hl[0], - al1 = hl[1], - al2 = hl[2], - al3 = hl[3], - al4 = hl[4], - al5 = hl[5], - al6 = hl[6], - al7 = hl[7]; - - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; - wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; - } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; - - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; - - // add - h = ah7; - l = al7; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +/** + * Helper function returning false if object is a separator + * @param {Object} obj object to test against + * @return {Boolean} `false` if object is a separator + */ - // Sigma1 - h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); - l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); +Separator.exclude = function (obj) { + return obj.type !== 'separator'; +}; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +/** + * Stringify separator + * @return {String} the separator display string + */ - // Ch - h = (ah4 & ah5) ^ (~ah4 & ah6); - l = (al4 & al5) ^ (~al4 & al6); +Separator.prototype.toString = function () { + return this.line; +}; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - // K - h = K[i*2]; - l = K[i*2+1]; +/***/ }), +/* 136 */ +/***/ (function(module, exports, __webpack_require__) { - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +"use strict"; - // w - h = wh[i%16]; - l = wl[i%16]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +var _ = __webpack_require__(28); +var chalk = __webpack_require__(20); - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +/** + * The paginator keep trakcs of a pointer index in a list and return + * a subset of the choices if the list is too long. + */ - th = c & 0xffff | d << 16; - tl = a & 0xffff | b << 16; +var Paginator = module.exports = function () { + this.pointer = 0; + this.lastIndex = 0; +}; - // add - h = th; - l = tl; +Paginator.prototype.paginate = function (output, active, pageSize) { + pageSize = pageSize || 7; + var middleOfList = Math.floor(pageSize / 2); + var lines = output.split('\n'); - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + // Make sure there's enough lines to paginate + if (lines.length <= pageSize) { + return output; + } - // Sigma0 - h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); - l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); + // Move the pointer only when the user go down and limit it to the middle of the list + if (this.pointer < middleOfList && this.lastIndex < active && active - this.lastIndex < pageSize) { + this.pointer = Math.min(middleOfList, this.pointer + active - this.lastIndex); + } + this.lastIndex = active; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + // Duplicate the lines so it give an infinite list look + var infinite = _.flatten([lines, lines, lines]); + var topIndex = Math.max(0, active + lines.length - this.pointer); - // Maj - h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); - l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); + var section = infinite.splice(topIndex, pageSize).join('\n'); + return section + '\n' + chalk.dim('(Move up and down to reveal more choices)'); +}; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +/***/ }), +/* 137 */ +/***/ (function(module, exports) { - bh7 = (c & 0xffff) | (d << 16); - bl7 = (a & 0xffff) | (b << 16); +/*! + * is-extglob <https://github.com/jonschlinkert/is-extglob> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - // add - h = bh3; - l = bl3; +module.exports = function isExtglob(str) { + return typeof str === 'string' + && /[@?!+*]\(/.test(str); +}; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - h = th; - l = tl; +/***/ }), +/* 138 */ +/***/ (function(module, exports, __webpack_require__) { - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +/*! + * is-glob <https://github.com/jonschlinkert/is-glob> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +var isExtglob = __webpack_require__(137); - bh3 = (c & 0xffff) | (d << 16); - bl3 = (a & 0xffff) | (b << 16); +module.exports = function isGlob(str) { + return typeof str === 'string' + && (/[*!?{}(|)[\]]/.test(str) + || isExtglob(str)); +}; - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; +/***/ }), +/* 139 */ +/***/ (function(module, exports, __webpack_require__) { - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; +"use strict"; - if (i%16 === 15) { - for (j = 0; j < 16; j++) { - // add - h = wh[j]; - l = wl[j]; +/** + * @fileOverview + * Core operations on curve 25519 required for the higher level modules. + */ - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +/* + * Copyright (c) 2007, 2013, 2014 Michele Bini + * Copyright (c) 2014 Mega Limited + * under the MIT License. + * + * Authors: Guy K. Kloss, Michele Bini + * + * You should have received a copy of the license along with this program. + */ - h = wh[(j+9)%16]; - l = wl[(j+9)%16]; +var crypto = __webpack_require__(8); - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + /** + * @exports jodid25519/core + * Core operations on curve 25519 required for the higher level modules. + * + * @description + * Core operations on curve 25519 required for the higher level modules. + * + * <p> + * This core code is extracted from Michele Bini's curve255.js implementation, + * which is used as a base for Curve25519 ECDH and Ed25519 EdDSA operations. + * </p> + */ + var ns = {}; - // sigma0 - th = wh[(j+1)%16]; - tl = wl[(j+1)%16]; - h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); - l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); + function _setbit(n, c, v) { + var i = c >> 4; + var a = n[i]; + a = a + (1 << (c & 0xf)) * v; + n[i] = a; + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + function _getbit(n, c) { + return (n[c >> 4] >> (c & 0xf)) & 1; + } - // sigma1 - th = wh[(j+14)%16]; - tl = wl[(j+14)%16]; - h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); - l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); + function _ZERO() { + return [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + function _ONE() { + return [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + // Basepoint. + function _BASE() { + return [9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + } - wh[j] = (c & 0xffff) | (d << 16); - wl[j] = (a & 0xffff) | (b << 16); + // return -1, 0, +1 when a is less than, equal, or greater than b + function _bigintcmp(a, b) { + // The following code is a bit tricky to avoid code branching + var c, abs_r, mask; + var r = 0; + for (c = 15; c >= 0; c--) { + var x = a[c]; + var y = b[c]; + r = r + (x - y) * (1 - r * r); + // http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs + // correct for [-294967295, 294967295] + mask = r >> 31; + abs_r = (r + mask) ^ mask; + // http://stackoverflow.com/questions/596467/how-do-i-convert-a-number-to-an-integer-in-javascript + // this rounds towards zero + r = ~~((r << 1) / (abs_r + 1)); } - } + return r; } - // add - h = ah0; - l = al0; - - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; - - h = hh[0]; - l = hl[0]; + function _bigintadd(a, b) { + var r = []; + var v; + r[0] = (v = a[0] + b[0]) & 0xffff; + r[1] = (v = (v >>> 16) + a[1] + b[1]) & 0xffff; + r[2] = (v = (v >>> 16) + a[2] + b[2]) & 0xffff; + r[3] = (v = (v >>> 16) + a[3] + b[3]) & 0xffff; + r[4] = (v = (v >>> 16) + a[4] + b[4]) & 0xffff; + r[5] = (v = (v >>> 16) + a[5] + b[5]) & 0xffff; + r[6] = (v = (v >>> 16) + a[6] + b[6]) & 0xffff; + r[7] = (v = (v >>> 16) + a[7] + b[7]) & 0xffff; + r[8] = (v = (v >>> 16) + a[8] + b[8]) & 0xffff; + r[9] = (v = (v >>> 16) + a[9] + b[9]) & 0xffff; + r[10] = (v = (v >>> 16) + a[10] + b[10]) & 0xffff; + r[11] = (v = (v >>> 16) + a[11] + b[11]) & 0xffff; + r[12] = (v = (v >>> 16) + a[12] + b[12]) & 0xffff; + r[13] = (v = (v >>> 16) + a[13] + b[13]) & 0xffff; + r[14] = (v = (v >>> 16) + a[14] + b[14]) & 0xffff; + r[15] = (v >>> 16) + a[15] + b[15]; + return r; + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + function _bigintsub(a, b) { + var r = []; + var v; + r[0] = (v = 0x80000 + a[0] - b[0]) & 0xffff; + r[1] = (v = (v >>> 16) + 0x7fff8 + a[1] - b[1]) & 0xffff; + r[2] = (v = (v >>> 16) + 0x7fff8 + a[2] - b[2]) & 0xffff; + r[3] = (v = (v >>> 16) + 0x7fff8 + a[3] - b[3]) & 0xffff; + r[4] = (v = (v >>> 16) + 0x7fff8 + a[4] - b[4]) & 0xffff; + r[5] = (v = (v >>> 16) + 0x7fff8 + a[5] - b[5]) & 0xffff; + r[6] = (v = (v >>> 16) + 0x7fff8 + a[6] - b[6]) & 0xffff; + r[7] = (v = (v >>> 16) + 0x7fff8 + a[7] - b[7]) & 0xffff; + r[8] = (v = (v >>> 16) + 0x7fff8 + a[8] - b[8]) & 0xffff; + r[9] = (v = (v >>> 16) + 0x7fff8 + a[9] - b[9]) & 0xffff; + r[10] = (v = (v >>> 16) + 0x7fff8 + a[10] - b[10]) & 0xffff; + r[11] = (v = (v >>> 16) + 0x7fff8 + a[11] - b[11]) & 0xffff; + r[12] = (v = (v >>> 16) + 0x7fff8 + a[12] - b[12]) & 0xffff; + r[13] = (v = (v >>> 16) + 0x7fff8 + a[13] - b[13]) & 0xffff; + r[14] = (v = (v >>> 16) + 0x7fff8 + a[14] - b[14]) & 0xffff; + r[15] = (v >>> 16) - 8 + a[15] - b[15]; + return r; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + function _sqr8h(a7, a6, a5, a4, a3, a2, a1, a0) { + // 'division by 0x10000' can not be replaced by '>> 16' because + // more than 32 bits of precision are needed similarly + // 'multiplication by 2' cannot be replaced by '<< 1' + var r = []; + var v; + r[0] = (v = a0 * a0) & 0xffff; + r[1] = (v = (0 | (v / 0x10000)) + 2 * a0 * a1) & 0xffff; + r[2] = (v = (0 | (v / 0x10000)) + 2 * a0 * a2 + a1 * a1) & 0xffff; + r[3] = (v = (0 | (v / 0x10000)) + 2 * a0 * a3 + 2 * a1 * a2) & 0xffff; + r[4] = (v = (0 | (v / 0x10000)) + 2 * a0 * a4 + 2 * a1 * a3 + a2 + * a2) & 0xffff; + r[5] = (v = (0 | (v / 0x10000)) + 2 * a0 * a5 + 2 * a1 * a4 + 2 + * a2 * a3) & 0xffff; + r[6] = (v = (0 | (v / 0x10000)) + 2 * a0 * a6 + 2 * a1 * a5 + 2 + * a2 * a4 + a3 * a3) & 0xffff; + r[7] = (v = (0 | (v / 0x10000)) + 2 * a0 * a7 + 2 * a1 * a6 + 2 + * a2 * a5 + 2 * a3 * a4) & 0xffff; + r[8] = (v = (0 | (v / 0x10000)) + 2 * a1 * a7 + 2 * a2 * a6 + 2 + * a3 * a5 + a4 * a4) & 0xffff; + r[9] = (v = (0 | (v / 0x10000)) + 2 * a2 * a7 + 2 * a3 * a6 + 2 + * a4 * a5) & 0xffff; + r[10] = (v = (0 | (v / 0x10000)) + 2 * a3 * a7 + 2 * a4 * a6 + + a5 * a5) & 0xffff; + r[11] = (v = (0 | (v / 0x10000)) + 2 * a4 * a7 + 2 * a5 * a6) & 0xffff; + r[12] = (v = (0 | (v / 0x10000)) + 2 * a5 * a7 + a6 * a6) & 0xffff; + r[13] = (v = (0 | (v / 0x10000)) + 2 * a6 * a7) & 0xffff; + r[14] = (v = (0 | (v / 0x10000)) + a7 * a7) & 0xffff; + r[15] = 0 | (v / 0x10000); + return r; + } - hh[0] = ah0 = (c & 0xffff) | (d << 16); - hl[0] = al0 = (a & 0xffff) | (b << 16); + function _sqrmodp(a) { + var x = _sqr8h(a[15], a[14], a[13], a[12], a[11], a[10], a[9], + a[8]); + var z = _sqr8h(a[7], a[6], a[5], a[4], a[3], a[2], a[1], a[0]); + var y = _sqr8h(a[15] + a[7], a[14] + a[6], a[13] + a[5], a[12] + + a[4], + a[11] + a[3], a[10] + a[2], a[9] + a[1], a[8] + + a[0]); + var r = []; + var v; + r[0] = (v = 0x800000 + z[0] + (y[8] - x[8] - z[8] + x[0] - 0x80) + * 38) & 0xffff; + r[1] = (v = 0x7fff80 + (v >>> 16) + z[1] + + (y[9] - x[9] - z[9] + x[1]) * 38) & 0xffff; + r[2] = (v = 0x7fff80 + (v >>> 16) + z[2] + + (y[10] - x[10] - z[10] + x[2]) * 38) & 0xffff; + r[3] = (v = 0x7fff80 + (v >>> 16) + z[3] + + (y[11] - x[11] - z[11] + x[3]) * 38) & 0xffff; + r[4] = (v = 0x7fff80 + (v >>> 16) + z[4] + + (y[12] - x[12] - z[12] + x[4]) * 38) & 0xffff; + r[5] = (v = 0x7fff80 + (v >>> 16) + z[5] + + (y[13] - x[13] - z[13] + x[5]) * 38) & 0xffff; + r[6] = (v = 0x7fff80 + (v >>> 16) + z[6] + + (y[14] - x[14] - z[14] + x[6]) * 38) & 0xffff; + r[7] = (v = 0x7fff80 + (v >>> 16) + z[7] + + (y[15] - x[15] - z[15] + x[7]) * 38) & 0xffff; + r[8] = (v = 0x7fff80 + (v >>> 16) + z[8] + y[0] - x[0] - z[0] + + x[8] * 38) & 0xffff; + r[9] = (v = 0x7fff80 + (v >>> 16) + z[9] + y[1] - x[1] - z[1] + + x[9] * 38) & 0xffff; + r[10] = (v = 0x7fff80 + (v >>> 16) + z[10] + y[2] - x[2] - z[2] + + x[10] * 38) & 0xffff; + r[11] = (v = 0x7fff80 + (v >>> 16) + z[11] + y[3] - x[3] - z[3] + + x[11] * 38) & 0xffff; + r[12] = (v = 0x7fff80 + (v >>> 16) + z[12] + y[4] - x[4] - z[4] + + x[12] * 38) & 0xffff; + r[13] = (v = 0x7fff80 + (v >>> 16) + z[13] + y[5] - x[5] - z[5] + + x[13] * 38) & 0xffff; + r[14] = (v = 0x7fff80 + (v >>> 16) + z[14] + y[6] - x[6] - z[6] + + x[14] * 38) & 0xffff; + r[15] = 0x7fff80 + (v >>> 16) + z[15] + y[7] - x[7] - z[7] + + x[15] * 38; + _reduce(r); + return r; + } - h = ah1; - l = al1; + function _mul8h(a7, a6, a5, a4, a3, a2, a1, a0, b7, b6, b5, b4, b3, + b2, b1, b0) { + // 'division by 0x10000' can not be replaced by '>> 16' because + // more than 32 bits of precision are needed + var r = []; + var v; + r[0] = (v = a0 * b0) & 0xffff; + r[1] = (v = (0 | (v / 0x10000)) + a0 * b1 + a1 * b0) & 0xffff; + r[2] = (v = (0 | (v / 0x10000)) + a0 * b2 + a1 * b1 + a2 * b0) & 0xffff; + r[3] = (v = (0 | (v / 0x10000)) + a0 * b3 + a1 * b2 + a2 * b1 + + a3 * b0) & 0xffff; + r[4] = (v = (0 | (v / 0x10000)) + a0 * b4 + a1 * b3 + a2 * b2 + + a3 * b1 + a4 * b0) & 0xffff; + r[5] = (v = (0 | (v / 0x10000)) + a0 * b5 + a1 * b4 + a2 * b3 + + a3 * b2 + a4 * b1 + a5 * b0) & 0xffff; + r[6] = (v = (0 | (v / 0x10000)) + a0 * b6 + a1 * b5 + a2 * b4 + + a3 * b3 + a4 * b2 + a5 * b1 + a6 * b0) & 0xffff; + r[7] = (v = (0 | (v / 0x10000)) + a0 * b7 + a1 * b6 + a2 * b5 + + a3 * b4 + a4 * b3 + a5 * b2 + a6 * b1 + a7 * b0) & 0xffff; + r[8] = (v = (0 | (v / 0x10000)) + a1 * b7 + a2 * b6 + a3 * b5 + + a4 * b4 + a5 * b3 + a6 * b2 + a7 * b1) & 0xffff; + r[9] = (v = (0 | (v / 0x10000)) + a2 * b7 + a3 * b6 + a4 * b5 + + a5 * b4 + a6 * b3 + a7 * b2) & 0xffff; + r[10] = (v = (0 | (v / 0x10000)) + a3 * b7 + a4 * b6 + a5 * b5 + + a6 * b4 + a7 * b3) & 0xffff; + r[11] = (v = (0 | (v / 0x10000)) + a4 * b7 + a5 * b6 + a6 * b5 + + a7 * b4) & 0xffff; + r[12] = (v = (0 | (v / 0x10000)) + a5 * b7 + a6 * b6 + a7 * b5) & 0xffff; + r[13] = (v = (0 | (v / 0x10000)) + a6 * b7 + a7 * b6) & 0xffff; + r[14] = (v = (0 | (v / 0x10000)) + a7 * b7) & 0xffff; + r[15] = (0 | (v / 0x10000)); + return r; + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + function _mulmodp(a, b) { + // Karatsuba multiplication scheme: x*y = (b^2+b)*x1*y1 - + // b*(x1-x0)*(y1-y0) + (b+1)*x0*y0 + var x = _mul8h(a[15], a[14], a[13], a[12], a[11], a[10], a[9], + a[8], b[15], b[14], b[13], b[12], b[11], b[10], + b[9], b[8]); + var z = _mul8h(a[7], a[6], a[5], a[4], a[3], a[2], a[1], a[0], + b[7], b[6], b[5], b[4], b[3], b[2], b[1], b[0]); + var y = _mul8h(a[15] + a[7], a[14] + a[6], a[13] + a[5], a[12] + + a[4], + a[11] + a[3], a[10] + a[2], a[9] + a[1], a[8] + + a[0], + b[15] + b[7], b[14] + b[6], b[13] + b[5], b[12] + + b[4], + b[11] + b[3], b[10] + b[2], b[9] + b[1], b[8] + + b[0]); + var r = []; + var v; + r[0] = (v = 0x800000 + z[0] + (y[8] - x[8] - z[8] + x[0] - 0x80) + * 38) & 0xffff; + r[1] = (v = 0x7fff80 + (v >>> 16) + z[1] + + (y[9] - x[9] - z[9] + x[1]) * 38) & 0xffff; + r[2] = (v = 0x7fff80 + (v >>> 16) + z[2] + + (y[10] - x[10] - z[10] + x[2]) * 38) & 0xffff; + r[3] = (v = 0x7fff80 + (v >>> 16) + z[3] + + (y[11] - x[11] - z[11] + x[3]) * 38) & 0xffff; + r[4] = (v = 0x7fff80 + (v >>> 16) + z[4] + + (y[12] - x[12] - z[12] + x[4]) * 38) & 0xffff; + r[5] = (v = 0x7fff80 + (v >>> 16) + z[5] + + (y[13] - x[13] - z[13] + x[5]) * 38) & 0xffff; + r[6] = (v = 0x7fff80 + (v >>> 16) + z[6] + + (y[14] - x[14] - z[14] + x[6]) * 38) & 0xffff; + r[7] = (v = 0x7fff80 + (v >>> 16) + z[7] + + (y[15] - x[15] - z[15] + x[7]) * 38) & 0xffff; + r[8] = (v = 0x7fff80 + (v >>> 16) + z[8] + y[0] - x[0] - z[0] + + x[8] * 38) & 0xffff; + r[9] = (v = 0x7fff80 + (v >>> 16) + z[9] + y[1] - x[1] - z[1] + + x[9] * 38) & 0xffff; + r[10] = (v = 0x7fff80 + (v >>> 16) + z[10] + y[2] - x[2] - z[2] + + x[10] * 38) & 0xffff; + r[11] = (v = 0x7fff80 + (v >>> 16) + z[11] + y[3] - x[3] - z[3] + + x[11] * 38) & 0xffff; + r[12] = (v = 0x7fff80 + (v >>> 16) + z[12] + y[4] - x[4] - z[4] + + x[12] * 38) & 0xffff; + r[13] = (v = 0x7fff80 + (v >>> 16) + z[13] + y[5] - x[5] - z[5] + + x[13] * 38) & 0xffff; + r[14] = (v = 0x7fff80 + (v >>> 16) + z[14] + y[6] - x[6] - z[6] + + x[14] * 38) & 0xffff; + r[15] = 0x7fff80 + (v >>> 16) + z[15] + y[7] - x[7] - z[7] + + x[15] * 38; + _reduce(r); + return r; + } - h = hh[1]; - l = hl[1]; + function _reduce(arr) { + var aCopy = arr.slice(0); + var choice = [arr, aCopy]; + var v = arr[15]; + // Use the dummy copy instead of just returning to be more constant time. + var a = choice[(v < 0x8000) & 1]; + a[15] = v & 0x7fff; + // >32-bits of precision are required here so '/ 0x8000' can not be + // replaced by the arithmetic equivalent '>>> 15' + v = (0 | (v / 0x8000)) * 19; + a[0] = (v += a[0]) & 0xffff; + v = v >>> 16; + a[1] = (v += a[1]) & 0xffff; + v = v >>> 16; + a[2] = (v += a[2]) & 0xffff; + v = v >>> 16; + a[3] = (v += a[3]) & 0xffff; + v = v >>> 16; + a[4] = (v += a[4]) & 0xffff; + v = v >>> 16; + a[5] = (v += a[5]) & 0xffff; + v = v >>> 16; + a[6] = (v += a[6]) & 0xffff; + v = v >>> 16; + a[7] = (v += a[7]) & 0xffff; + v = v >>> 16; + a[8] = (v += a[8]) & 0xffff; + v = v >>> 16; + a[9] = (v += a[9]) & 0xffff; + v = v >>> 16; + a[10] = (v += a[10]) & 0xffff; + v = v >>> 16; + a[11] = (v += a[11]) & 0xffff; + v = v >>> 16; + a[12] = (v += a[12]) & 0xffff; + v = v >>> 16; + a[13] = (v += a[13]) & 0xffff; + v = v >>> 16; + a[14] = (v += a[14]) & 0xffff; + v = v >>> 16; + a[15] += v; + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + function _addmodp(a, b) { + var r = []; + var v; + r[0] = (v = ((0 | (a[15] >>> 15)) + (0 | (b[15] >>> 15))) * 19 + + a[0] + b[0]) & 0xffff; + r[1] = (v = (v >>> 16) + a[1] + b[1]) & 0xffff; + r[2] = (v = (v >>> 16) + a[2] + b[2]) & 0xffff; + r[3] = (v = (v >>> 16) + a[3] + b[3]) & 0xffff; + r[4] = (v = (v >>> 16) + a[4] + b[4]) & 0xffff; + r[5] = (v = (v >>> 16) + a[5] + b[5]) & 0xffff; + r[6] = (v = (v >>> 16) + a[6] + b[6]) & 0xffff; + r[7] = (v = (v >>> 16) + a[7] + b[7]) & 0xffff; + r[8] = (v = (v >>> 16) + a[8] + b[8]) & 0xffff; + r[9] = (v = (v >>> 16) + a[9] + b[9]) & 0xffff; + r[10] = (v = (v >>> 16) + a[10] + b[10]) & 0xffff; + r[11] = (v = (v >>> 16) + a[11] + b[11]) & 0xffff; + r[12] = (v = (v >>> 16) + a[12] + b[12]) & 0xffff; + r[13] = (v = (v >>> 16) + a[13] + b[13]) & 0xffff; + r[14] = (v = (v >>> 16) + a[14] + b[14]) & 0xffff; + r[15] = (v >>> 16) + (a[15] & 0x7fff) + (b[15] & 0x7fff); + return r; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + function _submodp(a, b) { + var r = []; + var v; + r[0] = (v = 0x80000 + + ((0 | (a[15] >>> 15)) - (0 | (b[15] >>> 15)) - 1) + * 19 + a[0] - b[0]) & 0xffff; + r[1] = (v = (v >>> 16) + 0x7fff8 + a[1] - b[1]) & 0xffff; + r[2] = (v = (v >>> 16) + 0x7fff8 + a[2] - b[2]) & 0xffff; + r[3] = (v = (v >>> 16) + 0x7fff8 + a[3] - b[3]) & 0xffff; + r[4] = (v = (v >>> 16) + 0x7fff8 + a[4] - b[4]) & 0xffff; + r[5] = (v = (v >>> 16) + 0x7fff8 + a[5] - b[5]) & 0xffff; + r[6] = (v = (v >>> 16) + 0x7fff8 + a[6] - b[6]) & 0xffff; + r[7] = (v = (v >>> 16) + 0x7fff8 + a[7] - b[7]) & 0xffff; + r[8] = (v = (v >>> 16) + 0x7fff8 + a[8] - b[8]) & 0xffff; + r[9] = (v = (v >>> 16) + 0x7fff8 + a[9] - b[9]) & 0xffff; + r[10] = (v = (v >>> 16) + 0x7fff8 + a[10] - b[10]) & 0xffff; + r[11] = (v = (v >>> 16) + 0x7fff8 + a[11] - b[11]) & 0xffff; + r[12] = (v = (v >>> 16) + 0x7fff8 + a[12] - b[12]) & 0xffff; + r[13] = (v = (v >>> 16) + 0x7fff8 + a[13] - b[13]) & 0xffff; + r[14] = (v = (v >>> 16) + 0x7fff8 + a[14] - b[14]) & 0xffff; + r[15] = (v >>> 16) + 0x7ff8 + (a[15] & 0x7fff) + - (b[15] & 0x7fff); + return r; + } - hh[1] = ah1 = (c & 0xffff) | (d << 16); - hl[1] = al1 = (a & 0xffff) | (b << 16); + function _invmodp(a) { + var c = a; + var i = 250; + while (--i) { + a = _sqrmodp(a); + a = _mulmodp(a, c); + } + a = _sqrmodp(a); + a = _sqrmodp(a); + a = _mulmodp(a, c); + a = _sqrmodp(a); + a = _sqrmodp(a); + a = _mulmodp(a, c); + a = _sqrmodp(a); + a = _mulmodp(a, c); + return a; + } - h = ah2; - l = al2; + function _mulasmall(a) { + // 'division by 0x10000' can not be replaced by '>> 16' because + // more than 32 bits of precision are needed + var m = 121665; + var r = []; + var v; + r[0] = (v = a[0] * m) & 0xffff; + r[1] = (v = (0 | (v / 0x10000)) + a[1] * m) & 0xffff; + r[2] = (v = (0 | (v / 0x10000)) + a[2] * m) & 0xffff; + r[3] = (v = (0 | (v / 0x10000)) + a[3] * m) & 0xffff; + r[4] = (v = (0 | (v / 0x10000)) + a[4] * m) & 0xffff; + r[5] = (v = (0 | (v / 0x10000)) + a[5] * m) & 0xffff; + r[6] = (v = (0 | (v / 0x10000)) + a[6] * m) & 0xffff; + r[7] = (v = (0 | (v / 0x10000)) + a[7] * m) & 0xffff; + r[8] = (v = (0 | (v / 0x10000)) + a[8] * m) & 0xffff; + r[9] = (v = (0 | (v / 0x10000)) + a[9] * m) & 0xffff; + r[10] = (v = (0 | (v / 0x10000)) + a[10] * m) & 0xffff; + r[11] = (v = (0 | (v / 0x10000)) + a[11] * m) & 0xffff; + r[12] = (v = (0 | (v / 0x10000)) + a[12] * m) & 0xffff; + r[13] = (v = (0 | (v / 0x10000)) + a[13] * m) & 0xffff; + r[14] = (v = (0 | (v / 0x10000)) + a[14] * m) & 0xffff; + r[15] = (0 | (v / 0x10000)) + a[15] * m; + _reduce(r); + return r; + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + function _dbl(x, z) { + var x_2, z_2, m, n, o; + m = _sqrmodp(_addmodp(x, z)); + n = _sqrmodp(_submodp(x, z)); + o = _submodp(m, n); + x_2 = _mulmodp(n, m); + z_2 = _mulmodp(_addmodp(_mulasmall(o), m), o); + return [x_2, z_2]; + } - h = hh[2]; - l = hl[2]; + function _sum(x, z, x_p, z_p, x_1) { + var x_3, z_3, p, q; + p = _mulmodp(_submodp(x, z), _addmodp(x_p, z_p)); + q = _mulmodp(_addmodp(x, z), _submodp(x_p, z_p)); + x_3 = _sqrmodp(_addmodp(p, q)); + z_3 = _mulmodp(_sqrmodp(_submodp(p, q)), x_1); + return [x_3, z_3]; + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + function _generateKey(curve25519) { + var buffer = crypto.randomBytes(32); - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + // For Curve25519 DH keys, we need to apply some bit mask on generated + // keys: + // * clear bit 0, 1, 2 of first byte + // * clear bit 7 of last byte + // * set bit 6 of last byte + if (curve25519 === true) { + buffer[0] &= 0xf8; + buffer[31] = (buffer[31] & 0x7f) | 0x40; + } + var result = []; + for (var i = 0; i < buffer.length; i++) { + result.push(String.fromCharCode(buffer[i])); + } + return result.join(''); + } - hh[2] = ah2 = (c & 0xffff) | (d << 16); - hl[2] = al2 = (a & 0xffff) | (b << 16); + // Expose some functions to the outside through this name space. + // Note: This is not part of the public API. + ns.getbit = _getbit; + ns.setbit = _setbit; + ns.addmodp = _addmodp; + ns.invmodp = _invmodp; + ns.mulmodp = _mulmodp; + ns.reduce = _reduce; + ns.dbl = _dbl; + ns.sum = _sum; + ns.ZERO = _ZERO; + ns.ONE = _ONE; + ns.BASE = _BASE; + ns.bigintadd = _bigintadd; + ns.bigintsub = _bigintsub; + ns.bigintcmp = _bigintcmp; + ns.mulmodp = _mulmodp; + ns.sqrmodp = _sqrmodp; + ns.generateKey = _generateKey; - h = ah3; - l = al3; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +module.exports = ns; - h = hh[3]; - l = hl[3]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; +/***/ }), +/* 140 */ +/***/ (function(module, exports, __webpack_require__) { - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; +"use strict"; - hh[3] = ah3 = (c & 0xffff) | (d << 16); - hl[3] = al3 = (a & 0xffff) | (b << 16); +/** + * @fileOverview + * A collection of general utility functions.. + */ - h = ah4; - l = al4; +/* + * Copyright (c) 2011, 2012, 2014 Ron Garret + * Copyright (c) 2007, 2013, 2014 Michele Bini + * Copyright (c) 2014 Mega Limited + * under the MIT License. + * + * Authors: Guy K. Kloss, Michele Bini, Ron Garret + * + * You should have received a copy of the license along with this program. + */ - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; +var core = __webpack_require__(139); - h = hh[4]; - l = hl[4]; + /** + * @exports jodid25519/utils + * A collection of general utility functions.. + * + * @description + * A collection of general utility functions.. + */ + var ns = {}; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + var _HEXCHARS = "0123456789abcdef"; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + function _hexencode(vector) { + var result = []; + for (var i = vector.length - 1; i >= 0; i--) { + var value = vector[i]; + result.push(_HEXCHARS.substr((value >>> 12) & 0x0f, 1)); + result.push(_HEXCHARS.substr((value >>> 8) & 0x0f, 1)); + result.push(_HEXCHARS.substr((value >>> 4) & 0x0f, 1)); + result.push(_HEXCHARS.substr(value & 0x0f, 1)); + } + return result.join(''); + } - hh[4] = ah4 = (c & 0xffff) | (d << 16); - hl[4] = al4 = (a & 0xffff) | (b << 16); + function _hexdecode(vector) { + var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + for (var i = vector.length - 1, l = 0; i >= 0; i -= 4) { + result[l] = (_HEXCHARS.indexOf(vector.charAt(i))) + | (_HEXCHARS.indexOf(vector.charAt(i - 1)) << 4) + | (_HEXCHARS.indexOf(vector.charAt(i - 2)) << 8) + | (_HEXCHARS.indexOf(vector.charAt(i - 3)) << 12); + l++; + } + return result; + } - h = ah5; - l = al5; + var _BASE32CHARS = "abcdefghijklmnopqrstuvwxyz234567"; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + var _BASE32VALUES = (function () { + var result = {}; + for (var i = 0; i < _BASE32CHARS.length; i++) { + result[_BASE32CHARS.charAt(i)] = i; + } + return result; + })(); - h = hh[5]; - l = hl[5]; + function _base32encode(n) { + var c; + var r = ""; + for (c = 0; c < 255; c += 5) { + r = _BASE32CHARS.substr(core.getbit(n, c) + + (core.getbit(n, c + 1) << 1) + + (core.getbit(n, c + 2) << 2) + + (core.getbit(n, c + 3) << 3) + + (core.getbit(n, c + 4) << 4), 1) + + r; + } + return r; + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + function _base32decode(n) { + var c = 0; + var r = core.ZERO(); + var l = n.length; + for (c = 0; (l > 0) && (c < 255); c += 5) { + l--; + var v = _BASE32VALUES[n.substr(l, 1)]; + core.setbit(r, c, v & 1); + v >>= 1; + core.setbit(r, c + 1, v & 1); + v >>= 1; + core.setbit(r, c + 2, v & 1); + v >>= 1; + core.setbit(r, c + 3, v & 1); + v >>= 1; + core.setbit(r, c + 4, v & 1); + } + return r; + } - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + function _map(f, l) { + var result = new Array(l.length); + for (var i = 0; i < l.length; i++) { + result[i] = f(l[i]); + } + return result; + } - hh[5] = ah5 = (c & 0xffff) | (d << 16); - hl[5] = al5 = (a & 0xffff) | (b << 16); + function _chr(n) { + return String.fromCharCode(n); + } - h = ah6; - l = al6; + function _ord(c) { + return c.charCodeAt(0); + } - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + function _bytes2string(bytes) { + return _map(_chr, bytes).join(''); + } - h = hh[6]; - l = hl[6]; + function _string2bytes(s) { + return _map(_ord, s); + } - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; + // Expose some functions to the outside through this name space. - hh[6] = ah6 = (c & 0xffff) | (d << 16); - hl[6] = al6 = (a & 0xffff) | (b << 16); + /** + * Encodes an array of unsigned 8-bit integers to a hex string. + * + * @function + * @param vector {array} + * Array containing the byte values. + * @returns {string} + * String containing vector in a hexadecimal representation. + */ + ns.hexEncode = _hexencode; - h = ah7; - l = al7; - a = l & 0xffff; b = l >>> 16; - c = h & 0xffff; d = h >>> 16; + /** + * Decodes a hex string to an array of unsigned 8-bit integers. + * + * @function + * @param vector {string} + * String containing vector in a hexadecimal representation. + * @returns {array} + * Array containing the byte values. + */ + ns.hexDecode = _hexdecode; - h = hh[7]; - l = hl[7]; - a += l & 0xffff; b += l >>> 16; - c += h & 0xffff; d += h >>> 16; + /** + * Encodes an array of unsigned 8-bit integers using base32 encoding. + * + * @function + * @param vector {array} + * Array containing the byte values. + * @returns {string} + * String containing vector in a hexadecimal representation. + */ + ns.base32encode = _base32encode; - b += a >>> 16; - c += b >>> 16; - d += c >>> 16; - hh[7] = ah7 = (c & 0xffff) | (d << 16); - hl[7] = al7 = (a & 0xffff) | (b << 16); + /** + * Decodes a base32 encoded string to an array of unsigned 8-bit integers. + * + * @function + * @param vector {string} + * String containing vector in a hexadecimal representation. + * @returns {array} + * Array containing the byte values. + */ + ns.base32decode = _base32decode; - pos += 128; - n -= 128; - } - return n; -} + /** + * Converts an unsigned 8-bit integer array representation to a byte string. + * + * @function + * @param vector {array} + * Array containing the byte values. + * @returns {string} + * Byte string representation of vector. + */ + ns.bytes2string = _bytes2string; -function crypto_hash(out, m, n) { - var hh = new Int32Array(8), - hl = new Int32Array(8), - x = new Uint8Array(256), - i, b = n; - hh[0] = 0x6a09e667; - hh[1] = 0xbb67ae85; - hh[2] = 0x3c6ef372; - hh[3] = 0xa54ff53a; - hh[4] = 0x510e527f; - hh[5] = 0x9b05688c; - hh[6] = 0x1f83d9ab; - hh[7] = 0x5be0cd19; + /** + * Converts a byte string representation to an array of unsigned + * 8-bit integers. + * + * @function + * @param vector {array} + * Array containing the byte values. + * @returns {string} + * Byte string representation of vector. + */ + ns.string2bytes = _string2bytes; - hl[0] = 0xf3bcc908; - hl[1] = 0x84caa73b; - hl[2] = 0xfe94f82b; - hl[3] = 0x5f1d36f1; - hl[4] = 0xade682d1; - hl[5] = 0x2b3e6c1f; - hl[6] = 0xfb41bd6b; - hl[7] = 0x137e2179; +module.exports = ns; - crypto_hashblocks_hl(hh, hl, m, n); - n %= 128; - for (i = 0; i < n; i++) x[i] = m[b-n+i]; - x[n] = 128; +/***/ }), +/* 141 */ +/***/ (function(module, exports, __webpack_require__) { - n = 256-128*(n<112?1:0); - x[n-9] = 0; - ts64(x, n-8, (b / 0x20000000) | 0, b << 3); - crypto_hashblocks_hl(hh, hl, x, n); +"use strict"; - for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); - return 0; -} +var isPromise = __webpack_require__(556); -function add(p, q) { - var a = gf(), b = gf(), c = gf(), - d = gf(), e = gf(), f = gf(), - g = gf(), h = gf(), t = gf(); +/** + * Return a function that will run a function asynchronously or synchronously + * + * example: + * runAsync(wrappedFunction, callback)(...args); + * + * @param {Function} func Function to run + * @param {Function} cb Callback function passed the `func` returned value + * @return {Function(arguments)} Arguments to pass to `func`. This function will in turn + * return a Promise (Node >= 0.12) or call the callbacks. + */ - Z(a, p[1], p[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b, p[0], p[1]); - A(t, q[0], q[1]); - M(b, b, t); - M(c, p[3], q[3]); - M(c, c, D2); - M(d, p[2], q[2]); - A(d, d, d); - Z(e, b, a); - Z(f, d, c); - A(g, d, c); - A(h, b, a); +var runAsync = module.exports = function (func, cb) { + cb = cb || function () {}; - M(p[0], e, f); - M(p[1], h, g); - M(p[2], g, f); - M(p[3], e, h); -} + return function () { + var async = false; + var args = arguments; -function cswap(p, q, b) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p[i], q[i], b); - } -} + var promise = new Promise(function (resolve, reject) { + var answer = func.apply({ + async: function () { + async = true; + return function (err, value) { + if (err) { + reject(err); + } else { + resolve(value); + } + }; + } + }, Array.prototype.slice.call(args)); -function pack(r, p) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p[2]); - M(tx, p[0], zi); - M(ty, p[1], zi); - pack25519(r, ty); - r[31] ^= par25519(tx) << 7; -} + if (!async) { + if (isPromise(answer)) { + answer.then(resolve, reject); + } else { + resolve(answer); + } + } + }); -function scalarmult(p, q, s) { - var b, i; - set25519(p[0], gf0); - set25519(p[1], gf1); - set25519(p[2], gf1); - set25519(p[3], gf0); - for (i = 255; i >= 0; --i) { - b = (s[(i/8)|0] >> (i&7)) & 1; - cswap(p, q, b); - add(q, p); - add(p, p); - cswap(p, q, b); + promise.then(cb.bind(null, null), cb); + + return promise; } -} +}; -function scalarbase(p, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p, q, s); -} +runAsync.cb = function (func, cb) { + return runAsync(function () { + var args = Array.prototype.slice.call(arguments); + if (args.length === func.length - 1) { + args.push(this.async()); + } + return func.apply(this, args); + }, cb); +}; -function crypto_sign_keypair(pk, sk, seeded) { - var d = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()]; - var i; - if (!seeded) randombytes(sk, 32); - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; +/***/ }), +/* 142 */ +/***/ (function(module, exports, __webpack_require__) { - scalarbase(p, d); - pack(pk, p); +var Rx = __webpack_require__(40); +__webpack_require__(617); +__webpack_require__(618); +__webpack_require__(619); +__webpack_require__(312); +__webpack_require__(620); +__webpack_require__(621); +__webpack_require__(622); +__webpack_require__(623); +__webpack_require__(313); +__webpack_require__(624); +__webpack_require__(625); - for (i = 0; i < 32; i++) sk[i+32] = pk[i]; - return 0; -} +module.exports = Rx; -var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); -function modL(r, x) { - var carry, i, j, k; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k = i - 12; j < k; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = (x[j] + 128) >> 8; - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i+1] += x[i] >> 8; - r[i] = x[i] & 255; - } -} +/***/ }), +/* 143 */ +/***/ (function(module, exports, __webpack_require__) { -function reduce(r) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r[i]; - for (i = 0; i < 64; i++) r[i] = 0; - modL(r, x); -} +// Copyright 2015 Joyent, Inc. -// Note: difference from C - smlen returned, not passed as argument. -function crypto_sign(sm, m, n, sk) { - var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p = [gf(), gf(), gf(), gf()]; +module.exports = { + read: read, + readSSHPrivate: readSSHPrivate, + write: write +}; - crypto_hash(d, sk, 32); - d[0] &= 248; - d[31] &= 127; - d[31] |= 64; +var assert = __webpack_require__(11); +var asn1 = __webpack_require__(50); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); +var crypto = __webpack_require__(8); - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var pem = __webpack_require__(58); +var rfc4253 = __webpack_require__(75); +var SSHBuffer = __webpack_require__(144); +var errors = __webpack_require__(44); - crypto_hash(r, sm.subarray(32), n+32); - reduce(r); - scalarbase(p, r); - pack(sm, p); +var bcrypt; - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h, sm, n + 64); - reduce(h); +function read(buf, options) { + return (pem.read(buf, options)); +} - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i+j] += h[i] * d[j]; - } - } +var MAGIC = 'openssh-key-v1'; - modL(sm.subarray(32), x); - return smlen; -} +function readSSHPrivate(type, buf, options) { + buf = new SSHBuffer({buffer: buf}); -function unpackneg(r, p) { - var t = gf(), chk = gf(), num = gf(), - den = gf(), den2 = gf(), den4 = gf(), - den6 = gf(); + var magic = buf.readCString(); + assert.strictEqual(magic, MAGIC, 'bad magic string'); - set25519(r[2], gf1); - unpack25519(r[1], p); - S(num, r[1]); - M(den, num, D); - Z(num, num, r[2]); - A(den, r[2], den); + var cipher = buf.readString(); + var kdf = buf.readString(); + var kdfOpts = buf.readBuffer(); - S(den2, den); - S(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); + var nkeys = buf.readInt(); + if (nkeys !== 1) { + throw (new Error('OpenSSH-format key file contains ' + + 'multiple keys: this is unsupported.')); + } - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r[0], t, den); + var pubKey = buf.readBuffer(); - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r[0], r[0], I); + if (type === 'public') { + assert.ok(buf.atEnd(), 'excess bytes left after key'); + return (rfc4253.read(pubKey)); + } - S(chk, r[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; + var privKeyBlob = buf.readBuffer(); + assert.ok(buf.atEnd(), 'excess bytes left after key'); - if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); + var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts }); + switch (kdf) { + case 'none': + if (cipher !== 'none') { + throw (new Error('OpenSSH-format key uses KDF "none" ' + + 'but specifies a cipher other than "none"')); + } + break; + case 'bcrypt': + var salt = kdfOptsBuf.readBuffer(); + var rounds = kdfOptsBuf.readInt(); + var cinf = utils.opensshCipherInfo(cipher); + if (bcrypt === undefined) { + bcrypt = __webpack_require__(278); + } - M(r[3], r[0], r[1]); - return 0; -} + if (typeof (options.passphrase) === 'string') { + options.passphrase = new Buffer(options.passphrase, + 'utf-8'); + } + if (!Buffer.isBuffer(options.passphrase)) { + throw (new errors.KeyEncryptedError( + options.filename, 'OpenSSH')); + } -function crypto_sign_open(m, sm, n, pk) { - var i, mlen; - var t = new Uint8Array(32), h = new Uint8Array(64); - var p = [gf(), gf(), gf(), gf()], - q = [gf(), gf(), gf(), gf()]; + var pass = new Uint8Array(options.passphrase); + var salti = new Uint8Array(salt); + /* Use the pbkdf to derive both the key and the IV. */ + var out = new Uint8Array(cinf.keySize + cinf.blockSize); + var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, + out, out.length, rounds); + if (res !== 0) { + throw (new Error('bcrypt_pbkdf function returned ' + + 'failure, parameters invalid')); + } + out = new Buffer(out); + var ckey = out.slice(0, cinf.keySize); + var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); + var cipherStream = crypto.createDecipheriv(cinf.opensslName, + ckey, iv); + cipherStream.setAutoPadding(false); + var chunk, chunks = []; + cipherStream.once('error', function (e) { + if (e.toString().indexOf('bad decrypt') !== -1) { + throw (new Error('Incorrect passphrase ' + + 'supplied, could not decrypt key')); + } + throw (e); + }); + cipherStream.write(privKeyBlob); + cipherStream.end(); + while ((chunk = cipherStream.read()) !== null) + chunks.push(chunk); + privKeyBlob = Buffer.concat(chunks); + break; + default: + throw (new Error( + 'OpenSSH-format key uses unknown KDF "' + kdf + '"')); + } - mlen = -1; - if (n < 64) return -1; + buf = new SSHBuffer({buffer: privKeyBlob}); - if (unpackneg(q, pk)) return -1; + var checkInt1 = buf.readInt(); + var checkInt2 = buf.readInt(); + if (checkInt1 !== checkInt2) { + throw (new Error('Incorrect passphrase supplied, could not ' + + 'decrypt key')); + } - for (i = 0; i < n; i++) m[i] = sm[i]; - for (i = 0; i < 32; i++) m[i+32] = pk[i]; - crypto_hash(h, m, n); - reduce(h); - scalarmult(p, q, h); + var ret = {}; + var key = rfc4253.readInternal(ret, 'private', buf.remainder()); - scalarbase(q, sm.subarray(32)); - add(p, q); - pack(t, p); + buf.skip(ret.consumed); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m[i] = 0; - return -1; - } + var comment = buf.readString(); + key.comment = comment; - for (i = 0; i < n; i++) m[i] = sm[i + 64]; - mlen = n; - return mlen; + return (key); } -var crypto_secretbox_KEYBYTES = 32, - crypto_secretbox_NONCEBYTES = 24, - crypto_secretbox_ZEROBYTES = 32, - crypto_secretbox_BOXZEROBYTES = 16, - crypto_scalarmult_BYTES = 32, - crypto_scalarmult_SCALARBYTES = 32, - crypto_box_PUBLICKEYBYTES = 32, - crypto_box_SECRETKEYBYTES = 32, - crypto_box_BEFORENMBYTES = 32, - crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, - crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, - crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, - crypto_sign_BYTES = 64, - crypto_sign_PUBLICKEYBYTES = 32, - crypto_sign_SECRETKEYBYTES = 64, - crypto_sign_SEEDBYTES = 32, - crypto_hash_BYTES = 64; +function write(key, options) { + var pubKey; + if (PrivateKey.isPrivateKey(key)) + pubKey = key.toPublic(); + else + pubKey = key; -nacl.lowlevel = { - crypto_core_hsalsa20: crypto_core_hsalsa20, - crypto_stream_xor: crypto_stream_xor, - crypto_stream: crypto_stream, - crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, - crypto_stream_salsa20: crypto_stream_salsa20, - crypto_onetimeauth: crypto_onetimeauth, - crypto_onetimeauth_verify: crypto_onetimeauth_verify, - crypto_verify_16: crypto_verify_16, - crypto_verify_32: crypto_verify_32, - crypto_secretbox: crypto_secretbox, - crypto_secretbox_open: crypto_secretbox_open, - crypto_scalarmult: crypto_scalarmult, - crypto_scalarmult_base: crypto_scalarmult_base, - crypto_box_beforenm: crypto_box_beforenm, - crypto_box_afternm: crypto_box_afternm, - crypto_box: crypto_box, - crypto_box_open: crypto_box_open, - crypto_box_keypair: crypto_box_keypair, - crypto_hash: crypto_hash, - crypto_sign: crypto_sign, - crypto_sign_keypair: crypto_sign_keypair, - crypto_sign_open: crypto_sign_open, + var cipher = 'none'; + var kdf = 'none'; + var kdfopts = new Buffer(0); + var cinf = { blockSize: 8 }; + var passphrase; + if (options !== undefined) { + passphrase = options.passphrase; + if (typeof (passphrase) === 'string') + passphrase = new Buffer(passphrase, 'utf-8'); + if (passphrase !== undefined) { + assert.buffer(passphrase, 'options.passphrase'); + assert.optionalString(options.cipher, 'options.cipher'); + cipher = options.cipher; + if (cipher === undefined) + cipher = 'aes128-ctr'; + cinf = utils.opensshCipherInfo(cipher); + kdf = 'bcrypt'; + } + } - crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, - crypto_sign_BYTES: crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, - crypto_hash_BYTES: crypto_hash_BYTES -}; + var privBuf; + if (PrivateKey.isPrivateKey(key)) { + privBuf = new SSHBuffer({}); + var checkInt = crypto.randomBytes(4).readUInt32BE(0); + privBuf.writeInt(checkInt); + privBuf.writeInt(checkInt); + privBuf.write(key.toBuffer('rfc4253')); + privBuf.writeString(key.comment || ''); -/* High-level API */ + var n = 1; + while (privBuf._offset % cinf.blockSize !== 0) + privBuf.writeChar(n++); + privBuf = privBuf.toBuffer(); + } -function checkLengths(k, n) { - if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); -} + switch (kdf) { + case 'none': + break; + case 'bcrypt': + var salt = crypto.randomBytes(16); + var rounds = 16; + var kdfssh = new SSHBuffer({}); + kdfssh.writeBuffer(salt); + kdfssh.writeInt(rounds); + kdfopts = kdfssh.toBuffer(); -function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); -} + if (bcrypt === undefined) { + bcrypt = __webpack_require__(278); + } + var pass = new Uint8Array(passphrase); + var salti = new Uint8Array(salt); + /* Use the pbkdf to derive both the key and the IV. */ + var out = new Uint8Array(cinf.keySize + cinf.blockSize); + var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length, + out, out.length, rounds); + if (res !== 0) { + throw (new Error('bcrypt_pbkdf function returned ' + + 'failure, parameters invalid')); + } + out = new Buffer(out); + var ckey = out.slice(0, cinf.keySize); + var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize); -function checkArrayTypes() { - var t, i; - for (i = 0; i < arguments.length; i++) { - if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') - throw new TypeError('unexpected type ' + t + ', use Uint8Array'); - } -} + var cipherStream = crypto.createCipheriv(cinf.opensslName, + ckey, iv); + cipherStream.setAutoPadding(false); + var chunk, chunks = []; + cipherStream.once('error', function (e) { + throw (e); + }); + cipherStream.write(privBuf); + cipherStream.end(); + while ((chunk = cipherStream.read()) !== null) + chunks.push(chunk); + privBuf = Buffer.concat(chunks); + break; + default: + throw (new Error('Unsupported kdf ' + kdf)); + } -function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; -} + var buf = new SSHBuffer({}); -// TODO: Completely remove this in v0.15. -if (!nacl.util) { - nacl.util = {}; - nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { - throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); - }; -} + buf.writeCString(MAGIC); + buf.writeString(cipher); /* cipher */ + buf.writeString(kdf); /* kdf */ + buf.writeBuffer(kdfopts); /* kdfoptions */ -nacl.randomBytes = function(n) { - var b = new Uint8Array(n); - randombytes(b, n); - return b; -}; + buf.writeInt(1); /* nkeys */ + buf.writeBuffer(pubKey.toBuffer('rfc4253')); -nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c = new Uint8Array(m.length); - for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c, m, m.length, nonce, key); - return c.subarray(crypto_secretbox_BOXZEROBYTES); -}; + if (privBuf) + buf.writeBuffer(privBuf); -nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m = new Uint8Array(c.length); - for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c.length < 32) return false; - if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; - return m.subarray(crypto_secretbox_ZEROBYTES); -}; + buf = buf.toBuffer(); -nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; -nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; -nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; + var header; + if (PrivateKey.isPrivateKey(key)) + header = 'OPENSSH PRIVATE KEY'; + else + header = 'OPENSSH PUBLIC KEY'; -nacl.scalarMult = function(n, p) { - checkArrayTypes(n, p); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p); - return q; -}; + var tmp = buf.toString('base64'); + var len = tmp.length + (tmp.length / 70) + + 18 + 16 + header.length*2 + 10; + buf = new Buffer(len); + var o = 0; + o += buf.write('-----BEGIN ' + header + '-----\n', o); + for (var i = 0; i < tmp.length; ) { + var limit = i + 70; + if (limit > tmp.length) + limit = tmp.length; + o += buf.write(tmp.slice(i, limit), o); + buf[o++] = 10; + i = limit; + } + o += buf.write('-----END ' + header + '-----\n', o); -nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; -}; + return (buf.slice(0, o)); +} -nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; -nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; -nacl.box = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k); +/***/ }), +/* 144 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2015 Joyent, Inc. + +module.exports = SSHBuffer; + +var assert = __webpack_require__(11); + +function SSHBuffer(opts) { + assert.object(opts, 'options'); + if (opts.buffer !== undefined) + assert.buffer(opts.buffer, 'options.buffer'); + + this._size = opts.buffer ? opts.buffer.length : 1024; + this._buffer = opts.buffer || (new Buffer(this._size)); + this._offset = 0; +} + +SSHBuffer.prototype.toBuffer = function () { + return (this._buffer.slice(0, this._offset)); }; -nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k, publicKey, secretKey); - return k; +SSHBuffer.prototype.atEnd = function () { + return (this._offset >= this._buffer.length); }; -nacl.box.after = nacl.secretbox; +SSHBuffer.prototype.remainder = function () { + return (this._buffer.slice(this._offset)); +}; -nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k); +SSHBuffer.prototype.skip = function (n) { + this._offset += n; }; -nacl.box.open.after = nacl.secretbox.open; +SSHBuffer.prototype.expand = function () { + this._size *= 2; + var buf = new Buffer(this._size); + this._buffer.copy(buf, 0); + this._buffer = buf; +}; -nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; +SSHBuffer.prototype.readPart = function () { + return ({data: this.readBuffer()}); }; -nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +SSHBuffer.prototype.readBuffer = function () { + var len = this._buffer.readUInt32BE(this._offset); + this._offset += 4; + assert.ok(this._offset + len <= this._buffer.length, + 'length out of bounds at +0x' + this._offset.toString(16) + + ' (data truncated?)'); + var buf = this._buffer.slice(this._offset, this._offset + len); + this._offset += len; + return (buf); }; -nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; -nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; -nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; -nacl.box.nonceLength = crypto_box_NONCEBYTES; -nacl.box.overheadLength = nacl.secretbox.overheadLength; +SSHBuffer.prototype.readString = function () { + return (this.readBuffer().toString()); +}; -nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; +SSHBuffer.prototype.readCString = function () { + var offset = this._offset; + while (offset < this._buffer.length && + this._buffer[offset] !== 0x00) + offset++; + assert.ok(offset < this._buffer.length, 'c string does not terminate'); + var str = this._buffer.slice(this._offset, offset).toString(); + this._offset = offset + 1; + return (str); }; -nacl.sign.open = function(signedMsg, publicKey) { - if (arguments.length !== 2) - throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m = new Uint8Array(mlen); - for (var i = 0; i < m.length; i++) m[i] = tmp[i]; - return m; +SSHBuffer.prototype.readInt = function () { + var v = this._buffer.readUInt32BE(this._offset); + this._offset += 4; + return (v); }; -nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; +SSHBuffer.prototype.readInt64 = function () { + assert.ok(this._offset + 8 < this._buffer.length, + 'buffer not long enough to read Int64'); + var v = this._buffer.slice(this._offset, this._offset + 8); + this._offset += 8; + return (v); }; -nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error('bad signature size'); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error('bad public key size'); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; - return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +SSHBuffer.prototype.readChar = function () { + var v = this._buffer[this._offset++]; + return (v); }; -nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return {publicKey: pk, secretKey: sk}; +SSHBuffer.prototype.writeBuffer = function (buf) { + while (this._offset + 4 + buf.length > this._size) + this.expand(); + this._buffer.writeUInt32BE(buf.length, this._offset); + this._offset += 4; + buf.copy(this._buffer, this._offset); + this._offset += buf.length; }; -nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error('bad secret key size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; - return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +SSHBuffer.prototype.writeString = function (str) { + this.writeBuffer(new Buffer(str, 'utf8')); }; -nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error('bad seed size'); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return {publicKey: pk, secretKey: sk}; +SSHBuffer.prototype.writeCString = function (str) { + while (this._offset + 1 + str.length > this._size) + this.expand(); + this._buffer.write(str, this._offset); + this._offset += str.length; + this._buffer[this._offset++] = 0; }; -nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; -nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; -nacl.sign.seedLength = crypto_sign_SEEDBYTES; -nacl.sign.signatureLength = crypto_sign_BYTES; +SSHBuffer.prototype.writeInt = function (v) { + while (this._offset + 4 > this._size) + this.expand(); + this._buffer.writeUInt32BE(v, this._offset); + this._offset += 4; +}; -nacl.hash = function(msg) { - checkArrayTypes(msg); - var h = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h, msg, msg.length); - return h; +SSHBuffer.prototype.writeInt64 = function (v) { + assert.buffer(v, 'value'); + if (v.length > 8) { + var lead = v.slice(0, v.length - 8); + for (var i = 0; i < lead.length; ++i) { + assert.strictEqual(lead[i], 0, + 'must fit in 64 bits of precision'); + } + v = v.slice(v.length - 8, v.length); + } + while (this._offset + 8 > this._size) + this.expand(); + v.copy(this._buffer, this._offset); + this._offset += 8; }; -nacl.hash.hashLength = crypto_hash_BYTES; +SSHBuffer.prototype.writeChar = function (v) { + while (this._offset + 1 > this._size) + this.expand(); + this._buffer[this._offset++] = v; +}; -nacl.verify = function(x, y) { - checkArrayTypes(x, y); - // Zero length arguments are considered not equal. - if (x.length === 0 || y.length === 0) return false; - if (x.length !== y.length) return false; - return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +SSHBuffer.prototype.writePart = function (p) { + this.writeBuffer(p.data); }; -nacl.setPRNG = function(fn) { - randombytes = fn; +SSHBuffer.prototype.write = function (buf) { + while (this._offset + buf.length > this._size) + this.expand(); + buf.copy(this._buffer, this._offset); + this._offset += buf.length; }; -(function() { - // Initialize PRNG if environment provides CSPRNG. - // If not, methods calling randombytes will throw. - var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; - if (crypto && crypto.getRandomValues) { - // Browsers. - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } else if (true) { - // Node.js. - crypto = __webpack_require__(7); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v[i]; - cleanup(v); - }); - } - } -})(); -})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); +/***/ }), +/* 145 */ +/***/ (function(module, exports, __webpack_require__) { +var chownr = __webpack_require__(455) +var tar = __webpack_require__(322) +var pump = __webpack_require__(301) +var mkdirp = __webpack_require__(114) +var fs = __webpack_require__(5) +var path = __webpack_require__(0) +var os = __webpack_require__(47) -/***/ }), -/* 111 */ -/***/ (function(module, exports) { +var win32 = os.platform() === 'win32' -module.exports = require("child_process"); +var noop = function () {} -/***/ }), -/* 112 */ -/***/ (function(module, exports) { +var echo = function (name) { + return name +} -module.exports = require("https"); +var normalize = !win32 ? echo : function (name) { + return name.replace(/\\/g, '/').replace(/:/g, '_') +} -/***/ }), -/* 113 */ -/***/ (function(module, exports) { +var statAll = function (fs, stat, cwd, ignore, entries, sort) { + var queue = entries || ['.'] -module.exports = require("os"); + return function loop (callback) { + if (!queue.length) return callback() + var next = queue.shift() + var nextAbs = path.join(cwd, next) -/***/ }), -/* 114 */ -/***/ (function(module, exports) { + stat(nextAbs, function (err, stat) { + if (err) return callback(err) -module.exports = require("querystring"); + if (!stat.isDirectory()) return callback(null, next, stat) -/***/ }), -/* 115 */ -/***/ (function(module, exports) { + fs.readdir(nextAbs, function (err, files) { + if (err) return callback(err) -module.exports = require("readline"); + if (sort) files.sort() + for (var i = 0; i < files.length; i++) { + if (!ignore(path.join(cwd, next, files[i]))) queue.push(path.join(next, files[i])) + } -/***/ }), -/* 116 */ -/***/ (function(module, exports) { + callback(null, next, stat) + }) + }) + } +} -module.exports = require("tty"); +var strip = function (map, level) { + return function (header) { + header.name = header.name.split('/').slice(level).join('/') -/***/ }), -/* 117 */ -/***/ (function(module, exports) { + var linkname = header.linkname + if (linkname && (header.type === 'link' || path.isAbsolute(linkname))) { + header.linkname = linkname.split('/').slice(level).join('/') + } -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. + return map(header) + } +} +exports.pack = function (cwd, opts) { + if (!cwd) cwd = '.' + if (!opts) opts = {} -module.exports = { + var xfs = opts.fs || fs + var ignore = opts.ignore || opts.filter || noop + var map = opts.map || noop + var mapStream = opts.mapStream || echo + var statNext = statAll(xfs, opts.dereference ? xfs.stat : xfs.lstat, cwd, ignore, opts.entries, opts.sort) + var strict = opts.strict !== false + var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() + var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 + var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 + var pack = opts.pack || tar.pack() - newInvalidAsn1Error: function(msg) { - var e = new Error(); - e.name = 'InvalidAsn1Error'; - e.message = msg || ''; - return e; + if (opts.strip) map = strip(map, opts.strip) + + if (opts.readable) { + dmode |= parseInt(555, 8) + fmode |= parseInt(444, 8) + } + if (opts.writable) { + dmode |= parseInt(333, 8) + fmode |= parseInt(222, 8) } -}; + var onsymlink = function (filename, header) { + xfs.readlink(path.join(cwd, filename), function (err, linkname) { + if (err) return pack.destroy(err) + header.linkname = normalize(linkname) + pack.entry(header, onnextentry) + }) + } + var onstat = function (err, filename, stat) { + if (err) return pack.destroy(err) + if (!filename) return pack.finalize() -/***/ }), -/* 118 */ -/***/ (function(module, exports) { + if (stat.isSocket()) return onnextentry() // tar does not support sockets... -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. + var header = { + name: normalize(filename), + mode: (stat.mode | (stat.isDirectory() ? dmode : fmode)) & umask, + mtime: stat.mtime, + size: stat.size, + type: 'file', + uid: stat.uid, + gid: stat.gid + } + if (stat.isDirectory()) { + header.size = 0 + header.type = 'directory' + header = map(header) || header + return pack.entry(header, onnextentry) + } -module.exports = { - EOC: 0, - Boolean: 1, - Integer: 2, - BitString: 3, - OctetString: 4, - Null: 5, - OID: 6, - ObjectDescriptor: 7, - External: 8, - Real: 9, // float - Enumeration: 10, - PDV: 11, - Utf8String: 12, - RelativeOID: 13, - Sequence: 16, - Set: 17, - NumericString: 18, - PrintableString: 19, - T61String: 20, - VideotexString: 21, - IA5String: 22, - UTCTime: 23, - GeneralizedTime: 24, - GraphicString: 25, - VisibleString: 26, - GeneralString: 28, - UniversalString: 29, - CharacterString: 30, - BMPString: 31, - Constructor: 32, - Context: 128 -}; + if (stat.isSymbolicLink()) { + header.size = 0 + header.type = 'symlink' + header = map(header) || header + return onsymlink(filename, header) + } + // TODO: add fifo etc... -/***/ }), -/* 119 */ -/***/ (function(module, exports, __webpack_require__) { + header = map(header) || header -"use strict"; + if (!stat.isFile()) { + if (strict) return pack.destroy(new Error('unsupported type for ' + filename)) + return onnextentry() + } + var entry = pack.entry(header, onnextentry) + if (!entry) return -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.pack = exports.packTarball = undefined; + var rs = mapStream(xfs.createReadStream(path.join(cwd, filename)), header) -var _asyncToGenerator2; + rs.on('error', function (err) { // always forward errors on destroy + entry.destroy(err) + }) -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + pump(rs, entry) + } -let packTarball = exports.packTarball = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { - var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var onnextentry = function (err) { + if (err) return pack.destroy(err) + statNext(onstat) + } - let mapHeader = _ref2.mapHeader; + onnextentry() - const pkg = yield config.readRootManifest(); - const bundledDependencies = pkg.bundledDependencies, - main = pkg.main, - onlyFiles = pkg.files; + return pack +} - // include required files +var head = function (list) { + return list.length ? list[list.length - 1] : null +} - let filters = NEVER_IGNORE.slice(); - // include default filters unless `files` is used - if (!onlyFiles) { - filters = filters.concat(DEFAULT_IGNORE); - } - if (main) { - filters = filters.concat((0, (_filter || _load_filter()).ignoreLinesToRegex)(['!/' + main])); - } +var processGetuid = function () { + return process.getuid ? process.getuid() : -1 +} - // include bundledDependencies - if (bundledDependencies) { - const folder = config.getFolder(pkg); - filters = (0, (_filter || _load_filter()).ignoreLinesToRegex)(bundledDependencies.map(function (name) { - return `!${folder}/${name}`; - }), '.'); - } - - // `files` field - if (onlyFiles) { - let lines = ['*', // ignore all files except those that are explicitly included with a negation filter - '.*']; - lines = lines.concat(onlyFiles.map(function (filename) { - return `!${filename}`; - }), onlyFiles.map(function (filename) { - return `!${path.join(filename, '**')}`; - })); - const regexes = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines, '.'); - filters = filters.concat(regexes); - } +var processUmask = function () { + return process.umask ? process.umask() : 0 +} - const files = yield (_fs || _load_fs()).walk(config.cwd, null, new Set(FOLDERS_IGNORE)); - const dotIgnoreFiles = (0, (_filter || _load_filter()).filterOverridenGitignores)(files); +exports.extract = function (cwd, opts) { + if (!cwd) cwd = '.' + if (!opts) opts = {} - // create ignores - for (const file of dotIgnoreFiles) { - const raw = yield (_fs || _load_fs()).readFile(file.absolute); - const lines = raw.split('\n'); + var xfs = opts.fs || fs + var ignore = opts.ignore || opts.filter || noop + var map = opts.map || noop + var mapStream = opts.mapStream || echo + var own = opts.chown !== false && !win32 && processGetuid() === 0 + var extract = opts.extract || tar.extract() + var stack = [] + var now = new Date() + var umask = typeof opts.umask === 'number' ? ~opts.umask : ~processUmask() + var dmode = typeof opts.dmode === 'number' ? opts.dmode : 0 + var fmode = typeof opts.fmode === 'number' ? opts.fmode : 0 + var strict = opts.strict !== false - const regexes = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines, path.dirname(file.relative)); - filters = filters.concat(regexes); - } + if (opts.strip) map = strip(map, opts.strip) - // files to definitely keep, takes precedence over ignore filter - const keepFiles = new Set(); + if (opts.readable) { + dmode |= parseInt(555, 8) + fmode |= parseInt(444, 8) + } + if (opts.writable) { + dmode |= parseInt(333, 8) + fmode |= parseInt(222, 8) + } - // files to definitely ignore - const ignoredFiles = new Set(); + var utimesParent = function (name, cb) { // we just set the mtime on the parent dir again everytime we write an entry + var top + while ((top = head(stack)) && name.slice(0, top[0].length) !== top[0]) stack.pop() + if (!top) return cb() + xfs.utimes(top[0], now, top[1], cb) + } - // list of files that didn't match any of our patterns, if a directory in the chain above was matched - // then we should inherit it - const possibleKeepFiles = new Set(); + var utimes = function (name, header, cb) { + if (opts.utimes === false) return cb() - // apply filters - (0, (_filter || _load_filter()).sortFilter)(files, filters, keepFiles, possibleKeepFiles, ignoredFiles); + if (header.type === 'directory') return xfs.utimes(name, now, header.mtime, cb) + if (header.type === 'symlink') return utimesParent(name, cb) // TODO: how to set mtime on link? - const packer = tar.pack(config.cwd, { - ignore: function (name) { - const relative = path.relative(config.cwd, name); - // Don't ignore directories, since we need to recurse inside them to check for unignored files. - if (fs2.lstatSync(name).isDirectory()) { - const isParentOfKeptFile = Array.from(keepFiles).some(function (name) { - return !path.relative(relative, name).startsWith('..'); - }); - return !isParentOfKeptFile; - } - // Otherwise, ignore a file if we're not supposed to keep it. - return !keepFiles.has(relative); - }, - map: function (header) { - const suffix = header.name === '.' ? '' : `/${header.name}`; - header.name = `package${suffix}`; - delete header.uid; - delete header.gid; - return mapHeader ? mapHeader(header) : header; - } - }); + xfs.utimes(name, now, header.mtime, function (err) { + if (err) return cb(err) + utimesParent(name, cb) + }) + } - return packer; - }); + var chperm = function (name, header, cb) { + var link = header.type === 'symlink' + var chmod = link ? xfs.lchmod : xfs.chmod + var chown = link ? xfs.lchown : xfs.chown - return function packTarball(_x) { - return _ref.apply(this, arguments); - }; -})(); + if (!chmod) return cb() -let pack = exports.pack = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, dir) { - const packer = yield packTarball(config); - const compressor = packer.pipe(new zlib.Gzip()); + var mode = (header.mode | (header.type === 'directory' ? dmode : fmode)) & umask + chmod(name, mode, function (err) { + if (err) return cb(err) + if (!own) return cb() + if (!chown) return cb() + chown(name, header.uid, header.gid, cb) + }) + } - return compressor; - }); + extract.on('entry', function (header, stream, next) { + header = map(header) || header + header.name = normalize(header.name) + var name = path.join(cwd, path.join('/', header.name)) - return function pack(_x3, _x4) { - return _ref3.apply(this, arguments); - }; -})(); + if (ignore(name, header)) { + stream.resume() + return next() + } -let run = exports.run = (() => { - var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const pkg = yield config.readRootManifest(); - if (!pkg.name) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('noName')); + var stat = function (err) { + if (err) return next(err) + utimes(name, header, function (err) { + if (err) return next(err) + if (win32) return next() + chperm(name, header, next) + }) } - if (!pkg.version) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('noVersion')); + + var onsymlink = function () { + if (win32) return next() // skip symlinks on win for now before it can be tested + xfs.unlink(name, function () { + xfs.symlink(header.linkname, name, stat) + }) } - const normaliseScope = function (name) { - return name[0] === '@' ? name.substr(1).replace('/', '-') : name; - }; - const filename = flags.filename || path.join(config.cwd, `${normaliseScope(pkg.name)}-v${pkg.version}.tgz`); + var onlink = function () { + if (win32) return next() // skip links on win for now before it can be tested + xfs.unlink(name, function () { + var srcpath = path.resolve(cwd, header.linkname) - const stream = yield pack(config, config.cwd); + xfs.link(srcpath, name, function (err) { + if (err && err.code === 'EPERM' && opts.hardlinkAsFilesFallback) { + stream = xfs.createReadStream(srcpath) + return onfile() + } - yield new Promise(function (resolve, reject) { - stream.pipe(fs2.createWriteStream(filename)); - stream.on('error', reject); - stream.on('close', resolve); - }); + stat(err) + }) + }) + } - reporter.success(reporter.lang('packWroteTarball', filename)); - }); + var onfile = function () { + var ws = xfs.createWriteStream(name) + var rs = mapStream(stream, header) - return function run(_x5, _x6, _x7, _x8) { - return _ref4.apply(this, arguments); - }; -})(); + ws.on('error', function (err) { // always forward errors on destroy + rs.destroy(err) + }) -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; + pump(rs, ws, function (err) { + if (err) return next(err) + ws.on('close', stat) + }) + } -var _fs; + if (header.type === 'directory') { + stack.push([name, header.mtime]) + return mkdirfix(name, { + fs: xfs, own: own, uid: header.uid, gid: header.gid + }, stat) + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + mkdirfix(path.dirname(name), { + fs: xfs, own: own, uid: header.uid, gid: header.gid + }, function (err) { + if (err) return next(err) -var _filter; + switch (header.type) { + case 'file': return onfile() + case 'link': return onlink() + case 'symlink': return onsymlink() + } -function _load_filter() { - return _filter = __webpack_require__(206); -} + if (strict) return next(new Error('unsupported type for ' + name + ' (' + header.type + ')')) -var _errors; + stream.resume() + next() + }) + }) -function _load_errors() { - return _errors = __webpack_require__(3); + return extract } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const zlib = __webpack_require__(169); -const path = __webpack_require__(1); -const tar = __webpack_require__(109); -const fs2 = __webpack_require__(6); - -const FOLDERS_IGNORE = [ -// never allow version control folders -'.git', 'CVS', '.svn', '.hg', 'node_modules']; - -const DEFAULT_IGNORE = (0, (_filter || _load_filter()).ignoreLinesToRegex)([...FOLDERS_IGNORE, - -// ignore cruft -'yarn.lock', '.lock-wscript', '.wafpickle-{0..9}', '*.swp', '._*', 'npm-debug.log', 'yarn-error.log', '.npmrc', '.yarnrc', '.npmignore', '.gitignore', '.DS_Store']); - -const NEVER_IGNORE = (0, (_filter || _load_filter()).ignoreLinesToRegex)([ -// never ignore these files -'!/package.json', '!/readme*', '!/+(license|licence)*', '!/+(changes|changelog|history)*']); - -function setFlags(commander) { - commander.option('-f, --filename <filename>', 'filename'); +function mkdirfix (name, opts, cb) { + mkdirp(name, {fs: opts.xfs}, function (err, made) { + if (!err && made && opts.own) { + chownr(made, opts.uid, opts.gid, cb) + } else { + cb(err) + } + }) } -function hasWrapper(commander, args) { - return true; -} /***/ }), -/* 120 */ +/* 146 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +(function(nacl) { +'use strict'; +// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri. +// Public domain. +// +// Implementation derived from TweetNaCl version 20140427. +// See for details: http://tweetnacl.cr.yp.to/ -Object.defineProperty(exports, "__esModule", { - value: true -}); +var gf = function(init) { + var i, r = new Float64Array(16); + if (init) for (i = 0; i < init.length; i++) r[i] = init[i]; + return r; +}; -var _asyncToGenerator2; +// Pluggable, initialized in high-level API below. +var randombytes = function(/* x, n */) { throw new Error('no PRNG'); }; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +var _0 = new Uint8Array(16); +var _9 = new Uint8Array(32); _9[0] = 9; -var _executeLifecycleScript; +var gf0 = gf(), + gf1 = gf([1]), + _121665 = gf([0xdb41, 1]), + D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]), + D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]), + X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]), + Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]), + I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); -function _load_executeLifecycleScript() { - return _executeLifecycleScript = __webpack_require__(62); +function ts64(x, i, h, l) { + x[i] = (h >> 24) & 0xff; + x[i+1] = (h >> 16) & 0xff; + x[i+2] = (h >> 8) & 0xff; + x[i+3] = h & 0xff; + x[i+4] = (l >> 24) & 0xff; + x[i+5] = (l >> 16) & 0xff; + x[i+6] = (l >> 8) & 0xff; + x[i+7] = l & 0xff; } -var _path; - -function _load_path() { - return _path = __webpack_require__(208); +function vn(x, xi, y, yi, n) { + var i,d = 0; + for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i]; + return (1 & ((d - 1) >>> 8)) - 1; } -var _index; - -function _load_index() { - return _index = _interopRequireDefault(__webpack_require__(129)); +function crypto_verify_16(x, xi, y, yi) { + return vn(x,xi,y,yi,16); } -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); +function crypto_verify_32(x, xi, y, yi) { + return vn(x,xi,y,yi,32); } -var _fs; +function core_salsa20(o, p, k, c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; -var _constants; + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); -var _packageConstraintResolver; + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); -function _load_packageConstraintResolver() { - return _packageConstraintResolver = _interopRequireDefault(__webpack_require__(359)); -} + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); -var _requestManager; + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); -function _load_requestManager() { - return _requestManager = _interopRequireDefault(__webpack_require__(209)); -} + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); -var _index2; + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); -function _load_index2() { - return _index2 = __webpack_require__(24); -} + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } + x0 = x0 + j0 | 0; + x1 = x1 + j1 | 0; + x2 = x2 + j2 | 0; + x3 = x3 + j3 | 0; + x4 = x4 + j4 | 0; + x5 = x5 + j5 | 0; + x6 = x6 + j6 | 0; + x7 = x7 + j7 | 0; + x8 = x8 + j8 | 0; + x9 = x9 + j9 | 0; + x10 = x10 + j10 | 0; + x11 = x11 + j11 | 0; + x12 = x12 + j12 | 0; + x13 = x13 + j13 | 0; + x14 = x14 + j14 | 0; + x15 = x15 + j15 | 0; -var _index3; + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; -function _load_index3() { - return _index3 = __webpack_require__(82); -} + o[ 4] = x1 >>> 0 & 0xff; + o[ 5] = x1 >>> 8 & 0xff; + o[ 6] = x1 >>> 16 & 0xff; + o[ 7] = x1 >>> 24 & 0xff; -var _map; + o[ 8] = x2 >>> 0 & 0xff; + o[ 9] = x2 >>> 8 & 0xff; + o[10] = x2 >>> 16 & 0xff; + o[11] = x2 >>> 24 & 0xff; -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); -} + o[12] = x3 >>> 0 & 0xff; + o[13] = x3 >>> 8 & 0xff; + o[14] = x3 >>> 16 & 0xff; + o[15] = x3 >>> 24 & 0xff; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + o[16] = x4 >>> 0 & 0xff; + o[17] = x4 >>> 8 & 0xff; + o[18] = x4 >>> 16 & 0xff; + o[19] = x4 >>> 24 & 0xff; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + o[20] = x5 >>> 0 & 0xff; + o[21] = x5 >>> 8 & 0xff; + o[22] = x5 >>> 16 & 0xff; + o[23] = x5 >>> 24 & 0xff; -const detectIndent = __webpack_require__(456); + o[24] = x6 >>> 0 & 0xff; + o[25] = x6 >>> 8 & 0xff; + o[26] = x6 >>> 16 & 0xff; + o[27] = x6 >>> 24 & 0xff; -const invariant = __webpack_require__(5); -const path = __webpack_require__(1); -const micromatch = __webpack_require__(243); + o[28] = x7 >>> 0 & 0xff; + o[29] = x7 >>> 8 & 0xff; + o[30] = x7 >>> 16 & 0xff; + o[31] = x7 >>> 24 & 0xff; -function sortObject(object) { - const sortedObject = {}; - Object.keys(object).sort().forEach(item => { - sortedObject[item] = object[item]; - }); - return sortedObject; -} + o[32] = x8 >>> 0 & 0xff; + o[33] = x8 >>> 8 & 0xff; + o[34] = x8 >>> 16 & 0xff; + o[35] = x8 >>> 24 & 0xff; -class Config { - constructor(reporter) { - this.constraintResolver = new (_packageConstraintResolver || _load_packageConstraintResolver()).default(this, reporter); - this.requestManager = new (_requestManager || _load_requestManager()).default(reporter); - this.reporter = reporter; - this._init({}); - } + o[36] = x9 >>> 0 & 0xff; + o[37] = x9 >>> 8 & 0xff; + o[38] = x9 >>> 16 & 0xff; + o[39] = x9 >>> 24 & 0xff; - // + o[40] = x10 >>> 0 & 0xff; + o[41] = x10 >>> 8 & 0xff; + o[42] = x10 >>> 16 & 0xff; + o[43] = x10 >>> 24 & 0xff; + o[44] = x11 >>> 0 & 0xff; + o[45] = x11 >>> 8 & 0xff; + o[46] = x11 >>> 16 & 0xff; + o[47] = x11 >>> 24 & 0xff; - // - - - // + o[48] = x12 >>> 0 & 0xff; + o[49] = x12 >>> 8 & 0xff; + o[50] = x12 >>> 16 & 0xff; + o[51] = x12 >>> 24 & 0xff; + o[52] = x13 >>> 0 & 0xff; + o[53] = x13 >>> 8 & 0xff; + o[54] = x13 >>> 16 & 0xff; + o[55] = x13 >>> 24 & 0xff; - // + o[56] = x14 >>> 0 & 0xff; + o[57] = x14 >>> 8 & 0xff; + o[58] = x14 >>> 16 & 0xff; + o[59] = x14 >>> 24 & 0xff; + o[60] = x15 >>> 0 & 0xff; + o[61] = x15 >>> 8 & 0xff; + o[62] = x15 >>> 16 & 0xff; + o[63] = x15 >>> 24 & 0xff; +} - // +function core_hsalsa20(o,p,k,c) { + var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24, + j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24, + j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24, + j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24, + j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24, + j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24, + j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24, + j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24, + j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24, + j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24, + j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24, + j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24, + j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24, + j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24, + j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24, + j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24; + var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, + x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, + x15 = j15, u; - // + for (var i = 0; i < 20; i += 2) { + u = x0 + x12 | 0; + x4 ^= u<<7 | u>>>(32-7); + u = x4 + x0 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x4 | 0; + x12 ^= u<<13 | u>>>(32-13); + u = x12 + x8 | 0; + x0 ^= u<<18 | u>>>(32-18); + u = x5 + x1 | 0; + x9 ^= u<<7 | u>>>(32-7); + u = x9 + x5 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x9 | 0; + x1 ^= u<<13 | u>>>(32-13); + u = x1 + x13 | 0; + x5 ^= u<<18 | u>>>(32-18); - // + u = x10 + x6 | 0; + x14 ^= u<<7 | u>>>(32-7); + u = x14 + x10 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x14 | 0; + x6 ^= u<<13 | u>>>(32-13); + u = x6 + x2 | 0; + x10 ^= u<<18 | u>>>(32-18); + u = x15 + x11 | 0; + x3 ^= u<<7 | u>>>(32-7); + u = x3 + x15 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x3 | 0; + x11 ^= u<<13 | u>>>(32-13); + u = x11 + x7 | 0; + x15 ^= u<<18 | u>>>(32-18); - // + u = x0 + x3 | 0; + x1 ^= u<<7 | u>>>(32-7); + u = x1 + x0 | 0; + x2 ^= u<<9 | u>>>(32-9); + u = x2 + x1 | 0; + x3 ^= u<<13 | u>>>(32-13); + u = x3 + x2 | 0; + x0 ^= u<<18 | u>>>(32-18); + u = x5 + x4 | 0; + x6 ^= u<<7 | u>>>(32-7); + u = x6 + x5 | 0; + x7 ^= u<<9 | u>>>(32-9); + u = x7 + x6 | 0; + x4 ^= u<<13 | u>>>(32-13); + u = x4 + x7 | 0; + x5 ^= u<<18 | u>>>(32-18); - // + u = x10 + x9 | 0; + x11 ^= u<<7 | u>>>(32-7); + u = x11 + x10 | 0; + x8 ^= u<<9 | u>>>(32-9); + u = x8 + x11 | 0; + x9 ^= u<<13 | u>>>(32-13); + u = x9 + x8 | 0; + x10 ^= u<<18 | u>>>(32-18); + u = x15 + x14 | 0; + x12 ^= u<<7 | u>>>(32-7); + u = x12 + x15 | 0; + x13 ^= u<<9 | u>>>(32-9); + u = x13 + x12 | 0; + x14 ^= u<<13 | u>>>(32-13); + u = x14 + x13 | 0; + x15 ^= u<<18 | u>>>(32-18); + } - // + o[ 0] = x0 >>> 0 & 0xff; + o[ 1] = x0 >>> 8 & 0xff; + o[ 2] = x0 >>> 16 & 0xff; + o[ 3] = x0 >>> 24 & 0xff; + o[ 4] = x5 >>> 0 & 0xff; + o[ 5] = x5 >>> 8 & 0xff; + o[ 6] = x5 >>> 16 & 0xff; + o[ 7] = x5 >>> 24 & 0xff; - // + o[ 8] = x10 >>> 0 & 0xff; + o[ 9] = x10 >>> 8 & 0xff; + o[10] = x10 >>> 16 & 0xff; + o[11] = x10 >>> 24 & 0xff; + o[12] = x15 >>> 0 & 0xff; + o[13] = x15 >>> 8 & 0xff; + o[14] = x15 >>> 16 & 0xff; + o[15] = x15 >>> 24 & 0xff; - // + o[16] = x6 >>> 0 & 0xff; + o[17] = x6 >>> 8 & 0xff; + o[18] = x6 >>> 16 & 0xff; + o[19] = x6 >>> 24 & 0xff; + o[20] = x7 >>> 0 & 0xff; + o[21] = x7 >>> 8 & 0xff; + o[22] = x7 >>> 16 & 0xff; + o[23] = x7 >>> 24 & 0xff; - // + o[24] = x8 >>> 0 & 0xff; + o[25] = x8 >>> 8 & 0xff; + o[26] = x8 >>> 16 & 0xff; + o[27] = x8 >>> 24 & 0xff; + o[28] = x9 >>> 0 & 0xff; + o[29] = x9 >>> 8 & 0xff; + o[30] = x9 >>> 16 & 0xff; + o[31] = x9 >>> 24 & 0xff; +} - // Whether we should ignore executing lifecycle scripts +function crypto_core_salsa20(out,inp,k,c) { + core_salsa20(out,inp,k,c); +} +function crypto_core_hsalsa20(out,inp,k,c) { + core_hsalsa20(out,inp,k,c); +} - // +var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); + // "expand 32-byte k" +function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + mpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i]; + } + return 0; +} - // +function crypto_stream_salsa20(c,cpos,b,n,k) { + var z = new Uint8Array(16), x = new Uint8Array(64); + var u, i; + for (i = 0; i < 16; i++) z[i] = 0; + for (i = 0; i < 8; i++) z[i] = n[i]; + while (b >= 64) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < 64; i++) c[cpos+i] = x[i]; + u = 1; + for (i = 8; i < 16; i++) { + u = u + (z[i] & 0xff) | 0; + z[i] = u & 0xff; + u >>>= 8; + } + b -= 64; + cpos += 64; + } + if (b > 0) { + crypto_core_salsa20(x,z,k,sigma); + for (i = 0; i < b; i++) c[cpos+i] = x[i]; + } + return 0; +} +function crypto_stream(c,cpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20(c,cpos,d,sn,s); +} - // +function crypto_stream_xor(c,cpos,m,mpos,d,n,k) { + var s = new Uint8Array(32); + crypto_core_hsalsa20(s,n,k,sigma); + var sn = new Uint8Array(8); + for (var i = 0; i < 8; i++) sn[i] = n[i+16]; + return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s); +} +/* +* Port of Andrew Moon's Poly1305-donna-16. Public domain. +* https://github.com/floodyberry/poly1305-donna +*/ - // +var poly1305 = function(key) { + this.buffer = new Uint8Array(16); + this.r = new Uint16Array(10); + this.h = new Uint16Array(10); + this.pad = new Uint16Array(8); + this.leftover = 0; + this.fin = 0; + var t0, t1, t2, t3, t4, t5, t6, t7; - /** - * Execute a promise produced by factory if it doesn't exist in our cache with - * the associated key. - */ + t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff; + t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = ((t4 >>> 1)) & 0x1ffe; + t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = ((t7 >>> 5)) & 0x007f; - getCache(key, factory) { - const cached = this.cache[key]; - if (cached) { - return cached; - } + this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8; + this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8; + this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8; + this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8; + this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8; + this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8; + this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8; + this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8; +}; - return this.cache[key] = factory().catch(err => { - this.cache[key] = null; - throw err; - }); - } +poly1305.prototype.blocks = function(m, mpos, bytes) { + var hibit = this.fin ? 0 : (1 << 11); + var t0, t1, t2, t3, t4, t5, t6, t7, c; + var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - /** - * Get a config option from our yarn config. - */ + var h0 = this.h[0], + h1 = this.h[1], + h2 = this.h[2], + h3 = this.h[3], + h4 = this.h[4], + h5 = this.h[5], + h6 = this.h[6], + h7 = this.h[7], + h8 = this.h[8], + h9 = this.h[9]; - getOption(key) { - let expand = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + var r0 = this.r[0], + r1 = this.r[1], + r2 = this.r[2], + r3 = this.r[3], + r4 = this.r[4], + r5 = this.r[5], + r6 = this.r[6], + r7 = this.r[7], + r8 = this.r[8], + r9 = this.r[9]; - const value = this.registries.yarn.getOption(key); + while (bytes >= 16) { + t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff; + t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff; + t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff; + h5 += ((t4 >>> 1)) & 0x1fff; + t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff; + t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + h9 += ((t7 >>> 5)) | hibit; - if (expand && typeof value === 'string') { - return (0, (_path || _load_path()).expandPath)(value); - } + c = 0; - return value; - } + d0 = c; + d0 += h0 * r0; + d0 += h1 * (5 * r9); + d0 += h2 * (5 * r8); + d0 += h3 * (5 * r7); + d0 += h4 * (5 * r6); + c = (d0 >>> 13); d0 &= 0x1fff; + d0 += h5 * (5 * r5); + d0 += h6 * (5 * r4); + d0 += h7 * (5 * r3); + d0 += h8 * (5 * r2); + d0 += h9 * (5 * r1); + c += (d0 >>> 13); d0 &= 0x1fff; - /** - * Reduce a list of versions to a single one based on an input range. - */ + d1 = c; + d1 += h0 * r1; + d1 += h1 * r0; + d1 += h2 * (5 * r9); + d1 += h3 * (5 * r8); + d1 += h4 * (5 * r7); + c = (d1 >>> 13); d1 &= 0x1fff; + d1 += h5 * (5 * r6); + d1 += h6 * (5 * r5); + d1 += h7 * (5 * r4); + d1 += h8 * (5 * r3); + d1 += h9 * (5 * r2); + c += (d1 >>> 13); d1 &= 0x1fff; - resolveConstraints(versions, range) { - return this.constraintResolver.reduce(versions, range); - } + d2 = c; + d2 += h0 * r2; + d2 += h1 * r1; + d2 += h2 * r0; + d2 += h3 * (5 * r9); + d2 += h4 * (5 * r8); + c = (d2 >>> 13); d2 &= 0x1fff; + d2 += h5 * (5 * r7); + d2 += h6 * (5 * r6); + d2 += h7 * (5 * r5); + d2 += h8 * (5 * r4); + d2 += h9 * (5 * r3); + c += (d2 >>> 13); d2 &= 0x1fff; - /** - * Initialise config. Fetch registry options, find package roots. - */ + d3 = c; + d3 += h0 * r3; + d3 += h1 * r2; + d3 += h2 * r1; + d3 += h3 * r0; + d3 += h4 * (5 * r9); + c = (d3 >>> 13); d3 &= 0x1fff; + d3 += h5 * (5 * r8); + d3 += h6 * (5 * r7); + d3 += h7 * (5 * r6); + d3 += h8 * (5 * r5); + d3 += h9 * (5 * r4); + c += (d3 >>> 13); d3 &= 0x1fff; - init() { - var _this = this; + d4 = c; + d4 += h0 * r4; + d4 += h1 * r3; + d4 += h2 * r2; + d4 += h3 * r1; + d4 += h4 * r0; + c = (d4 >>> 13); d4 &= 0x1fff; + d4 += h5 * (5 * r9); + d4 += h6 * (5 * r8); + d4 += h7 * (5 * r7); + d4 += h8 * (5 * r6); + d4 += h9 * (5 * r5); + c += (d4 >>> 13); d4 &= 0x1fff; - let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this._init(opts); + d5 = c; + d5 += h0 * r5; + d5 += h1 * r4; + d5 += h2 * r3; + d5 += h3 * r2; + d5 += h4 * r1; + c = (d5 >>> 13); d5 &= 0x1fff; + d5 += h5 * r0; + d5 += h6 * (5 * r9); + d5 += h7 * (5 * r8); + d5 += h8 * (5 * r7); + d5 += h9 * (5 * r6); + c += (d5 >>> 13); d5 &= 0x1fff; - _this.workspaceRootFolder = yield _this.findWorkspaceRoot(_this.cwd); - _this.lockfileFolder = _this.workspaceRootFolder || _this.cwd; + d6 = c; + d6 += h0 * r6; + d6 += h1 * r5; + d6 += h2 * r4; + d6 += h3 * r3; + d6 += h4 * r2; + c = (d6 >>> 13); d6 &= 0x1fff; + d6 += h5 * r1; + d6 += h6 * r0; + d6 += h7 * (5 * r9); + d6 += h8 * (5 * r8); + d6 += h9 * (5 * r7); + c += (d6 >>> 13); d6 &= 0x1fff; - yield (_fs || _load_fs()).mkdirp(_this.globalFolder); - yield (_fs || _load_fs()).mkdirp(_this.linkFolder); + d7 = c; + d7 += h0 * r7; + d7 += h1 * r6; + d7 += h2 * r5; + d7 += h3 * r4; + d7 += h4 * r3; + c = (d7 >>> 13); d7 &= 0x1fff; + d7 += h5 * r2; + d7 += h6 * r1; + d7 += h7 * r0; + d7 += h8 * (5 * r9); + d7 += h9 * (5 * r8); + c += (d7 >>> 13); d7 &= 0x1fff; - _this.linkedModules = []; + d8 = c; + d8 += h0 * r8; + d8 += h1 * r7; + d8 += h2 * r6; + d8 += h3 * r5; + d8 += h4 * r4; + c = (d8 >>> 13); d8 &= 0x1fff; + d8 += h5 * r3; + d8 += h6 * r2; + d8 += h7 * r1; + d8 += h8 * r0; + d8 += h9 * (5 * r9); + c += (d8 >>> 13); d8 &= 0x1fff; - const linkedModules = yield (_fs || _load_fs()).readdir(_this.linkFolder); + d9 = c; + d9 += h0 * r9; + d9 += h1 * r8; + d9 += h2 * r7; + d9 += h3 * r6; + d9 += h4 * r5; + c = (d9 >>> 13); d9 &= 0x1fff; + d9 += h5 * r4; + d9 += h6 * r3; + d9 += h7 * r2; + d9 += h8 * r1; + d9 += h9 * r0; + c += (d9 >>> 13); d9 &= 0x1fff; - for (const dir of linkedModules) { - const linkedPath = path.join(_this.linkFolder, dir); + c = (((c << 2) + c)) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = (c >>> 13); + d1 += c; - if (dir[0] === '@') { - // it's a scope, not a package - const scopedLinked = yield (_fs || _load_fs()).readdir(linkedPath); - _this.linkedModules.push(...scopedLinked.map(function (scopedDir) { - return path.join(dir, scopedDir); - })); - } else { - _this.linkedModules.push(dir); - } - } + h0 = d0; + h1 = d1; + h2 = d2; + h3 = d3; + h4 = d4; + h5 = d5; + h6 = d6; + h7 = d7; + h8 = d8; + h9 = d9; - for (const key of Object.keys((_index2 || _load_index2()).registries)) { - const Registry = (_index2 || _load_index2()).registries[key]; + mpos += 16; + bytes -= 16; + } + this.h[0] = h0; + this.h[1] = h1; + this.h[2] = h2; + this.h[3] = h3; + this.h[4] = h4; + this.h[5] = h5; + this.h[6] = h6; + this.h[7] = h7; + this.h[8] = h8; + this.h[9] = h9; +}; - // instantiate registry - const registry = new Registry(_this.cwd, _this.registries, _this.requestManager, _this.reporter); - yield registry.init(); +poly1305.prototype.finish = function(mac, macpos) { + var g = new Uint16Array(10); + var c, mask, f, i; - _this.registries[key] = registry; - _this.registryFolders.push(registry.folder); - const rootModuleFolder = path.join(_this.cwd, registry.folder); - if (_this.rootModuleFolders.indexOf(rootModuleFolder) < 0) { - _this.rootModuleFolders.push(rootModuleFolder); - } - } - - _this.networkConcurrency = opts.networkConcurrency || Number(_this.getOption('network-concurrency')) || (_constants || _load_constants()).NETWORK_CONCURRENCY; - - _this.childConcurrency = opts.childConcurrency || Number(_this.getOption('child-concurrency')) || Number(process.env.CHILD_CONCURRENCY) || (_constants || _load_constants()).CHILD_CONCURRENCY; - - _this.networkTimeout = opts.networkTimeout || Number(_this.getOption('network-timeout')) || (_constants || _load_constants()).NETWORK_TIMEOUT; - - _this.requestManager.setOptions({ - userAgent: String(_this.getOption('user-agent')), - httpProxy: String(opts.httpProxy || _this.getOption('proxy') || ''), - httpsProxy: String(opts.httpsProxy || _this.getOption('https-proxy') || ''), - strictSSL: Boolean(_this.getOption('strict-ssl')), - ca: Array.prototype.concat(opts.ca || _this.getOption('ca') || []).map(String), - cafile: String(opts.cafile || _this.getOption('cafile') || ''), - cert: String(opts.cert || _this.getOption('cert') || ''), - key: String(opts.key || _this.getOption('key') || ''), - networkConcurrency: _this.networkConcurrency, - networkTimeout: _this.networkTimeout - }); - _this._cacheRootFolder = String(opts.cacheFolder || _this.getOption('cache-folder') || (_constants || _load_constants()).MODULE_CACHE_DIRECTORY); - _this.workspacesEnabled = Boolean(_this.getOption('workspaces-experimental')); - - _this.pruneOfflineMirror = Boolean(_this.getOption('yarn-offline-mirror-pruning')); - _this.enableMetaFolder = Boolean(_this.getOption('enable-meta-folder')); - _this.enableLockfileVersions = Boolean(_this.getOption('yarn-enable-lockfile-versions')); - _this.linkFileDependencies = Boolean(_this.getOption('yarn-link-file-dependencies')); - - //init & create cacheFolder, tempFolder - _this.cacheFolder = path.join(_this._cacheRootFolder, 'v' + String((_constants || _load_constants()).CACHE_VERSION)); - _this.tempFolder = opts.tempFolder || path.join(_this.cacheFolder, '.tmp'); - yield (_fs || _load_fs()).mkdirp(_this.cacheFolder); - yield (_fs || _load_fs()).mkdirp(_this.tempFolder); - - if (opts.production === 'false') { - _this.production = false; - } else if (_this.getOption('production') || process.env.NODE_ENV === 'production' && process.env.NPM_CONFIG_PRODUCTION !== 'false' && process.env.YARN_PRODUCTION !== 'false') { - _this.production = true; - } else { - _this.production = !!opts.production; - } - - if (_this.workspaceRootFolder && !_this.workspacesEnabled) { - throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('workspaceExperimentalDisabled')); - } - })(); - } - - _init(opts) { - this.rootModuleFolders = []; - this.registryFolders = []; - this.linkedModules = []; - - this.registries = (0, (_map || _load_map()).default)(); - this.cache = (0, (_map || _load_map()).default)(); - this.cwd = opts.cwd || this.cwd || process.cwd(); - - this.looseSemver = opts.looseSemver == undefined ? true : opts.looseSemver; - - this.commandName = opts.commandName || ''; - - this.preferOffline = !!opts.preferOffline; - this.modulesFolder = opts.modulesFolder; - this.globalFolder = opts.globalFolder || (_constants || _load_constants()).GLOBAL_MODULE_DIRECTORY; - this.linkFolder = opts.linkFolder || (_constants || _load_constants()).LINK_REGISTRY_DIRECTORY; - this.offline = !!opts.offline; - this.binLinks = !!opts.binLinks; - - this.ignorePlatform = !!opts.ignorePlatform; - this.ignoreScripts = !!opts.ignoreScripts; - - this.disablePrepublish = !!opts.disablePrepublish; - - this.nonInteractive = !!opts.nonInteractive; - - this.requestManager.setOptions({ - offline: !!opts.offline && !opts.preferOffline, - captureHar: !!opts.captureHar - }); - - if (this.modulesFolder) { - this.rootModuleFolders.push(this.modulesFolder); - } - } - - /** - * Generate an absolute module path. - */ - - generateHardModulePath(pkg, ignoreLocation) { - invariant(this.cacheFolder, 'No package root'); - invariant(pkg, 'Undefined package'); - - if (pkg.location && !ignoreLocation) { - return pkg.location; - } - - let name = pkg.name; - let uid = pkg.uid; - if (pkg.registry) { - name = `${pkg.registry}-${name}`; - } - - const hash = pkg.remote.hash; - - - if (pkg.version && pkg.version !== pkg.uid) { - uid = `${pkg.version}-${uid}`; - } else if (hash) { - uid += `-${hash}`; - } - - return path.join(this.cacheFolder, `${name}-${uid}`); + if (this.leftover) { + i = this.leftover; + this.buffer[i++] = 1; + for (; i < 16; i++) this.buffer[i] = 0; + this.fin = 1; + this.blocks(this.buffer, 0, 16); } - /** - * Execute lifecycle scripts in the specified directory. Ignoring when the --ignore-scripts flag has been - * passed. - */ - - executeLifecycleScript(commandName, cwd) { - if (this.ignoreScripts) { - return Promise.resolve(); - } else { - return (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execFromManifest)(this, commandName, cwd || this.cwd); - } + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + for (i = 2; i < 10; i++) { + this.h[i] += c; + c = this.h[i] >>> 13; + this.h[i] &= 0x1fff; } + this.h[0] += (c * 5); + c = this.h[0] >>> 13; + this.h[0] &= 0x1fff; + this.h[1] += c; + c = this.h[1] >>> 13; + this.h[1] &= 0x1fff; + this.h[2] += c; - /** - * Generate an absolute temporary filename location based on the input filename. - */ - - getTemp(filename) { - invariant(this.tempFolder, 'No temp folder'); - return path.join(this.tempFolder, filename); + g[0] = this.h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (i = 1; i < 10; i++) { + g[i] = this.h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; } + g[9] -= (1 << 13); - /** - * Remote packages may be cached in a file system to be available for offline installation. - * Second time the same package needs to be installed it will be loaded from there. - * Given a package's filename, return a path in the offline mirror location. - */ - - getOfflineMirrorPath(packageFilename) { - let mirrorPath; - - for (const key of ['npm', 'yarn']) { - const registry = this.registries[key]; - - if (registry == null) { - continue; - } - - const registryMirrorPath = registry.config['yarn-offline-mirror']; - - if (registryMirrorPath === false) { - return null; - } - - if (registryMirrorPath == null) { - continue; - } - - mirrorPath = registryMirrorPath; - } - - if (mirrorPath == null) { - return null; - } + mask = (c ^ 1) - 1; + for (i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i]; - if (packageFilename == null) { - return mirrorPath; - } + this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff; + this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff; + this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff; + this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff; + this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff; + this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff; + this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff; + this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff; - return path.join(mirrorPath, path.basename(packageFilename)); + f = this.h[0] + this.pad[0]; + this.h[0] = f & 0xffff; + for (i = 1; i < 8; i++) { + f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0; + this.h[i] = f & 0xffff; } - /** - * Checker whether the folder input is a valid module folder. We output a yarn metadata - * file when we've successfully setup a folder so use this as a marker. - */ - - isValidModuleDest(dest) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (!(yield (_fs || _load_fs()).exists(dest))) { - return false; - } + mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff; + mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff; + mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff; + mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff; + mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff; + mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff; + mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff; + mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff; + mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff; + mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff; + mac[macpos+10] = (this.h[5] >>> 0) & 0xff; + mac[macpos+11] = (this.h[5] >>> 8) & 0xff; + mac[macpos+12] = (this.h[6] >>> 0) & 0xff; + mac[macpos+13] = (this.h[6] >>> 8) & 0xff; + mac[macpos+14] = (this.h[7] >>> 0) & 0xff; + mac[macpos+15] = (this.h[7] >>> 8) & 0xff; +}; - if (!(yield (_fs || _load_fs()).exists(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME)))) { - return false; - } +poly1305.prototype.update = function(m, mpos, bytes) { + var i, want; - return true; - })(); + if (this.leftover) { + want = (16 - this.leftover); + if (want > bytes) + want = bytes; + for (i = 0; i < want; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + bytes -= want; + mpos += want; + this.leftover += want; + if (this.leftover < 16) + return; + this.blocks(this.buffer, 0, 16); + this.leftover = 0; } - /** - * Read package metadata and normalized package info. - */ - - readPackageMetadata(dir) { - var _this2 = this; - - return this.getCache(`metadata-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const metadata = yield _this2.readJson(path.join(dir, (_constants || _load_constants()).METADATA_FILENAME)); - const pkg = yield _this2.readManifest(dir, metadata.registry); - - return { - package: pkg, - artifacts: metadata.artifacts || [], - hash: metadata.hash, - remote: metadata.remote, - registry: metadata.registry - }; - })); + if (bytes >= 16) { + want = bytes - (bytes % 16); + this.blocks(m, mpos, want); + mpos += want; + bytes -= want; } - /** - * Read normalized package info according yarn-metadata.json - * throw an error if package.json was not found - */ - - readManifest(dir, priorityRegistry) { - var _this3 = this; - - let isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - - return this.getCache(`manifest-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const manifest = yield _this3.maybeReadManifest(dir, priorityRegistry, isRoot); - - if (manifest) { - return manifest; - } else { - throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('couldntFindPackagejson', dir), 'ENOENT'); - } - })); + if (bytes) { + for (i = 0; i < bytes; i++) + this.buffer[this.leftover + i] = m[mpos+i]; + this.leftover += bytes; } +}; - /** - * try get the manifest file by looking - * 1. manifest file in cache - * 2. manifest file in registry - */ - maybeReadManifest(dir, priorityRegistry) { - var _this4 = this; - - let isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const metadataLoc = path.join(dir, (_constants || _load_constants()).METADATA_FILENAME); - - if (yield (_fs || _load_fs()).exists(metadataLoc)) { - const metadata = yield _this4.readJson(metadataLoc); - - if (!priorityRegistry) { - priorityRegistry = metadata.priorityRegistry; - } +function crypto_onetimeauth(out, outpos, m, mpos, n, k) { + var s = new poly1305(k); + s.update(m, mpos, n); + s.finish(out, outpos); + return 0; +} - if (typeof metadata.manifest !== 'undefined') { - return metadata.manifest; - } - } +function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) { + var x = new Uint8Array(16); + crypto_onetimeauth(x,0,m,mpos,n,k); + return crypto_verify_16(h,hpos,x,0); +} - if (priorityRegistry) { - const file = yield _this4.tryManifest(dir, priorityRegistry, isRoot); - if (file) { - return file; - } - } +function crypto_secretbox(c,m,d,n,k) { + var i; + if (d < 32) return -1; + crypto_stream_xor(c,0,m,0,d,n,k); + crypto_onetimeauth(c, 16, c, 32, d - 32, c); + for (i = 0; i < 16; i++) c[i] = 0; + return 0; +} - for (const registry of Object.keys((_index2 || _load_index2()).registries)) { - if (priorityRegistry === registry) { - continue; - } +function crypto_secretbox_open(m,c,d,n,k) { + var i; + var x = new Uint8Array(32); + if (d < 32) return -1; + crypto_stream(x,0,32,n,k); + if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1; + crypto_stream_xor(m,0,c,0,d,n,k); + for (i = 0; i < 32; i++) m[i] = 0; + return 0; +} - const file = yield _this4.tryManifest(dir, registry, isRoot); - if (file) { - return file; - } - } +function set25519(r, a) { + var i; + for (i = 0; i < 16; i++) r[i] = a[i]|0; +} - return null; - })(); +function car25519(o) { + var i, v, c = 1; + for (i = 0; i < 16; i++) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; } + o[0] += c-1 + 37 * (c-1); +} - /** - * Read the root manifest. - */ - - readRootManifest() { - return this.readManifest(this.cwd, 'npm', true); +function sel25519(p, q, b) { + var t, c = ~(b-1); + for (var i = 0; i < 16; i++) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; } +} - /** - * Try and find package info with the input directory and registry. - */ - - tryManifest(dir, registry, isRoot) { - var _this5 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const filename = (_index2 || _load_index2()).registries[registry].filename; - - const loc = path.join(dir, filename); - if (yield (_fs || _load_fs()).exists(loc)) { - const data = yield _this5.readJson(loc); - data._registry = registry; - data._loc = loc; - return (0, (_index || _load_index()).default)(data, dir, _this5, isRoot); - } else { - return null; - } - })(); +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for (i = 0; i < 16; i++) t[i] = n[i]; + car25519(t); + car25519(t); + car25519(t); + for (j = 0; j < 2; j++) { + m[0] = t[0] - 0xffed; + for (i = 1; i < 15; i++) { + m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1); + b = (m[15]>>16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1-b); } - - findManifest(dir, isRoot) { - var _this6 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - for (const registry of (_index2 || _load_index2()).registryNames) { - const manifest = yield _this6.tryManifest(dir, registry, isRoot); - - if (manifest) { - return manifest; - } - } - - return null; - })(); + for (i = 0; i < 16; i++) { + o[2*i] = t[i] & 0xff; + o[2*i+1] = t[i]>>8; } +} - findWorkspaceRoot(initial) { - var _this7 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let previous = null; - let current = path.normalize(initial); - - do { - const manifest = yield _this7.findManifest(current, true); - if (manifest && manifest.workspaces) { - const relativePath = path.relative(current, initial); - if (relativePath === '' || micromatch([relativePath], manifest.workspaces).length > 0) { - return current; - } else { - return null; - } - } - - previous = current; - current = path.dirname(current); - } while (current !== previous); +function neq25519(a, b) { + var c = new Uint8Array(32), d = new Uint8Array(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} - return null; - })(); - } +function par25519(a) { + var d = new Uint8Array(32); + pack25519(d, a); + return d[0] & 1; +} - resolveWorkspaces(root, rootManifest) { - var _this8 = this; +function unpack25519(o, n) { + var i; + for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8); + o[15] &= 0x7fff; +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const workspaces = {}; - const patterns = rootManifest.workspaces || []; - if (!_this8.workspacesEnabled) { - return workspaces; - } - if (!rootManifest.private && patterns.length > 0) { - throw new (_errors || _load_errors()).MessageError(_this8.reporter.lang('workspacesRequirePrivateProjects')); - } +function A(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] + b[i]; +} - const registryFilenames = (_index2 || _load_index2()).registryNames.map(function (registryName) { - return _this8.registries[registryName].constructor.filename; - }); - const trailingPattern = `/+(${registryFilenames.join(`|`)})`; +function Z(o, a, b) { + for (var i = 0; i < 16; i++) o[i] = a[i] - b[i]; +} - const files = yield Promise.all(patterns.map(function (pattern) { - return (_fs || _load_fs()).glob(pattern.replace(/\/?$/, trailingPattern), { cwd: root, ignore: _this8.registryFolders }); - })); +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; - for (const file of new Set([].concat(...files))) { - const loc = path.join(root, path.dirname(file)); - const manifest = yield _this8.findManifest(loc, false); + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; - if (!manifest) { - continue; - } + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is - if (!manifest.name) { - _this8.reporter.warn(_this8.reporter.lang('workspaceNameMandatory', loc)); - continue; - } - if (!manifest.version) { - _this8.reporter.warn(_this8.reporter.lang('workspaceVersionMandatory', loc)); - continue; - } + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - if (Object.prototype.hasOwnProperty.call(workspaces, manifest.name)) { - throw new (_errors || _load_errors()).MessageError(_this8.reporter.lang('workspaceNameDuplicate', manifest.name)); - } + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); - workspaces[manifest.name] = { loc, manifest }; - } + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} - return workspaces; - })(); - } +function S(o, a) { + M(o, a, a); +} - /** - * Description - */ +function inv25519(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 253; a >= 0; a--) { + S(c, c); + if(a !== 2 && a !== 4) M(c, c, i); + } + for (a = 0; a < 16; a++) o[a] = c[a]; +} - getFolder(pkg) { - let registryName = pkg._registry; - if (!registryName) { - const ref = pkg._reference; - invariant(ref, 'expected reference'); - registryName = ref.registry; - } - return this.registries[registryName].folder; +function pow2523(o, i) { + var c = gf(); + var a; + for (a = 0; a < 16; a++) c[a] = i[a]; + for (a = 250; a >= 0; a--) { + S(c, c); + if(a !== 1) M(c, c, i); } + for (a = 0; a < 16; a++) o[a] = c[a]; +} - /** - * Get root manifests. - */ +function crypto_scalarmult(q, n, p) { + var z = new Uint8Array(32); + var x = new Float64Array(80), r, i; + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(); + for (i = 0; i < 31; i++) z[i] = n[i]; + z[31]=(n[31]&127)|64; + z[0]&=248; + unpack25519(x,p); + for (i = 0; i < 16; i++) { + b[i]=x[i]; + d[i]=a[i]=c[i]=0; + } + a[0]=d[0]=1; + for (i=254; i>=0; --i) { + r=(z[i>>>3]>>>(i&7))&1; + sel25519(a,b,r); + sel25519(c,d,r); + A(e,a,c); + Z(a,a,c); + A(c,b,d); + Z(b,b,d); + S(d,e); + S(f,a); + M(a,c,a); + M(c,b,e); + A(e,a,c); + Z(a,a,c); + S(b,a); + Z(c,d,f); + M(a,c,_121665); + A(a,a,d); + M(c,c,a); + M(a,d,f); + M(d,b,x); + S(b,e); + sel25519(a,b,r); + sel25519(c,d,r); + } + for (i = 0; i < 16; i++) { + x[i+16]=a[i]; + x[i+32]=c[i]; + x[i+48]=b[i]; + x[i+64]=d[i]; + } + var x32 = x.subarray(32); + var x16 = x.subarray(16); + inv25519(x32,x32); + M(x16,x16,x32); + pack25519(q,x16); + return 0; +} - getRootManifests() { - var _this9 = this; +function crypto_scalarmult_base(q, n) { + return crypto_scalarmult(q, n, _9); +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const manifests = {}; - for (const registryName of (_index2 || _load_index2()).registryNames) { - const registry = (_index2 || _load_index2()).registries[registryName]; - const jsonLoc = path.join(_this9.cwd, registry.filename); +function crypto_box_keypair(y, x) { + randombytes(x, 32); + return crypto_scalarmult_base(y, x); +} - let object = {}; - let exists = false; - let indent; - if (yield (_fs || _load_fs()).exists(jsonLoc)) { - exists = true; +function crypto_box_beforenm(k, y, x) { + var s = new Uint8Array(32); + crypto_scalarmult(s, x, y); + return crypto_core_hsalsa20(k, _0, s, sigma); +} - const info = yield _this9.readJson(jsonLoc, (_fs || _load_fs()).readJsonAndFile); - object = info.object; - indent = detectIndent(info.content).indent || undefined; - } - manifests[registryName] = { loc: jsonLoc, object, exists, indent }; - } - return manifests; - })(); - } +var crypto_box_afternm = crypto_secretbox; +var crypto_box_open_afternm = crypto_secretbox_open; - /** - * Save root manifests. - */ - - saveRootManifests(manifests) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - for (const registryName of (_index2 || _load_index2()).registryNames) { - var _manifests$registryNa = manifests[registryName]; - const loc = _manifests$registryNa.loc, - object = _manifests$registryNa.object, - exists = _manifests$registryNa.exists, - indent = _manifests$registryNa.indent; +function crypto_box(c, m, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_afternm(c, m, d, n, k); +} - if (!exists && !Object.keys(object).length) { - continue; - } +function crypto_box_open(m, c, d, n, y, x) { + var k = new Uint8Array(32); + crypto_box_beforenm(k, y, x); + return crypto_box_open_afternm(m, c, d, n, k); +} - for (const field of (_constants || _load_constants()).DEPENDENCY_TYPES) { - if (object[field]) { - object[field] = sortObject(object[field]); - } - } +var K = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 +]; - yield (_fs || _load_fs()).writeFilePreservingEol(loc, JSON.stringify(object, null, indent || (_constants || _load_constants()).DEFAULT_INDENT) + '\n'); - } - })(); - } +function crypto_hashblocks_hl(hh, hl, m, n) { + var wh = new Int32Array(16), wl = new Int32Array(16), + bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, + bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, + th, tl, i, j, h, l, a, b, c, d; - /** - * Call the passed factory (defaults to fs.readJson) and rethrow a pretty error message if it was the result - * of a syntax error. - */ + var ah0 = hh[0], + ah1 = hh[1], + ah2 = hh[2], + ah3 = hh[3], + ah4 = hh[4], + ah5 = hh[5], + ah6 = hh[6], + ah7 = hh[7], - readJson(loc) { - let factory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_fs || _load_fs()).readJson; + al0 = hl[0], + al1 = hl[1], + al2 = hl[2], + al3 = hl[3], + al4 = hl[4], + al5 = hl[5], + al6 = hl[6], + al7 = hl[7]; - try { - return factory(loc); - } catch (err) { - if (err instanceof SyntaxError) { - throw new (_errors || _load_errors()).MessageError(this.reporter.lang('jsonError', loc, err.message)); - } else { - throw err; - } + var pos = 0; + while (n >= 128) { + for (i = 0; i < 16; i++) { + j = 8 * i + pos; + wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3]; + wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7]; } - } + for (i = 0; i < 80; i++) { + bh0 = ah0; + bh1 = ah1; + bh2 = ah2; + bh3 = ah3; + bh4 = ah4; + bh5 = ah5; + bh6 = ah6; + bh7 = ah7; - static create() { - let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - let reporter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new (_index3 || _load_index3()).NoopReporter(); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const config = new Config(reporter); - yield config.init(opts); - return config; - })(); - } -} -exports.default = Config; + bl0 = al0; + bl1 = al1; + bl2 = al2; + bl3 = al3; + bl4 = al4; + bl5 = al5; + bl6 = al6; + bl7 = al7; -/***/ }), -/* 121 */ -/***/ (function(module, exports, __webpack_require__) { + // add + h = ah7; + l = al7; -"use strict"; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; + // Sigma1 + h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32)))); + l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32)))); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.integrityErrors = undefined; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -var _asyncToGenerator2; + // Ch + h = (ah4 & ah5) ^ (~ah4 & ah6); + l = (al4 & al5) ^ (~al4 & al6); -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -var _constants; + // K + h = K[i*2]; + l = K[i*2+1]; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -var _index; + // w + h = wh[i%16]; + l = wl[i%16]; -function _load_index() { - return _index = __webpack_require__(24); -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -var _fs; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + th = c & 0xffff | d << 16; + tl = a & 0xffff | b << 16; -var _misc; + // add + h = th; + l = tl; -function _load_misc() { - return _misc = __webpack_require__(10); -} + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -var _workspaceLayout; + // Sigma0 + h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32)))); + l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32)))); -function _load_workspaceLayout() { - return _workspaceLayout = _interopRequireDefault(__webpack_require__(66)); -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + // Maj + h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); + l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -const invariant = __webpack_require__(5); -const path = __webpack_require__(1); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -const integrityErrors = exports.integrityErrors = { - EXPECTED_IS_NOT_A_JSON: 'integrityFailedExpectedIsNotAJSON', - FILES_MISSING: 'integrityFailedFilesMissing', - LOCKFILE_DONT_MATCH: 'integrityLockfilesDontMatch', - FLAGS_DONT_MATCH: 'integrityFlagsDontMatch', - LINKED_MODULES_DONT_MATCH: 'integrityCheckLinkedModulesDontMatch' -}; + bh7 = (c & 0xffff) | (d << 16); + bl7 = (a & 0xffff) | (b << 16); -/** - * - */ -class InstallationIntegrityChecker { - constructor(config) { - this.config = config; - } + // add + h = bh3; + l = bl3; - _getModuleLocation(usedRegistries) { - var _this = this; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // build up possible folders - let registries = (_index || _load_index()).registryNames; - if (usedRegistries && usedRegistries.size > 0) { - registries = usedRegistries; - } - const possibleFolders = []; - if (_this.config.modulesFolder) { - possibleFolders.push(_this.config.modulesFolder); - } + h = th; + l = tl; - // ensure we only write to a registry folder that was used - for (const name of registries) { - const loc = path.join(_this.config.cwd, _this.config.registries[name].folder); - possibleFolders.push(loc); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - // if we already have an integrity hash in one of these folders then use it's location otherwise use the - // first folder - let loc; - for (const possibleLoc of possibleFolders) { - if (yield (_fs || _load_fs()).exists(path.join(possibleLoc, (_constants || _load_constants()).INTEGRITY_FILENAME))) { - loc = possibleLoc; - break; - } - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - return loc || possibleFolders[0]; - })(); - } + bh3 = (c & 0xffff) | (d << 16); + bl3 = (a & 0xffff) | (b << 16); - /** - * Get the location of an existing integrity hash. If none exists then return the location where we should - * write a new one. - */ + ah1 = bh0; + ah2 = bh1; + ah3 = bh2; + ah4 = bh3; + ah5 = bh4; + ah6 = bh5; + ah7 = bh6; + ah0 = bh7; - _getIntegrityHashLocation(usedRegistries) { - var _this2 = this; + al1 = bl0; + al2 = bl1; + al3 = bl2; + al4 = bl3; + al5 = bl4; + al6 = bl5; + al7 = bl6; + al0 = bl7; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let locationFolder; + if (i%16 === 15) { + for (j = 0; j < 16; j++) { + // add + h = wh[j]; + l = wl[j]; - if (_this2.config.enableMetaFolder) { - locationFolder = path.join(_this2.config.lockfileFolder, (_constants || _load_constants()).META_FOLDER); - } else { - locationFolder = yield _this2._getModuleLocation(usedRegistries); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - const locationPath = path.join(locationFolder, (_constants || _load_constants()).INTEGRITY_FILENAME); - const exists = yield (_fs || _load_fs()).exists(locationPath); + h = wh[(j+9)%16]; + l = wl[(j+9)%16]; - return { - locationFolder, - locationPath, - exists - }; - })(); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * returns a list of files recursively in a directory sorted - */ - _getFilesDeep(rootDir) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let getFilePaths = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (rootDir, files) { - let currentDir = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : rootDir; + // sigma0 + th = wh[(j+1)%16]; + tl = wl[(j+1)%16]; + h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7); + l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7))); - for (const file of yield (_fs || _load_fs()).readdir(currentDir)) { - const entry = path.join(currentDir, file); - const stat = yield (_fs || _load_fs()).stat(entry); - if (stat.isDirectory()) { - yield getFilePaths(rootDir, files, entry); - } else { - files.push(path.relative(rootDir, entry)); - } - } - }); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - return function getFilePaths(_x, _x2) { - return _ref.apply(this, arguments); - }; - })(); + // sigma1 + th = wh[(j+14)%16]; + tl = wl[(j+14)%16]; + h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6); + l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6))); - const result = []; - yield getFilePaths(rootDir, result); - return result; - })(); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Generate integrity hash of input lockfile. - */ + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - _generateIntegrityFile(lockfile, patterns, flags, modulesFolder, artifacts) { - var _this3 = this; + wh[j] = (c & 0xffff) | (d << 16); + wl[j] = (a & 0xffff) | (b << 16); + } + } + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const result = { - flags: [], - linkedModules: [], - topLevelPatters: [], - lockfileEntries: {}, - files: [], - artifacts - }; + // add + h = ah0; + l = al0; - result.topLevelPatters = patterns.sort((_misc || _load_misc()).sortAlpha); + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - if (flags.flat) { - result.flags.push('flat'); - } - if (flags.ignoreScripts) { - result.flags.push('ignoreScripts'); - } + h = hh[0]; + l = hl[0]; - if (_this3.config.production) { - result.flags.push('production'); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const linkedModules = _this3.config.linkedModules; - if (linkedModules.length) { - result.linkedModules = linkedModules.sort((_misc || _load_misc()).sortAlpha); - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - Object.keys(lockfile).forEach(function (key) { - result.lockfileEntries[key] = lockfile[key].resolved; - }); + hh[0] = ah0 = (c & 0xffff) | (d << 16); + hl[0] = al0 = (a & 0xffff) | (b << 16); - if (flags.checkFiles) { - result.files = yield _this3._getFilesDeep(modulesFolder); - } + h = ah1; + l = al1; - return result; - })(); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - _getIntegrityFile(locationPath) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const expectedRaw = yield (_fs || _load_fs()).readFile(locationPath); - try { - return JSON.parse(expectedRaw); - } catch (e) { - // ignore JSON parsing for legacy text integrity files compatibility - } - return null; - })(); - } + h = hh[1]; + l = hl[1]; - _compareIntegrityFiles(actual, expected, checkFiles, locationFolder) { - var _this4 = this; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (!expected) { - return 'EXPECTED_IS_NOT_A_JSON'; - } - if (!(0, (_misc || _load_misc()).compareSortedArrays)(actual.linkedModules, expected.linkedModules)) { - return 'LINKED_MODULES_DONT_MATCH'; - } - if (!(0, (_misc || _load_misc()).compareSortedArrays)(actual.flags, expected.flags)) { - return 'FLAGS_DONT_MATCH'; - } - for (const key of Object.keys(actual.lockfileEntries)) { - if (actual.lockfileEntries[key] !== expected.lockfileEntries[key]) { - return 'LOCKFILE_DONT_MATCH'; - } - } - for (const key of Object.keys(expected.lockfileEntries)) { - if (actual.lockfileEntries[key] !== expected.lockfileEntries[key]) { - return 'LOCKFILE_DONT_MATCH'; - } - } - if (checkFiles) { - if (expected.files.length === 0) { - // edge case handling - --check-fies is passed but .yarn-integrity does not contain any files - // check and fail if there are file in node_modules after all. - const actualFiles = yield _this4._getFilesDeep(locationFolder); - if (actualFiles.length > 0) { - return 'FILES_MISSING'; - } - } else { - // TODO we may want to optimise this check by checking only for package.json files on very large trees - for (const file of expected.files) { - if (!(yield (_fs || _load_fs()).exists(path.join(locationFolder, file)))) { - return 'FILES_MISSING'; - } - } - } - } - return 'OK'; - })(); - } + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - check(patterns, lockfile, flags, workspaceLayout) { - var _this5 = this; + hh[1] = ah1 = (c & 0xffff) | (d << 16); + hl[1] = al1 = (a & 0xffff) | (b << 16); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // check if patterns exist in lockfile - const missingPatterns = patterns.filter(function (p) { - return !lockfile[p] && (!workspaceLayout || !workspaceLayout.getManifestByPattern(p)); - }); + h = ah2; + l = al2; - const loc = yield _this5._getIntegrityHashLocation(); - if (missingPatterns.length || !loc.exists) { - return { - integrityFileMissing: !loc.exists, - missingPatterns - }; - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - const actual = yield _this5._generateIntegrityFile(lockfile, patterns, Object.assign({}, flags, { checkFiles: false }), ( // don't generate files when checking, we check the files below - yield _this5._getModuleLocation())); - const expected = yield _this5._getIntegrityFile(loc.locationPath); - const integrityMatches = yield _this5._compareIntegrityFiles(actual, expected, flags.checkFiles, loc.locationFolder); + h = hh[2]; + l = hl[2]; - return { - integrityFileMissing: false, - integrityMatches: integrityMatches === 'OK', - integrityError: integrityMatches === 'OK' ? undefined : integrityMatches, - missingPatterns - }; - })(); - } + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - /** - * Get artifacts from integrity file if it exists. - */ - getArtifacts() { - var _this6 = this; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const loc = yield _this6._getIntegrityHashLocation(); - if (!loc.exists) { - return null; - } + hh[2] = ah2 = (c & 0xffff) | (d << 16); + hl[2] = al2 = (a & 0xffff) | (b << 16); - const expectedRaw = yield (_fs || _load_fs()).readFile(loc.locationPath); - let expected; - try { - expected = JSON.parse(expectedRaw); - } catch (e) { - // ignore JSON parsing for legacy text integrity files compatibility - } + h = ah3; + l = al3; - return expected ? expected.artifacts : null; - })(); - } + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; - /** - * Write the integrity hash of the current install to disk. - */ - save(patterns, lockfile, flags, usedRegistries, artifacts) { - var _this7 = this; + h = hh[3]; + l = hl[3]; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const moduleFolder = yield _this7._getModuleLocation(usedRegistries); - const integrityFile = yield _this7._generateIntegrityFile(lockfile, patterns, flags, moduleFolder, artifacts); + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; - const loc = yield _this7._getIntegrityHashLocation(usedRegistries); - invariant(loc.locationPath, 'expected integrity hash location'); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - yield (_fs || _load_fs()).mkdirp(path.dirname(loc.locationPath)); - yield (_fs || _load_fs()).writeFile(loc.locationPath, JSON.stringify(integrityFile, null, 2)); - })(); - } + hh[3] = ah3 = (c & 0xffff) | (d << 16); + hl[3] = al3 = (a & 0xffff) | (b << 16); - removeIntegrityFile() { - var _this8 = this; + h = ah4; + l = al4; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const loc = yield _this8._getIntegrityHashLocation(); - if (loc.exists) { - yield (_fs || _load_fs()).unlink(loc.locationPath); - } - })(); - } -} -exports.default = InstallationIntegrityChecker; + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -/***/ }), -/* 122 */ -/***/ (function(module, exports, __webpack_require__) { + h = hh[4]; + l = hl[4]; -"use strict"; + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.linkBin = undefined; + hh[4] = ah4 = (c & 0xffff) | (d << 16); + hl[4] = al4 = (a & 0xffff) | (b << 16); -var _slicedToArray2; + h = ah5; + l = al5; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -var _asyncToGenerator2; + h = hh[5]; + l = hl[5]; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -let linkBin = exports.linkBin = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { - if (process.platform === 'win32') { - const unlockMutex = yield (0, (_mutex || _load_mutex()).default)(src); - try { - yield cmdShim(src, dest); - } finally { - unlockMutex(); - } - } else { - yield (_fs || _load_fs()).mkdirp(path.dirname(dest)); - yield (_fs || _load_fs()).symlink(src, dest); - yield (_fs || _load_fs()).chmod(dest, '755'); - } - }); + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; - return function linkBin(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); + hh[5] = ah5 = (c & 0xffff) | (d << 16); + hl[5] = al5 = (a & 0xffff) | (b << 16); -var _packageHoister; + h = ah6; + l = al6; -function _load_packageHoister() { - return _packageHoister = _interopRequireDefault(__webpack_require__(360)); -} + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -var _constants; + h = hh[6]; + l = hl[6]; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -var _promise; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -function _load_promise() { - return _promise = _interopRequireWildcard(__webpack_require__(64)); -} + hh[6] = ah6 = (c & 0xffff) | (d << 16); + hl[6] = al6 = (a & 0xffff) | (b << 16); -var _misc; + h = ah7; + l = al7; -function _load_misc() { - return _misc = __webpack_require__(10); -} + a = l & 0xffff; b = l >>> 16; + c = h & 0xffff; d = h >>> 16; -var _fs; + h = hh[7]; + l = hl[7]; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + a += l & 0xffff; b += l >>> 16; + c += h & 0xffff; d += h >>> 16; -var _mutex; + b += a >>> 16; + c += b >>> 16; + d += c >>> 16; -function _load_mutex() { - return _mutex = _interopRequireDefault(__webpack_require__(385)); -} + hh[7] = ah7 = (c & 0xffff) | (d << 16); + hl[7] = al7 = (a & 0xffff) | (b << 16); -var _semver; + pos += 128; + n -= 128; + } -function _load_semver() { - return _semver = __webpack_require__(393); + return n; } -var _workspaceLayout; - -function _load_workspaceLayout() { - return _workspaceLayout = _interopRequireDefault(__webpack_require__(66)); -} +function crypto_hash(out, m, n) { + var hh = new Int32Array(8), + hl = new Int32Array(8), + x = new Uint8Array(256), + i, b = n; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + hh[0] = 0x6a09e667; + hh[1] = 0xbb67ae85; + hh[2] = 0x3c6ef372; + hh[3] = 0xa54ff53a; + hh[4] = 0x510e527f; + hh[5] = 0x9b05688c; + hh[6] = 0x1f83d9ab; + hh[7] = 0x5be0cd19; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + hl[0] = 0xf3bcc908; + hl[1] = 0x84caa73b; + hl[2] = 0xfe94f82b; + hl[3] = 0x5f1d36f1; + hl[4] = 0xade682d1; + hl[5] = 0x2b3e6c1f; + hl[6] = 0xfb41bd6b; + hl[7] = 0x137e2179; -const invariant = __webpack_require__(5); + crypto_hashblocks_hl(hh, hl, m, n); + n %= 128; -const cmdShim = (_promise || _load_promise()).promisify(__webpack_require__(410)); -const path = __webpack_require__(1); -// Concurrency for creating bin links disabled because of the issue #1961 -const linkBinConcurrency = 1; + for (i = 0; i < n; i++) x[i] = m[b-n+i]; + x[n] = 128; -class PackageLinker { - constructor(config, resolver) { - this.resolver = resolver; - this.reporter = config.reporter; - this.config = config; - this.artifacts = {}; - } + n = 256-128*(n<112?1:0); + x[n-9] = 0; + ts64(x, n-8, (b / 0x20000000) | 0, b << 3); + crypto_hashblocks_hl(hh, hl, x, n); - setArtifacts(artifacts) { - this.artifacts = artifacts; - } + for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]); - linkSelfDependencies(pkg, pkgLoc, targetBinLoc) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - targetBinLoc = path.join(targetBinLoc, '.bin'); - yield (_fs || _load_fs()).mkdirp(targetBinLoc); - targetBinLoc = yield (_fs || _load_fs()).realpath(targetBinLoc); - pkgLoc = yield (_fs || _load_fs()).realpath(pkgLoc); - for (const _ref2 of (0, (_misc || _load_misc()).entries)(pkg.bin)) { - var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2); + return 0; +} - const scriptName = _ref3[0]; - const scriptCmd = _ref3[1]; +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); - const dest = path.join(targetBinLoc, scriptName); - const src = path.join(pkgLoc, scriptCmd); - if (!(yield (_fs || _load_fs()).exists(src))) { - // TODO maybe throw an error - continue; - } - yield linkBin(src, dest); - } - })(); - } + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); - linkBinDependencies(pkg, dir) { - var _this = this; + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const deps = []; +function cswap(p, q, b) { + var i; + for (i = 0; i < 4; i++) { + sel25519(p[i], q[i], b); + } +} - const ref = pkg._reference; - invariant(ref, 'Package reference is missing'); +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} - const remote = pkg._remote; - invariant(remote, 'Package remote is missing'); +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for (i = 255; i >= 0; --i) { + b = (s[(i/8)|0] >> (i&7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} - // link up `bin scripts` in `dependencies` - for (const pattern of ref.dependencies) { - const dep = _this.resolver.getStrictResolvedPattern(pattern); - if (dep.bin && Object.keys(dep.bin).length) { - deps.push({ - dep, - loc: _this.config.generateHardModulePath(dep._reference) - }); - } - } +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} - // link up the `bin` scripts in bundled dependencies - if (pkg.bundleDependencies) { - for (const depName of pkg.bundleDependencies) { - const loc = path.join(_this.config.generateHardModulePath(ref), _this.config.getFolder(pkg), depName); +function crypto_sign_keypair(pk, sk, seeded) { + var d = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()]; + var i; - const dep = yield _this.config.readManifest(loc, remote.registry); + if (!seeded) randombytes(sk, 32); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - if (dep.bin && Object.keys(dep.bin).length) { - deps.push({ dep, loc }); - } - } - } + scalarbase(p, d); + pack(pk, p); - // no deps to link - if (!deps.length) { - return; - } + for (i = 0; i < 32; i++) sk[i+32] = pk[i]; + return 0; +} - // write the executables - for (const _ref4 of deps) { - const dep = _ref4.dep, - loc = _ref4.loc; +var L = new Float64Array([0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); - yield _this.linkSelfDependencies(dep, loc, dir); - } - })(); +function modL(r, x) { + var carry, i, j, k; + for (i = 63; i >= 32; --i) { + carry = 0; + for (j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; } - - getFlatHoistedTree(patterns) { - const hoister = new (_packageHoister || _load_packageHoister()).default(this.config, this.resolver); - hoister.seed(patterns); - return Promise.resolve(hoister.init()); + carry = 0; + for (j = 0; j < 32; j++) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for (j = 0; j < 32; j++) x[j] -= carry * L[j]; + for (i = 0; i < 32; i++) { + x[i+1] += x[i] >> 8; + r[i] = x[i] & 255; } +} - copyModules(patterns, linkDuplicates, workspaceLayout) { - var _this2 = this; +function reduce(r) { + var x = new Float64Array(64), i; + for (i = 0; i < 64; i++) x[i] = r[i]; + for (i = 0; i < 64; i++) r[i] = 0; + modL(r, x); +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let flatTree = yield _this2.getFlatHoistedTree(patterns); +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64); + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; - // sorted tree makes file creation and copying not to interfere with each other - flatTree = flatTree.sort(function (dep1, dep2) { - return dep1[0].localeCompare(dep2[0]); - }); + crypto_hash(d, sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; - // list of artifacts in modules to remove from extraneous removal - const artifactFiles = []; + var smlen = n + 64; + for (i = 0; i < n; i++) sm[64 + i] = m[i]; + for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i]; - const copyQueue = new Map(); - const hardlinkQueue = new Map(); - const hardlinksEnabled = linkDuplicates && (yield (_fs || _load_fs()).hardlinksWork(_this2.config.cwd)); + crypto_hash(r, sm.subarray(32), n+32); + reduce(r); + scalarbase(p, r); + pack(sm, p); - const copiedSrcs = new Map(); - const symlinkPaths = new Map(); - for (const _ref5 of flatTree) { - var _ref6 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref5, 2); + for (i = 32; i < 64; i++) sm[i] = sk[i]; + crypto_hash(h, sm, n + 64); + reduce(h); - const folder = _ref6[0]; - var _ref6$ = _ref6[1]; - const pkg = _ref6$.pkg; - const loc = _ref6$.loc; + for (i = 0; i < 64; i++) x[i] = 0; + for (i = 0; i < 32; i++) x[i] = r[i]; + for (i = 0; i < 32; i++) { + for (j = 0; j < 32; j++) { + x[i+j] += h[i] * d[j]; + } + } - const remote = pkg._remote || { type: '' }; - const ref = pkg._reference; - let dest = folder; - invariant(ref, 'expected package reference'); + modL(sm.subarray(32), x); + return smlen; +} - let src = loc; - let type = ''; - if (remote.type === 'link') { - // replace package source from incorrect cache location (workspaces and link: are not cached) - // with a symlink source - src = remote.reference; - type = 'symlink'; - } else if (workspaceLayout && remote.type === 'workspace') { - src = remote.reference; - type = 'symlink'; - if (dest.indexOf(workspaceLayout.virtualManifestName) !== -1) { - // we don't need to install virtual manifest - continue; - } - // to get real path for non hoisted dependencies - symlinkPaths.set(dest, src); - } else { - // backwards compatibility: get build artifacts from metadata - // does not apply to symlinked dependencies - const metadata = yield _this2.config.readPackageMetadata(src); - for (const file of metadata.artifacts) { - artifactFiles.push(path.join(dest, file)); - } - } +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); - for (const _ref7 of symlinkPaths.entries()) { - var _ref8 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref7, 2); + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); - const symlink = _ref8[0]; - const realpath = _ref8[1]; + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); - if (dest.indexOf(symlink + path.sep) === 0) { - // after hoisting we end up with this structure - // root/node_modules/workspace-package(symlink)/node_modules/package-a - // fs.copy operations can't copy files through a symlink, so all the paths under workspace-package - // need to be replaced with a real path, except for the symlink root/node_modules/workspace-package - dest = dest.replace(symlink, realpath); - } - } + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); - ref.setLocation(dest); + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) M(r[0], r[0], I); - const integrityArtifacts = _this2.artifacts[`${pkg.name}@${pkg.version}`]; - if (integrityArtifacts) { - for (const file of integrityArtifacts) { - artifactFiles.push(path.join(dest, file)); - } - } + S(chk, r[0]); + M(chk, chk, den); + if (neq25519(chk, num)) return -1; - const copiedDest = copiedSrcs.get(src); - if (!copiedDest) { - if (hardlinksEnabled) { - copiedSrcs.set(src, dest); - } - copyQueue.set(dest, { - src, - dest, - type, - onFresh() { - if (ref) { - ref.setFresh(true); - } - } - }); - } else { - hardlinkQueue.set(dest, { - src: copiedDest, - dest, - onFresh() { - if (ref) { - ref.setFresh(true); - } - } - }); - } - } + if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]); - // keep track of all scoped paths to remove empty scopes after copy - const scopedPaths = new Set(); + M(r[3], r[0], r[1]); + return 0; +} - // register root & scoped packages as being possibly extraneous - const possibleExtraneous = new Set(); - for (const folder of _this2.config.registryFolders) { - const loc = path.join(_this2.config.cwd, folder); +function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new Uint8Array(32), h = new Uint8Array(64); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; - if (yield (_fs || _load_fs()).exists(loc)) { - const files = yield (_fs || _load_fs()).readdir(loc); - let filepath; - for (const file of files) { - filepath = path.join(loc, file); - if (file[0] === '@') { - // it's a scope, not a package - scopedPaths.add(filepath); - const subfiles = yield (_fs || _load_fs()).readdir(filepath); - for (const subfile of subfiles) { - possibleExtraneous.add(path.join(filepath, subfile)); - } - } else { - possibleExtraneous.add(filepath); - } - } - } - } + mlen = -1; + if (n < 64) return -1; - // linked modules - for (const loc of possibleExtraneous) { - const stat = yield (_fs || _load_fs()).lstat(loc); - if (stat.isSymbolicLink()) { - possibleExtraneous.delete(loc); - copyQueue.delete(loc); - } - } + if (unpackneg(q, pk)) return -1; - // - let tick; - yield (_fs || _load_fs()).copyBulk(Array.from(copyQueue.values()), _this2.reporter, { - possibleExtraneous, - artifactFiles, + for (i = 0; i < n; i++) m[i] = sm[i]; + for (i = 0; i < 32; i++) m[i+32] = pk[i]; + crypto_hash(h, m, n); + reduce(h); + scalarmult(p, q, h); - ignoreBasenames: [(_constants || _load_constants()).METADATA_FILENAME, (_constants || _load_constants()).TARBALL_FILENAME], + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); - onStart: function (num) { - tick = _this2.reporter.progress(num); - }, - - onProgress(src) { - if (tick) { - tick(); - } - } - }); - yield (_fs || _load_fs()).hardlinkBulk(Array.from(hardlinkQueue.values()), _this2.reporter, { - possibleExtraneous, - artifactFiles, - - onStart: function (num) { - tick = _this2.reporter.progress(num); - }, - - onProgress(src) { - if (tick) { - tick(); - } - } - }); - - // remove all extraneous files that weren't in the tree - for (const loc of possibleExtraneous) { - _this2.reporter.verbose(_this2.reporter.lang('verboseFileRemoveExtraneous', loc)); - yield (_fs || _load_fs()).unlink(loc); - } - - // remove any empty scoped directories - for (const scopedPath of scopedPaths) { - const files = yield (_fs || _load_fs()).readdir(scopedPath); - if (files.length === 0) { - yield (_fs || _load_fs()).unlink(scopedPath); - } - } - - // create binary links - if (_this2.config.binLinks) { - const topLevelDependencies = _this2.determineTopLevelBinLinks(flatTree); - const tickBin = _this2.reporter.progress(flatTree.length + topLevelDependencies.length); - - // create links in transient dependencies - yield (_promise || _load_promise()).queue(flatTree, (() => { - var _ref9 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref10) { - var _ref11 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref10, 2); - - let dest = _ref11[0], - pkg = _ref11[1].pkg; - - const binLoc = path.join(dest, _this2.config.getFolder(pkg)); - yield _this2.linkBinDependencies(pkg, binLoc); - tickBin(); - }); - - return function (_x3) { - return _ref9.apply(this, arguments); - }; - })(), linkBinConcurrency); - - // create links at top level for all dependencies. - // non-transient dependencies will overwrite these during this.save() to ensure they take priority. - yield (_promise || _load_promise()).queue(topLevelDependencies, (() => { - var _ref12 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref13) { - var _ref14 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref13, 2); - - let dest = _ref14[0], - pkg = _ref14[1].pkg; - - if (pkg.bin && Object.keys(pkg.bin).length) { - const binLoc = path.join(_this2.config.cwd, _this2.config.getFolder(pkg)); - yield _this2.linkSelfDependencies(pkg, dest, binLoc); - tickBin(); - } - }); - - return function (_x4) { - return _ref12.apply(this, arguments); - }; - })(), linkBinConcurrency); - } - })(); - } - - determineTopLevelBinLinks(flatTree) { - const linksToCreate = new Map(); - - flatTree.forEach((_ref15) => { - var _ref16 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref15, 2); - - let dest = _ref16[0], - hoistManifest = _ref16[1]; - - if (!linksToCreate.has(hoistManifest.pkg.name)) { - linksToCreate.set(hoistManifest.pkg.name, [dest, hoistManifest]); - } - }); - - return Array.from(linksToCreate.values()); - } - - resolvePeerModules() { - for (const pkg of this.resolver.getManifests()) { - this._resolvePeerModules(pkg); - } + n -= 64; + if (crypto_verify_32(sm, 0, t, 0)) { + for (i = 0; i < n; i++) m[i] = 0; + return -1; } - _resolvePeerModules(pkg) { - const peerDeps = pkg.peerDependencies; - if (!peerDeps) { - return; - } + for (i = 0; i < n; i++) m[i] = sm[i + 64]; + mlen = n; + return mlen; +} - const ref = pkg._reference; - invariant(ref, 'Package reference is missing'); +var crypto_secretbox_KEYBYTES = 32, + crypto_secretbox_NONCEBYTES = 24, + crypto_secretbox_ZEROBYTES = 32, + crypto_secretbox_BOXZEROBYTES = 16, + crypto_scalarmult_BYTES = 32, + crypto_scalarmult_SCALARBYTES = 32, + crypto_box_PUBLICKEYBYTES = 32, + crypto_box_SECRETKEYBYTES = 32, + crypto_box_BEFORENMBYTES = 32, + crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, + crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, + crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, + crypto_sign_BYTES = 64, + crypto_sign_PUBLICKEYBYTES = 32, + crypto_sign_SECRETKEYBYTES = 64, + crypto_sign_SEEDBYTES = 32, + crypto_hash_BYTES = 64; - for (const name in peerDeps) { - const range = peerDeps[name]; - const patterns = this.resolver.patternsByPackage[name] || []; - const foundPattern = patterns.find(pattern => { - const resolvedPattern = this.resolver.getResolvedPattern(pattern); - return resolvedPattern ? this._satisfiesPeerDependency(range, resolvedPattern.version) : false; - }); +nacl.lowlevel = { + crypto_core_hsalsa20: crypto_core_hsalsa20, + crypto_stream_xor: crypto_stream_xor, + crypto_stream: crypto_stream, + crypto_stream_salsa20_xor: crypto_stream_salsa20_xor, + crypto_stream_salsa20: crypto_stream_salsa20, + crypto_onetimeauth: crypto_onetimeauth, + crypto_onetimeauth_verify: crypto_onetimeauth_verify, + crypto_verify_16: crypto_verify_16, + crypto_verify_32: crypto_verify_32, + crypto_secretbox: crypto_secretbox, + crypto_secretbox_open: crypto_secretbox_open, + crypto_scalarmult: crypto_scalarmult, + crypto_scalarmult_base: crypto_scalarmult_base, + crypto_box_beforenm: crypto_box_beforenm, + crypto_box_afternm: crypto_box_afternm, + crypto_box: crypto_box, + crypto_box_open: crypto_box_open, + crypto_box_keypair: crypto_box_keypair, + crypto_hash: crypto_hash, + crypto_sign: crypto_sign, + crypto_sign_keypair: crypto_sign_keypair, + crypto_sign_open: crypto_sign_open, - if (foundPattern) { - ref.addDependencies([foundPattern]); - } else { - const depError = patterns.length > 0 ? 'incorrectPeer' : 'unmetPeer'; - const pkgHuman = `${pkg.name}@${pkg.version}`, - depHuman = `${name}@${range}`; + crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES, + crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES, + crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES, + crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES, + crypto_scalarmult_BYTES: crypto_scalarmult_BYTES, + crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES, + crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES, + crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES, + crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES, + crypto_box_NONCEBYTES: crypto_box_NONCEBYTES, + crypto_box_ZEROBYTES: crypto_box_ZEROBYTES, + crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES, + crypto_sign_BYTES: crypto_sign_BYTES, + crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES, + crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES, + crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES, + crypto_hash_BYTES: crypto_hash_BYTES +}; - this.reporter.warn(this.reporter.lang(depError, pkgHuman, depHuman)); - } - } - } +/* High-level API */ - _satisfiesPeerDependency(range, version) { - return range === '*' || (0, (_semver || _load_semver()).satisfiesWithPreleases)(version, range, this.config.looseSemver); - } +function checkLengths(k, n) { + if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size'); + if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size'); +} - init(patterns, linkDuplicates, workspaceLayout) { - var _this3 = this; +function checkBoxLengths(pk, sk) { + if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size'); + if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size'); +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this3.resolvePeerModules(); - yield _this3.copyModules(patterns, linkDuplicates, workspaceLayout); - })(); +function checkArrayTypes() { + var t, i; + for (i = 0; i < arguments.length; i++) { + if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]') + throw new TypeError('unexpected type ' + t + ', use Uint8Array'); } } -exports.default = PackageLinker; -/***/ }), -/* 123 */ -/***/ (function(module, exports, __webpack_require__) { +function cleanup(arr) { + for (var i = 0; i < arr.length; i++) arr[i] = 0; +} -"use strict"; +// TODO: Completely remove this in v0.15. +if (!nacl.util) { + nacl.util = {}; + nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() { + throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js'); + }; +} +nacl.randomBytes = function(n) { + var b = new Uint8Array(n); + randombytes(b, n); + return b; +}; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.clearLine = clearLine; -exports.toStartOfLine = toStartOfLine; -exports.writeOnNthLine = writeOnNthLine; -exports.clearNthLine = clearNthLine; +nacl.secretbox = function(msg, nonce, key) { + checkArrayTypes(msg, nonce, key); + checkLengths(key, nonce); + var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); + var c = new Uint8Array(m.length); + for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i]; + crypto_secretbox(c, m, m.length, nonce, key); + return c.subarray(crypto_secretbox_BOXZEROBYTES); +}; +nacl.secretbox.open = function(box, nonce, key) { + checkArrayTypes(box, nonce, key); + checkLengths(key, nonce); + var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); + var m = new Uint8Array(c.length); + for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i]; + if (c.length < 32) return false; + if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false; + return m.subarray(crypto_secretbox_ZEROBYTES); +}; -const readline = __webpack_require__(115); +nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; +nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; +nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; -var _require = __webpack_require__(15); +nacl.scalarMult = function(n, p) { + checkArrayTypes(n, p); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult(q, n, p); + return q; +}; -const supportsColor = _require.supportsColor; +nacl.scalarMult.base = function(n) { + checkArrayTypes(n); + if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size'); + var q = new Uint8Array(crypto_scalarmult_BYTES); + crypto_scalarmult_base(q, n); + return q; +}; +nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; +nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; -const CLEAR_WHOLE_LINE = 0; -const CLEAR_RIGHT_OF_CURSOR = 1; +nacl.box = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox(msg, nonce, k); +}; -function clearLine(stdout) { - if (!supportsColor) { - return; - } +nacl.box.before = function(publicKey, secretKey) { + checkArrayTypes(publicKey, secretKey); + checkBoxLengths(publicKey, secretKey); + var k = new Uint8Array(crypto_box_BEFORENMBYTES); + crypto_box_beforenm(k, publicKey, secretKey); + return k; +}; - readline.clearLine(stdout, CLEAR_WHOLE_LINE); - readline.cursorTo(stdout, 0); -} +nacl.box.after = nacl.secretbox; -function toStartOfLine(stdout) { - if (!supportsColor) { - return; - } +nacl.box.open = function(msg, nonce, publicKey, secretKey) { + var k = nacl.box.before(publicKey, secretKey); + return nacl.secretbox.open(msg, nonce, k); +}; - readline.cursorTo(stdout, 0); -} +nacl.box.open.after = nacl.secretbox.open; -function writeOnNthLine(stdout, n, msg) { - if (!supportsColor) { - return; - } +nacl.box.keyPair = function() { + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); + crypto_box_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; - if (n == 0) { - readline.cursorTo(stdout, 0); - stdout.write(msg); - readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR); - return; - } - readline.cursorTo(stdout, 0); - readline.moveCursor(stdout, 0, -n); - stdout.write(msg); - readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR); - readline.cursorTo(stdout, 0); - readline.moveCursor(stdout, 0, n); -} +nacl.box.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_box_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); + crypto_scalarmult_base(pk, secretKey); + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; -function clearNthLine(stdout, n) { - if (!supportsColor) { - return; - } +nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; +nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; +nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; +nacl.box.nonceLength = crypto_box_NONCEBYTES; +nacl.box.overheadLength = nacl.secretbox.overheadLength; - if (n == 0) { - clearLine(stdout); - return; - } - readline.cursorTo(stdout, 0); - readline.moveCursor(stdout, 0, -n); - readline.clearLine(stdout, CLEAR_WHOLE_LINE); - readline.moveCursor(stdout, 0, n); -} +nacl.sign = function(msg, secretKey) { + checkArrayTypes(msg, secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length); + crypto_sign(signedMsg, msg, msg.length, secretKey); + return signedMsg; +}; -/***/ }), -/* 124 */ -/***/ (function(module, exports, __webpack_require__) { +nacl.sign.open = function(signedMsg, publicKey) { + if (arguments.length !== 2) + throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?'); + checkArrayTypes(signedMsg, publicKey); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var tmp = new Uint8Array(signedMsg.length); + var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); + if (mlen < 0) return null; + var m = new Uint8Array(mlen); + for (var i = 0; i < m.length; i++) m[i] = tmp[i]; + return m; +}; -"use strict"; +nacl.sign.detached = function(msg, secretKey) { + var signedMsg = nacl.sign(msg, secretKey); + var sig = new Uint8Array(crypto_sign_BYTES); + for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; + return sig; +}; +nacl.sign.detached.verify = function(msg, sig, publicKey) { + checkArrayTypes(msg, sig, publicKey); + if (sig.length !== crypto_sign_BYTES) + throw new Error('bad signature size'); + if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) + throw new Error('bad public key size'); + var sm = new Uint8Array(crypto_sign_BYTES + msg.length); + var m = new Uint8Array(crypto_sign_BYTES + msg.length); + var i; + for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; + for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i]; + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; -Object.defineProperty(exports, "__esModule", { - value: true -}); +nacl.sign.keyPair = function() { + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + crypto_sign_keypair(pk, sk); + return {publicKey: pk, secretKey: sk}; +}; -var _extends2; +nacl.sign.keyPair.fromSecretKey = function(secretKey) { + checkArrayTypes(secretKey); + if (secretKey.length !== crypto_sign_SECRETKEYBYTES) + throw new Error('bad secret key size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i]; + return {publicKey: pk, secretKey: new Uint8Array(secretKey)}; +}; -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(36)); -} +nacl.sign.keyPair.fromSeed = function(seed) { + checkArrayTypes(seed); + if (seed.length !== crypto_sign_SEEDBYTES) + throw new Error('bad seed size'); + var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); + var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); + for (var i = 0; i < 32; i++) sk[i] = seed[i]; + crypto_sign_keypair(pk, sk, true); + return {publicKey: pk, secretKey: sk}; +}; -var _baseReporter; +nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; +nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; +nacl.sign.seedLength = crypto_sign_SEEDBYTES; +nacl.sign.signatureLength = crypto_sign_BYTES; -function _load_baseReporter() { - return _baseReporter = _interopRequireDefault(__webpack_require__(51)); -} +nacl.hash = function(msg) { + checkArrayTypes(msg); + var h = new Uint8Array(crypto_hash_BYTES); + crypto_hash(h, msg, msg.length); + return h; +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +nacl.hash.hashLength = crypto_hash_BYTES; -class JSONReporter extends (_baseReporter || _load_baseReporter()).default { - constructor(opts) { - super(opts); +nacl.verify = function(x, y) { + checkArrayTypes(x, y); + // Zero length arguments are considered not equal. + if (x.length === 0 || y.length === 0) return false; + if (x.length !== y.length) return false; + return (vn(x, 0, y, 0, x.length) === 0) ? true : false; +}; - this._activityId = 0; - this._progressId = 0; - } +nacl.setPRNG = function(fn) { + randombytes = fn; +}; - _dump(type, data, error) { - let stdout = this.stdout; - if (error) { - stdout = this.stderr; +(function() { + // Initialize PRNG if environment provides CSPRNG. + // If not, methods calling randombytes will throw. + var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null; + if (crypto && crypto.getRandomValues) { + // Browsers. + var QUOTA = 65536; + nacl.setPRNG(function(x, n) { + var i, v = new Uint8Array(n); + for (i = 0; i < n; i += QUOTA) { + crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA))); + } + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); + } else if (true) { + // Node.js. + crypto = __webpack_require__(8); + if (crypto && crypto.randomBytes) { + nacl.setPRNG(function(x, n) { + var i, v = crypto.randomBytes(n); + for (i = 0; i < n; i++) x[i] = v[i]; + cleanup(v); + }); } - stdout.write(`${JSON.stringify({ type, data })}\n`); - } - - _verbose(msg) { - this._dump('verbose', msg); - } - - list(type, items, hints) { - this._dump('list', { type, items, hints }); - } - - tree(type, trees) { - this._dump('tree', { type, trees }); - } - - step(current, total, message) { - this._dump('step', { message, current, total }); - } - - inspect(value) { - this._dump('inspect', value); - } - - footer(showPeakMemory) { - this._dump('finished', this.getTotalTime()); } +})(); - log(msg) { - this._dump('log', msg); - } +})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {})); - command(msg) { - this._dump('command', msg); - } - table(head, body) { - this._dump('table', { head, body }); - } +/***/ }), +/* 147 */ +/***/ (function(module, exports) { - success(msg) { - this._dump('success', msg); - } - - error(msg) { - this._dump('error', msg, true); - } - - warn(msg) { - this._dump('warning', msg, true); - } - - info(msg) { - this._dump('info', msg); - } - - activitySet(total, workers) { - if (!this.isTTY || this.noProgress) { - return super.activitySet(total, workers); - } - - const id = this._activityId++; - this._dump('activitySetStart', { id, total, workers }); - - const spinners = []; - for (let i = 0; i < workers; i++) { - let current = 0; - let header = ''; - - spinners.push({ - clear() {}, - setPrefix(_current, _header) { - current = _current; - header = _header; - }, - tick: msg => { - this._dump('activitySetTick', { - id, - header, - current, - worker: i, - message: msg - }); - }, - end() {} - }); - } - - return { - spinners, - end: () => { - this._dump('activitySetEnd', { id }); - } - }; - } - - activity() { - return this._activity({}); - } +module.exports = { + "name": "yarn", + "installationMethod": "unknown", + "version": "1.0.1", + "license": "BSD-2-Clause", + "preferGlobal": true, + "description": "📦🈠Fast, reliable, and secure dependency management.", + "dependencies": { + "babel-eslint": "^7.2.3", + "babel-runtime": "^6.0.0", + "bytes": "^2.4.0", + "camelcase": "^4.0.0", + "chalk": "^1.1.1", + "cmd-shim": "^2.0.1", + "commander": "^2.9.0", + "death": "^1.0.0", + "debug": "^2.2.0", + "detect-indent": "^5.0.0", + "eslint-plugin-jest": "^20.0.3", + "eslint-plugin-jsx-a11y": "^6.0.2", + "eslint-plugin-relay": "0.0.8", + "glob": "^7.1.1", + "gunzip-maybe": "^1.4.0", + "ini": "^1.3.4", + "inquirer": "^3.0.1", + "invariant": "^2.2.0", + "is-builtin-module": "^1.0.0", + "is-ci": "^1.0.10", + "is-webpack-bundle": "^1.0.0", + "leven": "^2.0.0", + "loud-rejection": "^1.2.0", + "micromatch": "^2.3.11", + "mkdirp": "^0.5.1", + "node-emoji": "^1.6.1", + "normalize-url": "^1.9.1", + "object-path": "^0.11.2", + "proper-lockfile": "^2.0.0", + "read": "^1.0.7", + "request": "^2.81.0", + "request-capture-har": "^1.2.2", + "rimraf": "^2.5.0", + "semver": "^5.1.0", + "strip-bom": "^3.0.0", + "tar-fs": "^1.15.1", + "tar-stream": "^1.5.2", + "uuid": "^3.0.1", + "v8-compile-cache": "^1.1.0", + "validate-npm-package-license": "^3.0.1", + "yn": "^2.0.0" + }, + "devDependencies": { + "babel-core": "^6.24.1", + "babel-loader": "^6.2.5", + "babel-plugin-array-includes": "^2.0.3", + "babel-plugin-transform-inline-imports-commonjs": "^1.0.0", + "babel-plugin-transform-runtime": "^6.4.3", + "babel-preset-es2015-node4": "^2.1.0", + "babel-preset-node5": "^10.2.0", + "babel-preset-stage-0": "^6.0.0", + "babylon": "^6.5.0", + "eslint": "^4.3.0", + "eslint-config-fb-strict": "^20.1.0-delta.3", + "eslint-plugin-babel": "^4.0.0", + "eslint-plugin-flowtype": "^2.35.0", + "eslint-plugin-jasmine": "^2.6.2", + "eslint-plugin-prefer-object-spread": "^1.2.1", + "eslint-plugin-prettier": "^2.1.2", + "eslint-plugin-react": "^7.1.0", + "eslint-plugin-yarn-internal": "file:scripts/eslint-rules", + "execa": "^0.7.0", + "flow-bin": "^0.52.0", + "gulp": "^3.9.0", + "gulp-babel": "^6.0.0", + "gulp-if": "^2.0.1", + "gulp-newer": "^1.0.0", + "gulp-plumber": "^1.0.1", + "gulp-sourcemaps": "^2.2.0", + "gulp-util": "^3.0.7", + "gulp-watch": "^4.3.5", + "jest": "20.0.4", + "minimatch": "^3.0.4", + "mock-stdin": "^0.3.0", + "prettier": "^1.5.2", + "temp": "^0.8.3", + "webpack": "^2.1.0-beta.25", + "yargs": "^6.3.0" + }, + "engines": { + "node": ">=4.0.0" + }, + "repository": "yarnpkg/yarn", + "bin": { + "yarn": "./bin/yarn.js", + "yarnpkg": "./bin/yarn.js" + }, + "scripts": { + "build": "gulp build", + "build-bundle": "node ./scripts/build-webpack.js", + "build-chocolatey": "powershell ./scripts/build-chocolatey.ps1", + "build-deb": "./scripts/build-deb.sh", + "build-dist": "bash ./scripts/build-dist.sh", + "build-win-installer": "scripts\\build-windows-installer.bat", + "check-lockfile": "./scripts/check-lockfile.sh", + "lint": "eslint . && flow check", + "prettier": "eslint src __tests__ --fix", + "release-branch": "./scripts/release-branch.sh", + "test": "yarn lint && yarn test-only", + "test-ci": "yarn build && yarn test-only", + "test-only": "node --max_old_space_size=4096 node_modules/jest/bin/jest.js --coverage --verbose", + "watch": "gulp watch" + }, + "jest": { + "collectCoverageFrom": [ + "src/**/*.js" + ], + "testEnvironment": "node", + "modulePathIgnorePatterns": [ + "__tests__/fixtures/" + ], + "testPathIgnorePatterns": [ + "__tests__/(fixtures|__mocks__)/", + "updates/", + "/_(temp|mock|install|init|helpers).js$" + ] + } +}; - _activity(data) { - if (!this.isTTY || this.noProgress) { - return { - tick() {}, - end() {} - }; - } +/***/ }), +/* 148 */ +/***/ (function(module, exports) { - const id = this._activityId++; - this._dump('activityStart', (0, (_extends2 || _load_extends()).default)({ id }, data)); +module.exports = require("child_process"); - return { - tick: name => { - this._dump('activityTick', { id, name }); - }, +/***/ }), +/* 149 */ +/***/ (function(module, exports) { - end: () => { - this._dump('activityEnd', { id }); - } - }; - } +module.exports = require("https"); - progress(total) { - if (this.noProgress) { - return function () { - // noop - }; - } +/***/ }), +/* 150 */ +/***/ (function(module, exports) { - const id = this._progressId++; - let current = 0; - this._dump('progressStart', { id, total }); +module.exports = require("querystring"); - return () => { - current++; - this._dump('progressTick', { id, current }); +/***/ }), +/* 151 */ +/***/ (function(module, exports) { - if (current === total) { - this._dump('progressFinish', { id }); - } - }; - } -} -exports.default = JSONReporter; +module.exports = require("readline"); /***/ }), -/* 125 */ +/* 152 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -46345,74 +47699,133 @@ exports.default = JSONReporter; Object.defineProperty(exports, "__esModule", { value: true }); -exports.explodeGistFragment = explodeGistFragment; +exports.default = stringify; -var _errors; +var _misc; -function _load_errors() { - return _errors = __webpack_require__(3); +function _load_misc() { + return _misc = __webpack_require__(10); } -var _gitResolver; +var _constants; -function _load_gitResolver() { - return _gitResolver = _interopRequireDefault(__webpack_require__(61)); +function _load_constants() { + return _constants = __webpack_require__(6); } -var _exoticResolver; +var _package; -function _load_exoticResolver() { - return _exoticResolver = _interopRequireDefault(__webpack_require__(44)); +function _load_package() { + return _package = __webpack_require__(147); } -var _misc; +const NODE_VERSION = process.version; -function _load_misc() { - return _misc = _interopRequireWildcard(__webpack_require__(10)); +function shouldWrapKey(str) { + return str.indexOf('true') === 0 || str.indexOf('false') === 0 || /[:\s\n\\",\[\]]/g.test(str) || /^[0-9]/g.test(str) || !/^[a-zA-Z]/g.test(str); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function explodeGistFragment(fragment, reporter) { - fragment = (_misc || _load_misc()).removePrefix(fragment, 'gist:'); +function maybeWrap(str) { + if (typeof str === 'boolean' || typeof str === 'number' || shouldWrapKey(str)) { + return JSON.stringify(str); + } else { + return str; + } +} - const parts = fragment.split('#'); +const priorities = { + name: 1, + version: 2, + uid: 3, + resolved: 4, + registry: 5, + dependencies: 6 +}; - if (parts.length <= 2) { - return { - id: parts[0], - hash: parts[1] || '' - }; +function priorityThenAlphaSort(a, b) { + if (priorities[a] || priorities[b]) { + return (priorities[a] || 100) > (priorities[b] || 100) ? 1 : -1; } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidGistFragment', fragment)); + return (0, (_misc || _load_misc()).sortAlpha)(a, b); } } -class GistResolver extends (_exoticResolver || _load_exoticResolver()).default { +function _stringify(obj, options) { + if (typeof obj !== 'object') { + throw new TypeError(); + } - constructor(request, fragment) { - super(request, fragment); + const indent = options.indent; + const lines = []; - var _explodeGistFragment = explodeGistFragment(fragment, this.reporter); + // Sorting order needs to be consistent between runs, we run native sort by name because there are no + // problems with it being unstable because there are no to keys the same + // However priorities can be duplicated and native sort can shuffle things from run to run + const keys = Object.keys(obj).sort(priorityThenAlphaSort); - const id = _explodeGistFragment.id, - hash = _explodeGistFragment.hash; + let addedKeys = []; - this.id = id; - this.hash = hash; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const val = obj[key]; + if (val == null || addedKeys.indexOf(key) >= 0) { + continue; + } + + // + const valKeys = [key]; + + // get all keys that have the same value equality, we only want this for objects + if (typeof val === 'object') { + for (let j = i + 1; j < keys.length; j++) { + const key = keys[j]; + if (val === obj[key]) { + valKeys.push(key); + } + } + } + + // + const keyLine = valKeys.sort((_misc || _load_misc()).sortAlpha).map(maybeWrap).join(', '); + + if (typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number') { + lines.push(`${keyLine} ${maybeWrap(val)}`); + } else if (typeof val === 'object') { + lines.push(`${keyLine}:\n${_stringify(val, { indent: indent + ' ' })}` + (options.topLevel ? '\n' : '')); + } else { + throw new TypeError(); + } + + addedKeys = addedKeys.concat(valKeys); } - resolve() { - return this.fork((_gitResolver || _load_gitResolver()).default, false, `https://gist.github.com/${this.id}.git#${this.hash}`); + return indent + lines.join(`\n${indent}`); +} + +function stringify(obj, noHeader, enableVersions) { + const val = _stringify(obj, { + indent: '', + topLevel: true + }); + if (noHeader) { + return val; + } + + const lines = []; + lines.push('# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.'); + lines.push(`# yarn lockfile v${(_constants || _load_constants()).LOCKFILE_VERSION}`); + if (enableVersions) { + lines.push(`# yarn v${(_package || _load_package()).version}`); + lines.push(`# node ${NODE_VERSION}`); } + lines.push('\n'); + lines.push(val); + + return lines.join('\n'); } -exports.default = GistResolver; -GistResolver.protocol = 'gist'; /***/ }), -/* 126 */ +/* 153 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -46422,246 +47835,364 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _asyncToGenerator2; +var _consoleReporter; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function _load_consoleReporter() { + return _consoleReporter = __webpack_require__(421); } -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); -} +Object.defineProperty(exports, 'ConsoleReporter', { + enumerable: true, + get: function () { + return _interopRequireDefault(_consoleReporter || _load_consoleReporter()).default; + } +}); -var _registryResolver; +var _bufferReporter; -function _load_registryResolver() { - return _registryResolver = _interopRequireDefault(__webpack_require__(382)); +function _load_bufferReporter() { + return _bufferReporter = __webpack_require__(420); } -var _npmRegistry; - -function _load_npmRegistry() { - return _npmRegistry = _interopRequireDefault(__webpack_require__(43)); -} +Object.defineProperty(exports, 'BufferReporter', { + enumerable: true, + get: function () { + return _interopRequireDefault(_bufferReporter || _load_bufferReporter()).default; + } +}); -var _map; +var _eventReporter; -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); +function _load_eventReporter() { + return _eventReporter = __webpack_require__(425); } -var _fs; - -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} +Object.defineProperty(exports, 'EventReporter', { + enumerable: true, + get: function () { + return _interopRequireDefault(_eventReporter || _load_eventReporter()).default; + } +}); -var _constants; +var _jsonReporter; -function _load_constants() { - return _constants = __webpack_require__(8); +function _load_jsonReporter() { + return _jsonReporter = __webpack_require__(161); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const inquirer = __webpack_require__(152); +Object.defineProperty(exports, 'JSONReporter', { + enumerable: true, + get: function () { + return _interopRequireDefault(_jsonReporter || _load_jsonReporter()).default; + } +}); -const tty = __webpack_require__(116); -const invariant = __webpack_require__(5); -const path = __webpack_require__(1); +var _noopReporter; -const NPM_REGISTRY = /http[s]:\/\/registry.npmjs.org/g; +function _load_noopReporter() { + return _noopReporter = __webpack_require__(427); +} -class NpmResolver extends (_registryResolver || _load_registryResolver()).default { +Object.defineProperty(exports, 'NoopReporter', { + enumerable: true, + get: function () { + return _interopRequireDefault(_noopReporter || _load_noopReporter()).default; + } +}); - static findVersionInRegistryResponse(config, range, body, request) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (!body['dist-tags']) { - throw new (_errors || _load_errors()).MessageError(config.reporter.lang('malformedRegistryResponse', body.name)); - } +var _baseReporter; - if (range in body['dist-tags']) { - range = body['dist-tags'][range]; - } +function _load_baseReporter() { + return _baseReporter = __webpack_require__(77); +} - const satisfied = yield config.resolveConstraints(Object.keys(body.versions), range); - if (satisfied) { - return body.versions[satisfied]; - } else if (request && !config.nonInteractive) { - if (request.resolver && request.resolver.activity) { - request.resolver.activity.end(); - } - config.reporter.log(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range)); - let pageSize; - if (process.stdout instanceof tty.WriteStream) { - pageSize = process.stdout.rows - 2; - } - const response = yield inquirer.prompt([{ - name: 'package', - type: 'list', - message: config.reporter.lang('chooseVersionFromList', body.name), - choices: Object.keys(body.versions).reverse(), - pageSize - }]); - if (response && response.package) { - return body.versions[response.package]; - } - } - throw new (_errors || _load_errors()).MessageError(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range)); - })(); +Object.defineProperty(exports, 'Reporter', { + enumerable: true, + get: function () { + return _interopRequireDefault(_baseReporter || _load_baseReporter()).default; } +}); - resolveRequest() { - var _this = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (_this.config.offline) { - const res = yield _this.resolveRequestOffline(); - if (res != null) { - return res; - } - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - const body = yield _this.config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(_this.name)); +/***/ }), +/* 154 */ +/***/ (function(module, exports) { - if (body) { - return NpmResolver.findVersionInRegistryResponse(_this.config, _this.range, body, _this.request); - } else { - return null; - } - })(); - } +// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. - resolveRequestOffline() { - var _this2 = this; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const scope = _this2.config.registries.npm.getScope(_this2.name); - // find modules of this name - const prefix = scope ? _this2.name.split(/\/|%2f/)[1] : `npm-${_this2.name}-`; +module.exports = { - invariant(_this2.config.cacheFolder, 'expected packages root'); - const cacheFolder = path.join(_this2.config.cacheFolder, scope ? 'npm-' + scope : ''); + newInvalidAsn1Error: function(msg) { + var e = new Error(); + e.name = 'InvalidAsn1Error'; + e.message = msg || ''; + return e; + } - const files = yield _this2.config.getCache('cachedPackages', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const files = yield (_fs || _load_fs()).readdir(cacheFolder); - const validFiles = []; +}; - for (const name of files) { - // no hidden files - if (name[0] === '.') { - continue; - } - // ensure valid module cache - const dir = path.join(cacheFolder, name); - if (yield _this2.config.isValidModuleDest(dir)) { - validFiles.push(name); - } - } +/***/ }), +/* 155 */ +/***/ (function(module, exports) { - return validFiles; - })); +// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. - const versions = (0, (_map || _load_map()).default)(); - for (const name of files) { - // check if folder starts with our prefix - if (name.indexOf(prefix) !== 0) { - continue; - } +module.exports = { + EOC: 0, + Boolean: 1, + Integer: 2, + BitString: 3, + OctetString: 4, + Null: 5, + OID: 6, + ObjectDescriptor: 7, + External: 8, + Real: 9, // float + Enumeration: 10, + PDV: 11, + Utf8String: 12, + RelativeOID: 13, + Sequence: 16, + Set: 17, + NumericString: 18, + PrintableString: 19, + T61String: 20, + VideotexString: 21, + IA5String: 22, + UTCTime: 23, + GeneralizedTime: 24, + GraphicString: 25, + VisibleString: 26, + GeneralString: 28, + UniversalString: 29, + CharacterString: 30, + BMPString: 31, + Constructor: 32, + Context: 128 +}; - const dir = path.join(cacheFolder, name); - // read manifest and validate correct name - const pkg = yield _this2.config.readManifest(dir, 'npm'); - if (pkg.name !== _this2.name) { - continue; - } +/***/ }), +/* 156 */ +/***/ (function(module, exports, __webpack_require__) { - // read package metadata - const metadata = yield _this2.config.readPackageMetadata(dir); - if (!metadata.remote) { - continue; // old yarn metadata - } +"use strict"; - versions[pkg.version] = Object.assign({}, pkg, { - _remote: metadata.remote - }); - } - const satisfied = yield _this2.config.resolveConstraints(Object.keys(versions), _this2.range); - if (satisfied) { - return versions[satisfied]; - } else if (!_this2.config.preferOffline) { - throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('couldntFindPackageInCache', _this2.name, _this2.range, Object.keys(versions).join(', '))); - } else { - return null; - } - })(); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.pack = exports.packTarball = undefined; - cleanRegistry(url) { - if (this.config.getOption('registry') === (_constants || _load_constants()).YARN_REGISTRY) { - return url.replace(NPM_REGISTRY, (_constants || _load_constants()).YARN_REGISTRY); - } else { - return url; +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} + +let packTarball = exports.packTarball = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config) { + var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let mapHeader = _ref2.mapHeader; + + const pkg = yield config.readRootManifest(); + const bundledDependencies = pkg.bundledDependencies, + main = pkg.main, + onlyFiles = pkg.files; + + // include required files + + let filters = NEVER_IGNORE.slice(); + // include default filters unless `files` is used + if (!onlyFiles) { + filters = filters.concat(DEFAULT_IGNORE); + } + if (main) { + filters = filters.concat((0, (_filter || _load_filter()).ignoreLinesToRegex)(['!/' + main])); } - } - resolve() { - var _this3 = this; + // include bundledDependencies + if (bundledDependencies) { + const folder = config.getFolder(pkg); + filters = (0, (_filter || _load_filter()).ignoreLinesToRegex)(bundledDependencies.map(function (name) { + return `!${folder}/${name}`; + }), '.'); + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // lockfile - const shrunk = _this3.request.getLocked('tarball'); - if (shrunk) { - return shrunk; - } + // `files` field + if (onlyFiles) { + let lines = ['*', // ignore all files except those that are explicitly included with a negation filter + '.*']; + lines = lines.concat(onlyFiles.map(function (filename) { + return `!${filename}`; + }), onlyFiles.map(function (filename) { + return `!${path.join(filename, '**')}`; + })); + const regexes = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines, '.'); + filters = filters.concat(regexes); + } - const info = yield _this3.resolveRequest(); - if (info == null) { - throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('packageNotFoundRegistry', _this3.name, 'npm')); - } + const files = yield (_fs || _load_fs()).walk(config.cwd, null, new Set(FOLDERS_IGNORE)); + const dotIgnoreFiles = (0, (_filter || _load_filter()).filterOverridenGitignores)(files); - const deprecated = info.deprecated, - dist = info.dist; + // create ignores + for (const file of dotIgnoreFiles) { + const raw = yield (_fs || _load_fs()).readFile(file.absolute); + const lines = raw.split('\n'); - if (typeof deprecated === 'string') { - let human = `${info.name}@${info.version}`; - const parentNames = _this3.request.getParentNames(); - if (parentNames.length) { - human = parentNames.concat(human).join(' > '); + const regexes = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines, path.dirname(file.relative)); + filters = filters.concat(regexes); + } + + // files to definitely keep, takes precedence over ignore filter + const keepFiles = new Set(); + + // files to definitely ignore + const ignoredFiles = new Set(); + + // list of files that didn't match any of our patterns, if a directory in the chain above was matched + // then we should inherit it + const possibleKeepFiles = new Set(); + + // apply filters + (0, (_filter || _load_filter()).sortFilter)(files, filters, keepFiles, possibleKeepFiles, ignoredFiles); + + const packer = tar.pack(config.cwd, { + ignore: function (name) { + const relative = path.relative(config.cwd, name); + // Don't ignore directories, since we need to recurse inside them to check for unignored files. + if (fs2.lstatSync(name).isDirectory()) { + const isParentOfKeptFile = Array.from(keepFiles).some(function (name) { + return !path.relative(relative, name).startsWith('..'); + }); + return !isParentOfKeptFile; } - _this3.reporter.warn(`${human}: ${deprecated}`); + // Otherwise, ignore a file if we're not supposed to keep it. + return !keepFiles.has(relative); + }, + map: function (header) { + const suffix = header.name === '.' ? '' : `/${header.name}`; + header.name = `package${suffix}`; + delete header.uid; + delete header.gid; + return mapHeader ? mapHeader(header) : header; } + }); - if (dist != null && dist.tarball) { - info._remote = { - resolved: `${_this3.cleanRegistry(dist.tarball)}#${dist.shasum}`, - type: 'tarball', - reference: _this3.cleanRegistry(dist.tarball), - hash: dist.shasum, - registry: 'npm', - packageName: info.name - }; - } + return packer; + }); - info._uid = info.version; + return function packTarball(_x) { + return _ref.apply(this, arguments); + }; +})(); - return info; - })(); - } +let pack = exports.pack = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, dir) { + const packer = yield packTarball(config); + const compressor = packer.pipe(new zlib.Gzip()); + + return compressor; + }); + + return function pack(_x3, _x4) { + return _ref3.apply(this, arguments); + }; +})(); + +let run = exports.run = (() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const pkg = yield config.readRootManifest(); + if (!pkg.name) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('noName')); + } + if (!pkg.version) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('noVersion')); + } + + const normaliseScope = function (name) { + return name[0] === '@' ? name.substr(1).replace('/', '-') : name; + }; + const filename = flags.filename || path.join(config.cwd, `${normaliseScope(pkg.name)}-v${pkg.version}.tgz`); + + yield config.executeLifecycleScript('prepack'); + + const stream = yield pack(config, config.cwd); + + yield new Promise(function (resolve, reject) { + stream.pipe(fs2.createWriteStream(filename)); + stream.on('error', reject); + stream.on('close', resolve); + }); + + yield config.executeLifecycleScript('postpack'); + + reporter.success(reporter.lang('packWroteTarball', filename)); + }); + + return function run(_x5, _x6, _x7, _x8) { + return _ref4.apply(this, arguments); + }; +})(); + +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} + +var _filter; + +function _load_filter() { + return _filter = __webpack_require__(273); +} + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const zlib = __webpack_require__(230); +const path = __webpack_require__(0); +const tar = __webpack_require__(145); +const fs2 = __webpack_require__(5); + +const FOLDERS_IGNORE = [ +// never allow version control folders +'.git', 'CVS', '.svn', '.hg', 'node_modules']; + +const DEFAULT_IGNORE = (0, (_filter || _load_filter()).ignoreLinesToRegex)([...FOLDERS_IGNORE, + +// ignore cruft +'yarn.lock', '.lock-wscript', '.wafpickle-{0..9}', '*.swp', '._*', 'npm-debug.log', 'yarn-error.log', '.npmrc', '.yarnrc', '.npmignore', '.gitignore', '.DS_Store']); + +const NEVER_IGNORE = (0, (_filter || _load_filter()).ignoreLinesToRegex)([ +// never ignore these files +'!/package.json', '!/readme*', '!/+(license|licence)*', '!/+(changes|changelog|history)*']); + +function setFlags(commander) { + commander.option('-f, --filename <filename>', 'filename'); +} + +function hasWrapper(commander, args) { + return true; } -exports.default = NpmResolver; -NpmResolver.registry = 'npm'; /***/ }), -/* 127 */ +/* 157 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -46670,47 +48201,248 @@ NpmResolver.registry = 'npm'; Object.defineProperty(exports, "__esModule", { value: true }); +exports.getOutdated = exports.run = exports.requireLockfile = undefined; -var _slicedToArray2; +var _asyncToGenerator2; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _asyncToGenerator2; +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder); + const deps = yield getOutdated(config, reporter, flags, lockfile, args); -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + // do not pass the --latest flag to add, otherwise it may ignore the version ranges we already determined. + const addFlags = Object.assign({}, flags, { force: true, latest: false, existing: true }); + + setUserRequestedPackageVersions(deps, args); + + if (!deps.length) { + reporter.success(reporter.lang('allDependenciesUpToDate')); + return; + } + + // remove deps being upgraded from the lockfile, or else Add will use the already-installed version + // instead of the latest for the range. + deps.forEach(function (dep) { + return lockfile.removePattern(dep.upgradeTo); + }); + + const addArgs = deps.map(function (dep) { + return dep.upgradeTo; + }); + const add = new (_add || _load_add()).Add(addArgs, addFlags, config, reporter, lockfile); + yield add.init(); + }); + + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); + +let getOutdated = exports.getOutdated = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, lockfile, patterns) { + const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); + const outdatedFieldName = flags.latest ? 'latest' : 'wanted'; + + // this function attempts to determine the range operator on the semver range. + // this will only handle the simple cases of a semver starting with '^', '~', '>', '>=', '<=', or an exact version. + // "exotic" semver ranges will not be handled. + const getRangeOperator = function (version) { + const result = basicSemverOperatorRegex.exec(version); + return result ? result[1] || '' : '^'; + }; + + // Attempt to preserve the range operator from the package.json specified semver range. + // If an explicit operator was specified using --exact, --tilde, --caret, then that will take precedence. + const buildPatternToUpgradeTo = function (dep, flags) { + if (dep.latest === 'exotic') { + return dep.url; + } + + const toLatest = flags.latest; + const toVersion = toLatest ? dep.latest : dep.range; + let rangeOperator = ''; + + if (toLatest) { + if (flags.caret) { + rangeOperator = '^'; + } else if (flags.tilde) { + rangeOperator = '~'; + } else if (flags.exact) { + rangeOperator = ''; + } else { + rangeOperator = getRangeOperator(dep.range); + } + } + + return `${dep.name}@${rangeOperator}${toVersion}`; + }; + + // ensure scope is of the form `@scope/` + const normalizeScope = function () { + if (flags.scope) { + if (!flags.scope.startsWith('@')) { + flags.scope = '@' + flags.scope; + } + + if (!flags.scope.endsWith('/')) { + flags.scope += '/'; + } + } + }; + + const versionFilter = function (dep) { + return dep.current !== dep[outdatedFieldName]; + }; + + const scopeFilter = function (dep) { + if (validScopeRegex.test(flags.scope)) { + return dep.name.startsWith(flags.scope); + } + + return true; + }; + + if (!flags.latest) { + // these flags only have an affect when --latest is used + flags.tilde = false; + flags.exact = false; + flags.caret = false; + } + + normalizeScope(); + + const deps = (yield (_packageRequest || _load_packageRequest()).default.getOutdatedPackages(lockfile, install, config, reporter, patterns)).filter(versionFilter).filter(scopeFilter); + deps.forEach(function (dep) { + return dep.upgradeTo = buildPatternToUpgradeTo(dep, flags); + }); + + return deps; + }); + + return function getOutdated(_x5, _x6, _x7, _x8, _x9) { + return _ref2.apply(this, arguments); + }; +})(); + +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; + +var _add; + +function _load_add() { + return _add = __webpack_require__(121); } -var _extends2; +var _lockfile; -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(36)); +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); } -var _errors; +var _packageRequest; -function _load_errors() { - return _errors = __webpack_require__(3); +function _load_packageRequest() { + return _packageRequest = _interopRequireDefault(__webpack_require__(94)); } -var _misc; +var _normalizePattern; -function _load_misc() { - return _misc = __webpack_require__(10); +function _load_normalizePattern() { + return _normalizePattern = __webpack_require__(30); } -var _crypto; +var _install; -function _load_crypto() { - return _crypto = _interopRequireWildcard(__webpack_require__(85)); +function _load_install() { + return _install = __webpack_require__(31); } -var _child; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _load_child() { - return _child = _interopRequireWildcard(__webpack_require__(45)); +// used to detect whether a semver range is simple enough to preserve when doing a --latest upgrade. +// when not matched, the upgraded version range will default to `^` the same as the `add` command would. +const basicSemverOperatorRegex = new RegExp('^(\\^|~|>|<=|>=)?[^ |&,]+$'); + +// used to detect if a passed parameter is a scope or a package name. +const validScopeRegex = /^@[a-zA-Z0-9-][a-zA-Z0-9_.-]*\/$/g; + +// If specific versions were requested for packages, override what getOutdated reported as the latest to install +// Also add ones that are missing, since the requested packages may not have been outdated at all. +function setUserRequestedPackageVersions(deps, args) { + args.forEach(requestedPattern => { + const normalized = (0, (_normalizePattern || _load_normalizePattern()).normalizePattern)(requestedPattern); + const newPattern = `${normalized.name}@${normalized.range}`; + let found = false; + + deps.forEach(dep => { + if (normalized.hasVersion && dep.name === normalized.name) { + found = true; + dep.upgradeTo = newPattern; + } + }); + + if (normalized.hasVersion && !found) { + deps.push({ + name: normalized.name, + wanted: '', + latest: '', + url: '', + hint: '', + range: '', + current: '', + upgradeTo: newPattern + }); + } + }); +} + +function setFlags(commander) { + commander.usage('upgrade [flags]'); + commander.option('-S, --scope <scope>', 'upgrade packages under the specified scope'); + commander.option('--latest', 'list the latest version of packages, ignoring version ranges in package.json'); + commander.option('-E, --exact', 'install exact version. Only used when --latest is specified.'); + commander.option('-T, --tilde', 'install most recent release with the same minor version. Only used when --latest is specified.'); + commander.option('-C, --caret', 'install most recent release with the same major version. Only used when --latest is specified.'); +} + +function hasWrapper(commander, args) { + return true; +} + +const requireLockfile = exports.requireLockfile = true; + +/***/ }), +/* 158 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.integrityErrors = undefined; + +var _extends2; + +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); +} + +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} + +var _constants; + +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); } var _fs; @@ -46719,519 +48451,436 @@ function _load_fs() { return _fs = _interopRequireWildcard(__webpack_require__(4)); } -var _map; +var _misc; -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); +function _load_misc() { + return _misc = __webpack_require__(10); } -var _fs2; +var _workspaceLayout; -function _load_fs2() { - return _fs2 = __webpack_require__(6); +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(80)); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const invariant = __webpack_require__(5); -const semver = __webpack_require__(27); -const StringDecoder = __webpack_require__(168).StringDecoder; -const tarFs = __webpack_require__(109); -const tarStream = __webpack_require__(270); -const url = __webpack_require__(11); - - -const supportsArchiveCache = (0, (_map || _load_map()).default)({ - 'github.com': false }); +const invariant = __webpack_require__(7); +const path = __webpack_require__(0); -// Suppress any password prompts since we run these in the background -const env = (0, (_extends2 || _load_extends()).default)({}, process.env, { - GIT_ASKPASS: '', - GIT_TERMINAL_PROMPT: 0, - GIT_SSH_COMMAND: 'ssh -oBatchMode=yes' +const integrityErrors = exports.integrityErrors = { + EXPECTED_IS_NOT_A_JSON: 'integrityFailedExpectedIsNotAJSON', + FILES_MISSING: 'integrityFailedFilesMissing', + LOCKFILE_DONT_MATCH: 'integrityLockfilesDontMatch', + FLAGS_DONT_MATCH: 'integrityFlagsDontMatch', + LINKED_MODULES_DONT_MATCH: 'integrityCheckLinkedModulesDontMatch', + PATTERNS_DONT_MATCH: 'integrityPatternsDontMatch', + MODULES_FOLDERS_MISSING: 'integrityModulesFoldersMissing' +}; + +const INTEGRITY_FILE_DEFAULTS = () => ({ + modulesFolders: [], + flags: [], + linkedModules: [], + topLevelPatterns: [], + lockfileEntries: {}, + files: [] }); -// This regex is designed to match output from git of the style: -// ebeb6eafceb61dd08441ffe086c77eb472842494 refs/tags/v0.21.0 -// and extract the hash and tag name as capture groups -const gitRefLineRegex = /^([a-fA-F0-9]+)\s+(?:[^/]+\/){2}(.*)$/; - -class Git { - constructor(config, gitUrl, hash) { - this.supportsArchive = false; - this.fetched = false; +/** + * + */ +class InstallationIntegrityChecker { + constructor(config) { this.config = config; - this.reporter = config.reporter; - this.hash = hash; - this.ref = hash; - this.gitUrl = gitUrl; - this.cwd = this.config.getTemp((_crypto || _load_crypto()).hash(this.gitUrl.repository)); } /** - * npm URLs contain a 'git+' scheme prefix, which is not understood by git. - * git "URLs" also allow an alternative scp-like syntax, so they're not standard URLs. + * Get the common ancestor of every node_modules - it may be a node_modules directory itself, but isn't required to. */ - static npmUrlToGitUrl(npmUrl) { - // Expand shortened format first if needed - npmUrl = npmUrl.replace(/^github:/, 'git+ssh://git@github.com/'); - // Special case in npm, where ssh:// prefix is stripped to pass scp-like syntax - // which in git works as remote path only if there are no slashes before ':'. - const match = npmUrl.match(/^git\+ssh:\/\/((?:[^@:\/]+@)?([^@:\/]+):([^/]*).*)/); - // Additionally, if the host part is digits-only, npm falls back to - // interpreting it as an SSH URL with a port number. - if (match && /[^0-9]/.test(match[3])) { - return { - hostname: match[2], - protocol: 'ssh:', - repository: match[1] - }; + _getModulesRootFolder() { + if (this.config.modulesFolder) { + return this.config.modulesFolder; + } else if (this.config.workspaceRootFolder) { + return this.config.workspaceRootFolder; + } else { + return path.join(this.config.lockfileFolder, (_constants || _load_constants()).NODE_MODULES_FOLDER); } - - const repository = npmUrl.replace(/^git\+/, ''); - const parsed = url.parse(repository); - return { - hostname: parsed.hostname || null, - protocol: parsed.protocol || 'file:', - repository - }; } - static spawn(args) { - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + /** + * Get the directory in which the yarn-integrity file should be written. + */ - return (_child || _load_child()).spawn('git', args, (0, (_extends2 || _load_extends()).default)({}, opts, { env })); + _getIntegrityFileFolder() { + if (this.config.modulesFolder) { + return this.config.modulesFolder; + } else if (this.config.enableMetaFolder) { + return path.join(this.config.lockfileFolder, (_constants || _load_constants()).META_FOLDER); + } else { + return path.join(this.config.lockfileFolder, (_constants || _load_constants()).NODE_MODULES_FOLDER); + } } /** - * Check if the host specified in the input `gitUrl` has archive capability. + * Get the full path of the yarn-integrity file. */ - static hasArchiveCapability(ref) { + _getIntegrityFileLocation() { + var _this = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const hostname = ref.hostname; - if (ref.protocol !== 'ssh:' || hostname == null) { - return false; - } + const locationFolder = _this._getIntegrityFileFolder(); + const locationPath = path.join(locationFolder, (_constants || _load_constants()).INTEGRITY_FILENAME); - if (hostname in supportsArchiveCache) { - return supportsArchiveCache[hostname]; - } + const exists = yield (_fs || _load_fs()).exists(locationPath); - try { - yield Git.spawn(['archive', `--remote=${ref.repository}`, 'HEAD', Date.now() + '']); - throw new Error(); - } catch (err) { - const supports = err.message.indexOf('did not match any files') >= 0; - return supportsArchiveCache[hostname] = supports; - } + return { + locationFolder, + locationPath, + exists + }; })(); } /** - * Check if the input `target` is a 5-40 character hex commit hash. + * Get the list of the directories that contain our modules (there might be multiple such folders b/c of workspaces). */ - static isCommitHash(target) { - return !!target && /^[a-f0-9]{5,40}$/.test(target); - } + _getModulesFolders() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - static repoExists(ref) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - try { - yield Git.spawn(['ls-remote', '-t', ref.repository]); - return true; - } catch (err) { - return false; + let workspaceLayout = _ref.workspaceLayout; + + const locations = []; + + if (this.config.modulesFolder) { + locations.push(this.config.modulesFolder); + } else { + locations.push(path.join(this.config.lockfileFolder, (_constants || _load_constants()).NODE_MODULES_FOLDER)); + } + + if (workspaceLayout) { + for (const workspaceName of Object.keys(workspaceLayout.workspaces)) { + const loc = workspaceLayout.workspaces[workspaceName].loc; + + if (loc) { + locations.push(path.join(loc, (_constants || _load_constants()).NODE_MODULES_FOLDER)); + } } - })(); - } + } - static replaceProtocol(ref, protocol) { - return { - hostname: ref.hostname, - protocol, - repository: ref.repository.replace(/^(?:git|http):/, protocol) - }; + return locations.sort((_misc || _load_misc()).sortAlpha); } /** - * Attempt to upgrade insecure protocols to secure protocol + * Get a list of the files that are located inside our module folders. */ - static secureGitUrl(ref, hash, reporter) { + _getIntegrityListing() { + var _this2 = this; + + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + + let workspaceLayout = _ref2.workspaceLayout; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (Git.isCommitHash(hash)) { - // this is cryptographically secure - return ref; - } + const files = []; - if (ref.protocol === 'git:') { - const secureUrl = Git.replaceProtocol(ref, 'https:'); - if (yield Git.repoExists(secureUrl)) { - return secureUrl; - } else { - throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadGitWithoutCommit', ref)); - } - } + const recurse = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dir) { + for (const file of yield (_fs || _load_fs()).readdir(dir)) { + const entry = path.join(dir, file); + const stat = yield (_fs || _load_fs()).lstat(entry); - if (ref.protocol === 'http:') { - const secureRef = Git.replaceProtocol(ref, 'https:'); - if (yield Git.repoExists(secureRef)) { - return secureRef; - } else { - if (yield Git.repoExists(ref)) { - return ref; - } else { - throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadHTTPWithoutCommit', ref)); + if (stat.isDirectory()) { + yield recurse(entry); + } else { + files.push(entry); + } } - } - } + }); - if (ref.protocol === 'https:') { - if (yield Git.repoExists(ref)) { - return ref; - } else { - throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadHTTPSWithoutCommit', ref)); + return function recurse(_x3) { + return _ref3.apply(this, arguments); + }; + })(); + + for (const modulesFolder of _this2._getModulesFolders({ workspaceLayout })) { + if (yield (_fs || _load_fs()).exists(modulesFolder)) { + yield recurse(modulesFolder); } } - return ref; + return files; })(); } /** - * Archive a repo to destination + * Generate integrity hash of input lockfile. */ - archive(dest) { - if (this.supportsArchive) { - return this._archiveViaRemoteArchive(dest); - } else { - return this._archiveViaLocalFetched(dest); - } - } - - _archiveViaRemoteArchive(dest) { - var _this = this; + _generateIntegrityFile(lockfile, patterns, flags, workspaceLayout, artifacts) { + var _this3 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const hashStream = new (_crypto || _load_crypto()).HashStream(); - yield Git.spawn(['archive', `--remote=${_this.gitUrl.repository}`, _this.ref], { - process(proc, resolve, reject, done) { - const writeStream = (0, (_fs2 || _load_fs2()).createWriteStream)(dest); - proc.on('error', reject); - writeStream.on('error', reject); - writeStream.on('end', done); - writeStream.on('open', function () { - proc.stdout.pipe(hashStream).pipe(writeStream); - }); - writeStream.once('finish', done); - } + const result = (0, (_extends2 || _load_extends()).default)({}, INTEGRITY_FILE_DEFAULTS(), { + artifacts }); - return hashStream.getHash(); - })(); - } - _archiveViaLocalFetched(dest) { - var _this2 = this; + result.topLevelPatterns = patterns; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const hashStream = new (_crypto || _load_crypto()).HashStream(); - yield Git.spawn(['archive', _this2.hash], { - cwd: _this2.cwd, - process(proc, resolve, reject, done) { - const writeStream = (0, (_fs2 || _load_fs2()).createWriteStream)(dest); - proc.on('error', reject); - writeStream.on('error', reject); - writeStream.on('open', function () { - proc.stdout.pipe(hashStream).pipe(writeStream); - }); - writeStream.once('finish', done); - } - }); - return hashStream.getHash(); - })(); - } + // If using workspaces, we also need to add the workspaces patterns to the top-level, so that we'll know if a + // dependency is added or removed into one of them. We must take care not to read the aggregator (if !loc). + // + // Also note that we can't use of workspaceLayout.workspaces[].manifest._reference.patterns, because when + // doing a "yarn check", the _reference property hasn't yet been properly initialized. - /** - * Clone a repo to the input `dest`. Use `git archive` if it's available, otherwise fall - * back to `git clone`. - */ + if (workspaceLayout) { + result.topLevelPatterns = result.topLevelPatterns.filter(function (p) { + // $FlowFixMe + return !workspaceLayout.getManifestByPattern(p); + }); - clone(dest) { - if (this.supportsArchive) { - return this._cloneViaRemoteArchive(dest); - } else { - return this._cloneViaLocalFetched(dest); - } - } + for (const name of Object.keys(workspaceLayout.workspaces)) { + if (!workspaceLayout.workspaces[name].loc) { + continue; + } - _cloneViaRemoteArchive(dest) { - var _this3 = this; + const manifest = workspaceLayout.workspaces[name].manifest; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield Git.spawn(['archive', `--remote=${_this3.gitUrl.repository}`, _this3.ref], { - process(proc, update, reject, done) { - const extractor = tarFs.extract(dest, { - dmode: 0o555, // all dirs should be readable - fmode: 0o444 }); - extractor.on('error', reject); - extractor.on('finish', done); + if (manifest) { + for (const dependencyType of (_constants || _load_constants()).DEPENDENCY_TYPES) { + const dependencies = manifest[dependencyType]; - proc.stdout.pipe(extractor); - proc.on('error', reject); - } - }); - })(); - } + if (!dependencies) { + continue; + } - _cloneViaLocalFetched(dest) { - var _this4 = this; + for (const dep of Object.keys(dependencies)) { + result.topLevelPatterns.push(`${dep}@${dependencies[dep]}`); + } + } + } + } + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield Git.spawn(['archive', _this4.hash], { - cwd: _this4.cwd, - process(proc, resolve, reject, done) { - const extractor = tarFs.extract(dest, { - dmode: 0o555, // all dirs should be readable - fmode: 0o444 }); + result.topLevelPatterns.sort((_misc || _load_misc()).sortAlpha); - extractor.on('error', reject); - extractor.on('finish', done); + if (flags.checkFiles) { + result.flags.push('checkFiles'); + } - proc.stdout.pipe(extractor); - } - }); - })(); - } + if (flags.flat) { + result.flags.push('flat'); + } + if (flags.ignoreScripts) { + result.flags.push('ignoreScripts'); + } - /** - * Clone this repo. - */ + if (_this3.config.production) { + result.flags.push('production'); + } - fetch() { - var _this5 = this; + const linkedModules = _this3.config.linkedModules; - const gitUrl = this.gitUrl, - cwd = this.cwd; + if (linkedModules.length) { + result.linkedModules = linkedModules.sort((_misc || _load_misc()).sortAlpha); + } + for (const key of Object.keys(lockfile)) { + result.lockfileEntries[key] = lockfile[key].resolved || ''; + } - return (_fs || _load_fs()).lockQueue.push(gitUrl.repository, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (yield (_fs || _load_fs()).exists(cwd)) { - yield Git.spawn(['pull'], { cwd }); - } else { - yield Git.spawn(['clone', gitUrl.repository, cwd]); + for (const modulesFolder of _this3._getModulesFolders({ workspaceLayout })) { + if (yield (_fs || _load_fs()).exists(modulesFolder)) { + result.modulesFolders.push(path.relative(_this3.config.lockfileFolder, modulesFolder)); + } } - _this5.fetched = true; - })); - } + if (flags.checkFiles) { + const modulesRoot = _this3._getModulesRootFolder(); - /** - * Given a list of tags/branches from git, check if they match an input range. - */ + result.files = (yield _this3._getIntegrityListing({ workspaceLayout })).map(function (entry) { + return path.relative(modulesRoot, entry); + }).sort((_misc || _load_misc()).sortAlpha); + } - findResolution(range, tags) { - var _this6 = this; + return result; + })(); + } + _getIntegrityFile(locationPath) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // If there are no tags and target is *, fallback to the latest commit on master - // or if we have no target. - if (!range || !tags.length && range === '*') { - return 'master'; + const expectedRaw = yield (_fs || _load_fs()).readFile(locationPath); + try { + return (0, (_extends2 || _load_extends()).default)({}, INTEGRITY_FILE_DEFAULTS(), JSON.parse(expectedRaw)); + } catch (e) { + // ignore JSON parsing for legacy text integrity files compatibility } - - return (yield _this6.config.resolveConstraints(tags.filter(function (tag) { - return !!semver.valid(tag, _this6.config.looseSemver); - }), range)) || range; + return null; })(); } - /** - * Fetch the file by cloning the repo and reading it. - */ + _compareIntegrityFiles(actual, expected, checkFiles, workspaceLayout) { + if (!expected) { + return 'EXPECTED_IS_NOT_A_JSON'; + } - getFile(filename) { - if (this.supportsArchive) { - return this._getFileFromArchive(filename); - } else { - return this._getFileFromClone(filename); + if (!(0, (_misc || _load_misc()).compareSortedArrays)(actual.linkedModules, expected.linkedModules)) { + return 'LINKED_MODULES_DONT_MATCH'; } - } - _getFileFromArchive(filename) { - var _this7 = this; + let relevantExpectedFlags = expected.flags.slice(); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - try { - return yield Git.spawn(['archive', `--remote=${_this7.gitUrl.repository}`, _this7.ref, filename], { - process(proc, update, reject, done) { - const parser = tarStream.extract(); + // If we run "yarn" after "yarn --check-files", we shouldn't fail the less strict validation + if (actual.flags.indexOf('checkFiles') === -1) { + relevantExpectedFlags = relevantExpectedFlags.filter(flag => flag !== 'checkFiles'); + } - parser.on('error', reject); - parser.on('finish', done); + if (!(0, (_misc || _load_misc()).compareSortedArrays)(actual.flags, relevantExpectedFlags)) { + return 'FLAGS_DONT_MATCH'; + } - parser.on('entry', (header, stream, next) => { - const decoder = new StringDecoder('utf8'); - let fileContent = ''; + if (!(0, (_misc || _load_misc()).compareSortedArrays)(actual.topLevelPatterns, expected.topLevelPatterns || [])) { + return 'PATTERNS_DONT_MATCH'; + } - stream.on('data', buffer => { - fileContent += decoder.write(buffer); - }); - stream.on('end', () => { - const remaining = decoder.end(); - update(fileContent + remaining); - next(); - }); - stream.resume(); - }); + for (const key of Object.keys(actual.lockfileEntries)) { + if (actual.lockfileEntries[key] !== expected.lockfileEntries[key]) { + return 'LOCKFILE_DONT_MATCH'; + } + } - proc.stdout.pipe(parser); - } - }); - } catch (err) { - if (err.message.indexOf('did not match any files') >= 0) { - return false; - } else { - throw err; - } + for (const key of Object.keys(expected.lockfileEntries)) { + if (actual.lockfileEntries[key] !== expected.lockfileEntries[key]) { + return 'LOCKFILE_DONT_MATCH'; } - })(); - } + } - _getFileFromClone(filename) { - var _this8 = this; + if (checkFiles) { + // Early bailout if we expect more files than what we have + if (expected.files.length > actual.files.length) { + return 'FILES_MISSING'; + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - invariant(_this8.fetched, 'Repo not fetched'); + // Since we know the "files" array is sorted (alphabetically), we can optimize the thing + // Instead of storing the files in a Set, we can just iterate both arrays at once. O(n)! + for (let u = 0, v = 0; u < expected.files.length; ++u) { + // Index that, if reached, means that we won't have enough food to match the remaining expected entries anyway + const max = v + (actual.files.length - v) - (expected.files.length - u) + 1; - try { - return yield Git.spawn(['show', `${_this8.hash}:${filename}`], { - cwd: _this8.cwd - }); - } catch (err) { - // file doesn't exist - return false; + // Skip over files that have been added (ie not present in 'expected') + while (v < max && actual.files[v] !== expected.files[u]) { + v += 1; + } + + // If we've reached the index defined above, the file is either missing or we can early exit + if (v === max) { + return 'FILES_MISSING'; + } } - })(); + } + return 'OK'; } - /** - * Initialize the repo, find a secure url to use and - * set the ref to match an input `target`. - */ - init() { - var _this9 = this; + check(patterns, lockfile, flags, workspaceLayout) { + var _this4 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this9.gitUrl = yield Git.secureGitUrl(_this9.gitUrl, _this9.hash, _this9.reporter); - // check capabilities - if (yield Git.hasArchiveCapability(_this9.gitUrl)) { - _this9.supportsArchive = true; - } else { - yield _this9.fetch(); + // check if patterns exist in lockfile + const missingPatterns = patterns.filter(function (p) { + return !lockfile[p] && (!workspaceLayout || !workspaceLayout.getManifestByPattern(p)); + }); + + const loc = yield _this4._getIntegrityFileLocation(); + if (missingPatterns.length || !loc.exists) { + return { + integrityFileMissing: !loc.exists, + missingPatterns + }; } - return _this9.setRefRemote(); - })(); - } + const actual = yield _this4._generateIntegrityFile(lockfile, patterns, flags, workspaceLayout); - setRefRemote() { - var _this10 = this; + const expected = yield _this4._getIntegrityFile(loc.locationPath); + let integrityMatches = _this4._compareIntegrityFiles(actual, expected, flags.checkFiles, workspaceLayout); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const stdout = yield Git.spawn(['ls-remote', '--tags', '--heads', _this10.gitUrl.repository]); - const refs = Git.parseRefs(stdout); - return _this10.setRef(refs); + if (integrityMatches === 'OK') { + invariant(expected, "The integrity shouldn't pass without integrity file"); + for (const modulesFolder of expected.modulesFolders) { + if (!(yield (_fs || _load_fs()).exists(path.join(_this4.config.lockfileFolder, modulesFolder)))) { + integrityMatches = 'MODULES_FOLDERS_MISSING'; + } + } + } + + return { + integrityFileMissing: false, + integrityMatches: integrityMatches === 'OK', + integrityError: integrityMatches === 'OK' ? undefined : integrityMatches, + missingPatterns + }; })(); } /** - * TODO description + * Get artifacts from integrity file if it exists. */ - - setRef(refs) { - var _this11 = this; + getArtifacts() { + var _this5 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // get commit ref - const hash = _this11.hash; - - - const names = Object.keys(refs); - - if (Git.isCommitHash(hash)) { - for (const name in refs) { - if (refs[name] === hash) { - _this11.ref = name; - return hash; - } - } - - // `git archive` only accepts a treeish and we have no ref to this commit - _this11.supportsArchive = false; - - if (!_this11.fetched) { - // in fact, `git archive` can't be used, and we haven't fetched the project yet. Do it now. - yield _this11.fetch(); - } - return _this11.ref = _this11.hash = hash; + const loc = yield _this5._getIntegrityFileLocation(); + if (!loc.exists) { + return null; } - const ref = yield _this11.findResolution(hash, names); - const commit = refs[ref]; - if (commit) { - _this11.ref = ref; - return _this11.hash = commit; - } else { - throw new (_errors || _load_errors()).MessageError(_this11.reporter.lang('couldntFindMatch', ref, names.join(','), _this11.gitUrl.repository)); + const expectedRaw = yield (_fs || _load_fs()).readFile(loc.locationPath); + let expected; + try { + expected = JSON.parse(expectedRaw); + } catch (e) { + // ignore JSON parsing for legacy text integrity files compatibility } + + return expected ? expected.artifacts : null; })(); } /** - * Parse Git ref lines into hash of tag names to SHA hashes + * Write the integrity hash of the current install to disk. */ + save(patterns, lockfile, flags, workspaceLayout, artifacts) { + var _this6 = this; - static parseRefs(stdout) { - // store references - const refs = {}; - - // line delimited - const refLines = stdout.split('\n'); - - for (const line of refLines) { - const match = gitRefLineRegex.exec(line); - - if (match) { - var _match = (0, (_slicedToArray2 || _load_slicedToArray()).default)(match, 3); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const integrityFile = yield _this6._generateIntegrityFile(lockfile, patterns, flags, workspaceLayout, artifacts); - const sha = _match[1], - tagName = _match[2]; + const loc = yield _this6._getIntegrityFileLocation(); + invariant(loc.locationPath, 'expected integrity hash location'); - // As documented in gitrevisions: - // https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html#_specifying_revisions - // "A suffix ^ followed by an empty brace pair means the object could be a tag, - // and dereference the tag recursively until a non-tag object is found." - // In other words, the hash without ^{} is the hash of the tag, - // and the hash with ^{} is the hash of the commit at which the tag was made. + yield (_fs || _load_fs()).mkdirp(path.dirname(loc.locationPath)); + yield (_fs || _load_fs()).writeFile(loc.locationPath, JSON.stringify(integrityFile, null, 2)); + })(); + } - const name = (0, (_misc || _load_misc()).removeSuffix)(tagName, '^{}'); + removeIntegrityFile() { + var _this7 = this; - refs[name] = sha; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const loc = yield _this7._getIntegrityFileLocation(); + if (loc.exists) { + yield (_fs || _load_fs()).unlink(loc.locationPath); } - } - - return refs; + })(); } } -exports.default = Git; +exports.default = InstallationIntegrityChecker; /***/ }), -/* 128 */ +/* 159 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -47240,262 +48889,612 @@ exports.default = Git; Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = guessName; +exports.linkBin = undefined; -var _url; +var _slicedToArray2; -function _load_url() { - return _url = _interopRequireDefault(__webpack_require__(11)); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function cleanup(name) { - name = name.replace(/-\d+\.\d+\.\d+/, ''); - return name.split('.')[0]; -} +var _asyncToGenerator2; -function guessNameFallback(source) { - // If cannot parse as url, just return cleaned up last part - const parts = source.split('/'); - return cleanup(parts[parts.length - 1]); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -function guessName(source) { - try { - const parsed = (_url || _load_url()).default.parse(source); - - if (!parsed.pathname) { - return guessNameFallback(source); - } - - const parts = parsed.pathname.split('/'); - - // Priority goes to part that ends with .git - for (const part of parts) { - if (part.match(/\.git$/)) { - return cleanup(part); +let linkBin = exports.linkBin = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (src, dest) { + if (process.platform === 'win32') { + const unlockMutex = yield (0, (_mutex || _load_mutex()).default)(src); + try { + yield cmdShim(src, dest); + } finally { + unlockMutex(); } + } else { + yield (_fs || _load_fs()).mkdirp(path.dirname(dest)); + yield (_fs || _load_fs()).symlink(src, dest); + yield (_fs || _load_fs()).chmod(dest, '755'); } + }); - // Most likely a directory - if (parsed.host == null) { - return cleanup(parts[parts.length - 1]); - } - - // A site like github or gitlab - if (parts.length > 2) { - return cleanup(parts[2]); - } + return function linkBin(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); - // Privately hosted package? - if (parts.length > 1) { - return cleanup(parts[1]); - } +var _packageHoister; - return guessNameFallback(source); - } catch (e) { - return guessNameFallback(source); - } +function _load_packageHoister() { + return _packageHoister = _interopRequireDefault(__webpack_require__(415)); } -/***/ }), -/* 129 */ -/***/ (function(module, exports, __webpack_require__) { +var _constants; -"use strict"; +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} +var _promise; -Object.defineProperty(exports, "__esModule", { - value: true -}); +function _load_promise() { + return _promise = _interopRequireWildcard(__webpack_require__(53)); +} -var _asyncToGenerator2; +var _misc; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function _load_misc() { + return _misc = __webpack_require__(10); } -var _validate; +var _fs; -function _load_validate() { - return _validate = _interopRequireDefault(__webpack_require__(63)); +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } -var _fix; +var _mutex; -function _load_fix() { - return _fix = _interopRequireDefault(__webpack_require__(386)); +function _load_mutex() { + return _mutex = _interopRequireDefault(__webpack_require__(437)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _semver; -const path = __webpack_require__(1); +function _load_semver() { + return _semver = __webpack_require__(445); +} -exports.default = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, config, isRoot) { - // create human readable name - const name = info.name, - version = info.version; +var _workspaceLayout; - let human; - if (typeof name === 'string') { - human = name; - } - if (human && typeof version === 'string' && version) { - human += `@${version}`; - } - if (isRoot && info._loc) { - human = path.relative(config.cwd, info._loc); - } +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(80)); +} - function warn(msg) { - if (human) { - msg = `${human}: ${msg}`; - } - config.reporter.warn(msg); - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - yield (0, (_fix || _load_fix()).default)(info, moduleLoc, config.reporter, warn, config.looseSemver); - try { - (0, (_validate || _load_validate()).default)(info, isRoot, config.reporter, warn); - } catch (err) { - if (human) { - err.message = `${human}: ${err.message}`; - } - throw err; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return info; - }); +const invariant = __webpack_require__(7); - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); +const cmdShim = (_promise || _load_promise()).promisify(__webpack_require__(458)); +const path = __webpack_require__(0); +// Concurrency for creating bin links disabled because of the issue #1961 +const linkBinConcurrency = 1; -/***/ }), -/* 130 */ -/***/ (function(module, exports, __webpack_require__) { +class PackageLinker { + constructor(config, resolver) { + this.resolver = resolver; + this.reporter = config.reporter; + this.config = config; + this.artifacts = {}; + this.topLevelBinLinking = true; + } -"use strict"; + setArtifacts(artifacts) { + this.artifacts = artifacts; + } + setTopLevelBinLinking(topLevelBinLinking) { + this.topLevelBinLinking = topLevelBinLinking; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isValidLicense = isValidLicense; -exports.stringifyPerson = stringifyPerson; -exports.parsePerson = parsePerson; -exports.normalizePerson = normalizePerson; -exports.extractDescription = extractDescription; -exports.extractRepositoryUrl = extractRepositoryUrl; + linkSelfDependencies(pkg, pkgLoc, targetBinLoc) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + targetBinLoc = path.join(targetBinLoc, '.bin'); + yield (_fs || _load_fs()).mkdirp(targetBinLoc); + targetBinLoc = yield (_fs || _load_fs()).realpath(targetBinLoc); + pkgLoc = yield (_fs || _load_fs()).realpath(pkgLoc); + for (const _ref2 of (0, (_misc || _load_misc()).entries)(pkg.bin)) { + var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2); + const scriptName = _ref3[0]; + const scriptCmd = _ref3[1]; -const validateLicense = __webpack_require__(634); + const dest = path.join(targetBinLoc, scriptName); + const src = path.join(pkgLoc, scriptCmd); + if (!(yield (_fs || _load_fs()).exists(src))) { + // TODO maybe throw an error + continue; + } + yield linkBin(src, dest); + } + })(); + } -function isValidLicense(license) { - return !!license && validateLicense(license).validForNewPackages; -} + linkBinDependencies(pkg, dir) { + var _this = this; -function stringifyPerson(person) { - if (!person || typeof person !== 'object') { - return person; - } + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const deps = []; - const parts = []; - if (person.name) { - parts.push(person.name); - } + const ref = pkg._reference; + invariant(ref, 'Package reference is missing'); - const email = person.email || person.mail; - if (typeof email === 'string') { - parts.push(`<${email}>`); + const remote = pkg._remote; + invariant(remote, 'Package remote is missing'); + + // link up `bin scripts` in `dependencies` + for (const pattern of ref.dependencies) { + const dep = _this.resolver.getStrictResolvedPattern(pattern); + if ( + // Missing location means not installed inside node_modules + dep._reference && dep._reference.location && dep.bin && Object.keys(dep.bin).length) { + deps.push({ + dep, + loc: _this.config.generateHardModulePath(dep._reference) + }); + } + } + + // link up the `bin` scripts in bundled dependencies + if (pkg.bundleDependencies) { + for (const depName of pkg.bundleDependencies) { + const loc = path.join(_this.config.generateHardModulePath(ref), _this.config.getFolder(pkg), depName); + try { + const dep = yield _this.config.readManifest(loc, remote.registry); + + if (dep.bin && Object.keys(dep.bin).length) { + deps.push({ dep, loc }); + } + } catch (ex) { + if (ex.code !== 'ENOENT') { + throw ex; + } + // intentionally ignoring ENOENT error. + // bundledDependency either does not exist or does not contain a package.json + } + } + } + + // no deps to link + if (!deps.length) { + return; + } + + // write the executables + for (const _ref4 of deps) { + const dep = _ref4.dep, + loc = _ref4.loc; + + if (dep._reference && dep._reference.location) { + yield _this.linkSelfDependencies(dep, loc, dir); + } + } + })(); } - const url = person.url || person.web; - if (typeof url === 'string') { - parts.push(`(${url})`); + getFlatHoistedTree(patterns) { + var _ref5 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + let ignoreOptional = _ref5.ignoreOptional; + + const hoister = new (_packageHoister || _load_packageHoister()).default(this.config, this.resolver, { ignoreOptional }); + hoister.seed(patterns); + return hoister.init(); } - return parts.join(' '); -} + copyModules(patterns, workspaceLayout) { + var _this2 = this; -function parsePerson(person) { - if (typeof person !== 'string') { - return person; + var _ref6 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + let linkDuplicates = _ref6.linkDuplicates, + ignoreOptional = _ref6.ignoreOptional; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let flatTree = _this2.getFlatHoistedTree(patterns, { ignoreOptional }); + // sorted tree makes file creation and copying not to interfere with each other + flatTree = flatTree.sort(function (dep1, dep2) { + return dep1[0].localeCompare(dep2[0]); + }); + + // list of artifacts in modules to remove from extraneous removal + const artifactFiles = []; + + const copyQueue = new Map(); + const hardlinkQueue = new Map(); + const hardlinksEnabled = linkDuplicates && (yield (_fs || _load_fs()).hardlinksWork(_this2.config.cwd)); + + const copiedSrcs = new Map(); + const symlinkPaths = new Map(); + for (const _ref7 of flatTree) { + var _ref8 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref7, 2); + + const folder = _ref8[0]; + var _ref8$ = _ref8[1]; + const pkg = _ref8$.pkg; + const loc = _ref8$.loc; + + const remote = pkg._remote || { type: '' }; + const ref = pkg._reference; + let dest = folder; + invariant(ref, 'expected package reference'); + + let src = loc; + let type = ''; + if (remote.type === 'link') { + // replace package source from incorrect cache location (workspaces and link: are not cached) + // with a symlink source + src = remote.reference; + type = 'symlink'; + } else if (workspaceLayout && remote.type === 'workspace') { + src = remote.reference; + type = 'symlink'; + if (dest.indexOf(workspaceLayout.virtualManifestName) !== -1) { + // we don't need to install virtual manifest + continue; + } + // to get real path for non hoisted dependencies + symlinkPaths.set(dest, src); + } else { + // backwards compatibility: get build artifacts from metadata + // does not apply to symlinked dependencies + const metadata = yield _this2.config.readPackageMetadata(src); + for (const file of metadata.artifacts) { + artifactFiles.push(path.join(dest, file)); + } + } + + for (const _ref9 of symlinkPaths.entries()) { + var _ref10 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref9, 2); + + const symlink = _ref10[0]; + const realpath = _ref10[1]; + + if (dest.indexOf(symlink + path.sep) === 0) { + // after hoisting we end up with this structure + // root/node_modules/workspace-package(symlink)/node_modules/package-a + // fs.copy operations can't copy files through a symlink, so all the paths under workspace-package + // need to be replaced with a real path, except for the symlink root/node_modules/workspace-package + dest = dest.replace(symlink, realpath); + } + } + + ref.setLocation(dest); + + const integrityArtifacts = _this2.artifacts[`${pkg.name}@${pkg.version}`]; + if (integrityArtifacts) { + for (const file of integrityArtifacts) { + artifactFiles.push(path.join(dest, file)); + } + } + + const copiedDest = copiedSrcs.get(src); + if (!copiedDest) { + if (hardlinksEnabled) { + copiedSrcs.set(src, dest); + } + copyQueue.set(dest, { + src, + dest, + type, + onFresh() { + if (ref) { + ref.setFresh(true); + } + } + }); + } else { + hardlinkQueue.set(dest, { + src: copiedDest, + dest, + onFresh() { + if (ref) { + ref.setFresh(true); + } + } + }); + } + } + + // keep track of all scoped paths to remove empty scopes after copy + const scopedPaths = new Set(); + + // register root & scoped packages as being possibly extraneous + const possibleExtraneous = new Set(); + for (const folder of _this2.config.registryFolders) { + const loc = path.join(_this2.config.cwd, folder); + + if (yield (_fs || _load_fs()).exists(loc)) { + const files = yield (_fs || _load_fs()).readdir(loc); + let filepath; + for (const file of files) { + filepath = path.join(loc, file); + if (file[0] === '@') { + // it's a scope, not a package + scopedPaths.add(filepath); + const subfiles = yield (_fs || _load_fs()).readdir(filepath); + for (const subfile of subfiles) { + possibleExtraneous.add(path.join(filepath, subfile)); + } + } else { + possibleExtraneous.add(filepath); + } + } + } + } + + // If an Extraneous is an entry created via "yarn link", we prevent it from being overwritten. + // Unfortunately, the only way we can know if they have been created this way is to check if they + // are symlinks - problem is that it then conflicts with the newly introduced "link:" protocol, + // which also creates symlinks :( a somewhat weak fix is to check if the symlink target is registered + // inside the linkFolder, in which case we assume it has been created via "yarn link". Otherwise, we + // assume it's a link:-managed dependency, and overwrite it as usual. + const linkTargets = new Map(); + + let linkedModules; + try { + linkedModules = yield (_fs || _load_fs()).readdir(_this2.config.linkFolder); + } catch (err) { + if (err.code === 'ENOENT') { + linkedModules = []; + } else { + throw err; + } + } + + // TODO: Consolidate this logic with `this.config.linkedModules` logic + for (const entry of linkedModules) { + const entryPath = path.join(_this2.config.linkFolder, entry); + const stat = yield (_fs || _load_fs()).lstat(entryPath); + + if (stat.isSymbolicLink()) { + const packageName = entry; + linkTargets.set(packageName, (yield (_fs || _load_fs()).readlink(entryPath))); + } else if (stat.isDirectory() && entry[0] === '@') { + // if the entry is directory beginning with '@', then we're dealing with a package scope, which + // means we must iterate inside to retrieve the package names it contains + const scopeName = entry; + + for (const entry2 of yield (_fs || _load_fs()).readdir(entryPath)) { + const entryPath2 = path.join(entryPath, entry2); + const stat2 = yield (_fs || _load_fs()).lstat(entryPath2); + + if (stat2.isSymbolicLink()) { + const packageName = `${scopeName}/${entry2}`; + linkTargets.set(packageName, (yield (_fs || _load_fs()).readlink(entryPath2))); + } + } + } + } + + for (const loc of possibleExtraneous) { + let packageName = path.basename(loc); + const scopeName = path.basename(path.dirname(loc)); + + if (scopeName[0] === `@`) { + packageName = `${scopeName}/${packageName}`; + } + + if ((yield (_fs || _load_fs()).lstat(loc)).isSymbolicLink() && linkTargets.has(packageName) && linkTargets.get(packageName) === (yield (_fs || _load_fs()).readlink(loc))) { + possibleExtraneous.delete(loc); + copyQueue.delete(loc); + } + } + + // + let tick; + yield (_fs || _load_fs()).copyBulk(Array.from(copyQueue.values()), _this2.reporter, { + possibleExtraneous, + artifactFiles, + + ignoreBasenames: [(_constants || _load_constants()).METADATA_FILENAME, (_constants || _load_constants()).TARBALL_FILENAME], + + onStart: function (num) { + tick = _this2.reporter.progress(num); + }, + + onProgress(src) { + if (tick) { + tick(); + } + } + }); + yield (_fs || _load_fs()).hardlinkBulk(Array.from(hardlinkQueue.values()), _this2.reporter, { + possibleExtraneous, + artifactFiles, + + onStart: function (num) { + tick = _this2.reporter.progress(num); + }, + + onProgress(src) { + if (tick) { + tick(); + } + } + }); + + // remove all extraneous files that weren't in the tree + for (const loc of possibleExtraneous) { + _this2.reporter.verbose(_this2.reporter.lang('verboseFileRemoveExtraneous', loc)); + yield (_fs || _load_fs()).unlink(loc); + } + + // remove any empty scoped directories + for (const scopedPath of scopedPaths) { + const files = yield (_fs || _load_fs()).readdir(scopedPath); + if (files.length === 0) { + yield (_fs || _load_fs()).unlink(scopedPath); + } + } + + // create binary links + if (_this2.config.binLinks) { + const topLevelDependencies = _this2.determineTopLevelBinLinks(flatTree); + const tickBin = _this2.reporter.progress(flatTree.length + topLevelDependencies.length); + + // create links in transient dependencies + yield (_promise || _load_promise()).queue(flatTree, (() => { + var _ref11 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref12) { + var _ref13 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref12, 2); + + let dest = _ref13[0], + pkg = _ref13[1].pkg; + + if (pkg._reference && pkg._reference.location) { + const binLoc = path.join(dest, _this2.config.getFolder(pkg)); + yield _this2.linkBinDependencies(pkg, binLoc); + tickBin(); + } + }); + + return function (_x5) { + return _ref11.apply(this, arguments); + }; + })(), linkBinConcurrency); + + // create links at top level for all dependencies. + yield (_promise || _load_promise()).queue(topLevelDependencies, (() => { + var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref15) { + var _ref16 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref15, 2); + + let dest = _ref16[0], + pkg = _ref16[1]; + + if (pkg._reference && pkg._reference.location && pkg.bin && Object.keys(pkg.bin).length) { + const binLoc = path.join(_this2.config.cwd, _this2.config.getFolder(pkg)); + yield _this2.linkSelfDependencies(pkg, dest, binLoc); + tickBin(); + } + }); + + return function (_x6) { + return _ref14.apply(this, arguments); + }; + })(), linkBinConcurrency); + } + + for (const _ref17 of flatTree) { + var _ref18 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref17, 2); + + const pkg = _ref18[1].pkg; + + yield _this2._warnForMissingBundledDependencies(pkg); + } + })(); } - // format: name (url) <email> - const obj = {}; + determineTopLevelBinLinks(flatTree) { + const linksToCreate = new Map(); + for (const _ref19 of flatTree) { + var _ref20 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref19, 2); - let name = person.match(/^([^\(<]+)/); - if (name) { - name = name[0].trim(); - if (name) { - obj.name = name; + const dest = _ref20[0]; + var _ref20$ = _ref20[1]; + const pkg = _ref20$.pkg; + const isDirectRequire = _ref20$.isDirectRequire; + const name = pkg.name; + + + if (isDirectRequire || this.topLevelBinLinking && !linksToCreate.has(name)) { + linksToCreate.set(name, [dest, pkg]); + } } - } - const email = person.match(/<([^>]+)>/); - if (email) { - obj.email = email[1]; + return Array.from(linksToCreate.values()); } - const url = person.match(/\(([^\)]+)\)/); - if (url) { - obj.url = url[1]; + resolvePeerModules() { + for (const pkg of this.resolver.getManifests()) { + this._resolvePeerModules(pkg); + } } - return obj; -} + _resolvePeerModules(pkg) { + const peerDeps = pkg.peerDependencies; + if (!peerDeps) { + return; + } -function normalizePerson(person) { - return parsePerson(stringifyPerson(person)); -} + const ref = pkg._reference; + invariant(ref, 'Package reference is missing'); -function extractDescription(readme) { - if (typeof readme !== 'string' || readme === '') { - return undefined; - } + for (const name in peerDeps) { + const range = peerDeps[name]; + const pkgs = this.resolver.getAllInfoForPackageName(name); + const found = pkgs.find(pkg => { + var _ref21 = pkg._reference || {}; - // split into lines - const lines = readme.trim().split('\n').map(line => line.trim()); + const root = _ref21.root, + version = _ref21.version; - // find the start of the first paragraph, ignore headings - let start = 0; - for (; start < lines.length; start++) { - const line = lines[start]; - if (line && line.match(/^(#|$)/)) { - // line isn't empty and isn't a heading so this is the start of a paragraph - start++; - break; + return root && this._satisfiesPeerDependency(range, version); + }); + const foundPattern = found && found._reference && found._reference.patterns; + + if (foundPattern) { + ref.addDependencies(foundPattern); + } else { + const depError = pkgs.length > 0 ? 'incorrectPeer' : 'unmetPeer'; + const pkgHuman = `${pkg.name}@${pkg.version}`, + depHuman = `${name}@${range}`; + + this.reporter.warn(this.reporter.lang(depError, pkgHuman, depHuman)); + } } } - // skip newlines from the header to the first line - while (start < lines.length && !lines[start]) { - start++; + _satisfiesPeerDependency(range, version) { + return range === '*' || (0, (_semver || _load_semver()).satisfiesWithPreleases)(version, range, this.config.looseSemver); } - // continue to the first non empty line - let end = start; - while (end < lines.length && lines[end]) { - end++; + _warnForMissingBundledDependencies(pkg) { + var _this3 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const ref = pkg._reference; + + if (pkg.bundleDependencies) { + for (const depName of pkg.bundleDependencies) { + const loc = path.join(_this3.config.generateHardModulePath(ref), _this3.config.getFolder(pkg), depName); + if (!(yield (_fs || _load_fs()).exists(loc))) { + const pkgHuman = `${pkg.name}@${pkg.version}`; + _this3.reporter.warn(_this3.reporter.lang('missingBundledDependency', pkgHuman, depName)); + } + } + } + })(); } - return lines.slice(start, end).join(' '); -} + init(patterns, workspaceLayout) { + var _this4 = this; -function extractRepositoryUrl(repository) { - if (!repository || typeof repository !== 'object') { - return repository; + var _ref22 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + let linkDuplicates = _ref22.linkDuplicates, + ignoreOptional = _ref22.ignoreOptional; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this4.resolvePeerModules(); + yield _this4.copyModules(patterns, workspaceLayout, { linkDuplicates, ignoreOptional }); + })(); } - return repository.url; } +exports.default = PackageLinker; /***/ }), -/* 131 */ +/* 160 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -47504,6530 +49503,7150 @@ function extractRepositoryUrl(repository) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.explodeHashedUrl = explodeHashedUrl; -function explodeHashedUrl(url) { - const parts = url.split('#'); +exports.clearLine = clearLine; +exports.toStartOfLine = toStartOfLine; +exports.writeOnNthLine = writeOnNthLine; +exports.clearNthLine = clearNthLine; - return { - hash: parts[1] || '', - url: parts[0] - }; -} -/***/ }), -/* 132 */ -/***/ (function(module, exports, __webpack_require__) { +const readline = __webpack_require__(151); -"use strict"; +var _require = __webpack_require__(20); +const supportsColor = _require.supportsColor; -var buffer = __webpack_require__(76); -var Buffer = buffer.Buffer; -var SlowBuffer = buffer.SlowBuffer; -var MAX_LEN = buffer.kMaxLength || 2147483647; -exports.alloc = function alloc(size, fill, encoding) { - if (typeof Buffer.alloc === 'function') { - return Buffer.alloc(size, fill, encoding); - } - if (typeof encoding === 'number') { - throw new TypeError('encoding must not be number'); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); - } - var enc = encoding; - var _fill = fill; - if (_fill === undefined) { - enc = undefined; - _fill = 0; - } - var buf = new Buffer(size); - if (typeof _fill === 'string') { - var fillBuf = new Buffer(_fill, enc); - var flen = fillBuf.length; - var i = -1; - while (++i < size) { - buf[i] = fillBuf[i % flen]; - } - } else { - buf.fill(_fill); + +const CLEAR_WHOLE_LINE = 0; +const CLEAR_RIGHT_OF_CURSOR = 1; + +function clearLine(stdout) { + if (!supportsColor) { + return; } - return buf; + + readline.clearLine(stdout, CLEAR_WHOLE_LINE); + readline.cursorTo(stdout, 0); } -exports.allocUnsafe = function allocUnsafe(size) { - if (typeof Buffer.allocUnsafe === 'function') { - return Buffer.allocUnsafe(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); - } - if (size > MAX_LEN) { - throw new RangeError('size is too large'); + +function toStartOfLine(stdout) { + if (!supportsColor) { + return; } - return new Buffer(size); + + readline.cursorTo(stdout, 0); } -exports.from = function from(value, encodingOrOffset, length) { - if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { - return Buffer.from(value, encodingOrOffset, length); + +function writeOnNthLine(stdout, n, msg) { + if (!supportsColor) { + return; } - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); + + if (n == 0) { + readline.cursorTo(stdout, 0); + stdout.write(msg); + readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR); + return; } - if (typeof value === 'string') { - return new Buffer(value, encodingOrOffset); - } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - var offset = encodingOrOffset; - if (arguments.length === 1) { - return new Buffer(value); - } - if (typeof offset === 'undefined') { - offset = 0; - } - var len = length; - if (typeof len === 'undefined') { - len = value.byteLength - offset; - } - if (offset >= value.byteLength) { - throw new RangeError('\'offset\' is out of bounds'); - } - if (len > value.byteLength - offset) { - throw new RangeError('\'length\' is out of bounds'); - } - return new Buffer(value.slice(offset, offset + len)); - } - if (Buffer.isBuffer(value)) { - var out = new Buffer(value.length); - value.copy(out, 0, 0, value.length); - return out; - } - if (value) { - if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { - return new Buffer(value); - } - if (value.type === 'Buffer' && Array.isArray(value.data)) { - return new Buffer(value.data); - } - } - - throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); + readline.cursorTo(stdout, 0); + readline.moveCursor(stdout, 0, -n); + stdout.write(msg); + readline.clearLine(stdout, CLEAR_RIGHT_OF_CURSOR); + readline.cursorTo(stdout, 0); + readline.moveCursor(stdout, 0, n); } -exports.allocUnsafeSlow = function allocUnsafeSlow(size) { - if (typeof Buffer.allocUnsafeSlow === 'function') { - return Buffer.allocUnsafeSlow(size); - } - if (typeof size !== 'number') { - throw new TypeError('size must be a number'); + +function clearNthLine(stdout, n) { + if (!supportsColor) { + return; } - if (size >= MAX_LEN) { - throw new RangeError('size is too large'); + + if (n == 0) { + clearLine(stdout); + return; } - return new SlowBuffer(size); + readline.cursorTo(stdout, 0); + readline.moveCursor(stdout, 0, -n); + readline.clearLine(stdout, CLEAR_WHOLE_LINE); + readline.moveCursor(stdout, 0, n); } - /***/ }), -/* 133 */ -/***/ (function(module, exports) { +/* 161 */ +/***/ (function(module, exports, __webpack_require__) { -function Caseless (dict) { - this.dict = dict || {} -} -Caseless.prototype.set = function (name, value, clobber) { - if (typeof name === 'object') { - for (var i in name) { - this.set(i, name[i], value) - } - } else { - if (typeof clobber === 'undefined') clobber = true - var has = this.has(name) +"use strict"; - if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value - else this.dict[has || name] = value - return has - } -} -Caseless.prototype.has = function (name) { - var keys = Object.keys(this.dict) - , name = name.toLowerCase() - ; - for (var i=0;i<keys.length;i++) { - if (keys[i].toLowerCase() === name) return keys[i] - } - return false -} -Caseless.prototype.get = function (name) { - name = name.toLowerCase() - var result, _key - var headers = this.dict - Object.keys(headers).forEach(function (key) { - _key = key.toLowerCase() - if (name === _key) result = headers[key] - }) - return result -} -Caseless.prototype.swap = function (name) { - var has = this.has(name) - if (has === name) return - if (!has) throw new Error('There is no header than matches "'+name+'"') - this.dict[name] = this.dict[has] - delete this.dict[has] -} -Caseless.prototype.del = function (name) { - var has = this.has(name) - return delete this.dict[has || name] -} -module.exports = function (dict) {return new Caseless(dict)} -module.exports.httpify = function (resp, headers) { - var c = new Caseless(headers) - resp.setHeader = function (key, value, clobber) { - if (typeof value === 'undefined') return - return c.set(key, value, clobber) - } - resp.hasHeader = function (key) { - return c.has(key) - } - resp.getHeader = function (key) { - return c.get(key) - } - resp.removeHeader = function (key) { - return c.del(key) - } - resp.headers = c.dict - return c +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _extends2; + +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); } +var _baseReporter; -/***/ }), -/* 134 */ -/***/ (function(module, exports) { +function _load_baseReporter() { + return _baseReporter = _interopRequireDefault(__webpack_require__(77)); +} -module.exports = function(it){ - if(typeof it != 'function')throw TypeError(it + ' is not a function!'); - return it; -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 135 */ -/***/ (function(module, exports, __webpack_require__) { +class JSONReporter extends (_baseReporter || _load_baseReporter()).default { + constructor(opts) { + super(opts); -// getting tag from 19.1.3.6 Object.prototype.toString() -var cof = __webpack_require__(88) - , TAG = __webpack_require__(26)('toStringTag') - // ES3 wrong here - , ARG = cof(function(){ return arguments; }()) == 'Arguments'; + this._activityId = 0; + this._progressId = 0; + } -// fallback for IE11 Script Access Denied error -var tryGet = function(it, key){ - try { - return it[key]; - } catch(e){ /* empty */ } -}; + _dump(type, data, error) { + let stdout = this.stdout; + if (error) { + stdout = this.stderr; + } + stdout.write(`${JSON.stringify({ type, data })}\n`); + } -module.exports = function(it){ - var O, T, B; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T - // builtinTag case - : ARG ? cof(O) - // ES3 arguments fallback - : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; -}; + _verbose(msg) { + this._dump('verbose', msg); + } -/***/ }), -/* 136 */ -/***/ (function(module, exports) { + list(type, items, hints) { + this._dump('list', { type, items, hints }); + } -// 7.2.1 RequireObjectCoercible(argument) -module.exports = function(it){ - if(it == undefined)throw TypeError("Can't call method on " + it); - return it; -}; + tree(type, trees) { + this._dump('tree', { type, trees }); + } -/***/ }), -/* 137 */ -/***/ (function(module, exports, __webpack_require__) { + step(current, total, message) { + this._dump('step', { message, current, total }); + } -var isObject = __webpack_require__(91) - , document = __webpack_require__(29).document - // in old IE typeof document.createElement is 'object' - , is = isObject(document) && isObject(document.createElement); -module.exports = function(it){ - return is ? document.createElement(it) : {}; -}; + inspect(value) { + this._dump('inspect', value); + } -/***/ }), -/* 138 */ -/***/ (function(module, exports) { + footer(showPeakMemory) { + this._dump('finished', this.getTotalTime()); + } -module.exports = function(exec){ - try { - return !!exec(); - } catch(e){ - return true; + log(msg) { + this._dump('log', msg); } -}; -/***/ }), -/* 139 */ -/***/ (function(module, exports) { + command(msg) { + this._dump('command', msg); + } -module.exports = function(bitmap, value){ - return { - enumerable : !(bitmap & 1), - configurable: !(bitmap & 2), - writable : !(bitmap & 4), - value : value - }; -}; + table(head, body) { + this._dump('table', { head, body }); + } -/***/ }), -/* 140 */ -/***/ (function(module, exports, __webpack_require__) { + success(msg) { + this._dump('success', msg); + } -var def = __webpack_require__(70).f - , has = __webpack_require__(90) - , TAG = __webpack_require__(26)('toStringTag'); + error(msg) { + this._dump('error', msg, true); + } -module.exports = function(it, tag, stat){ - if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); -}; + warn(msg) { + this._dump('warning', msg, true); + } -/***/ }), -/* 141 */ -/***/ (function(module, exports, __webpack_require__) { + info(msg) { + this._dump('info', msg); + } -var shared = __webpack_require__(223)('keys') - , uid = __webpack_require__(225); -module.exports = function(key){ - return shared[key] || (shared[key] = uid(key)); -}; + activitySet(total, workers) { + if (!this.isTTY || this.noProgress) { + return super.activitySet(total, workers); + } -/***/ }), -/* 142 */ -/***/ (function(module, exports) { + const id = this._activityId++; + this._dump('activitySetStart', { id, total, workers }); -// 7.1.4 ToInteger -var ceil = Math.ceil - , floor = Math.floor; -module.exports = function(it){ - return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); -}; + const spinners = []; + for (let i = 0; i < workers; i++) { + let current = 0; + let header = ''; -/***/ }), -/* 143 */ -/***/ (function(module, exports, __webpack_require__) { + spinners.push({ + clear() {}, + setPrefix(_current, _header) { + current = _current; + header = _header; + }, + tick: msg => { + this._dump('activitySetTick', { + id, + header, + current, + worker: i, + message: msg + }); + }, + end() {} + }); + } -// to indexed object, toObject with fallback for non-array-like ES3 strings -var IObject = __webpack_require__(216) - , defined = __webpack_require__(136); -module.exports = function(it){ - return IObject(defined(it)); -}; + return { + spinners, + end: () => { + this._dump('activitySetEnd', { id }); + } + }; + } -/***/ }), -/* 144 */ -/***/ (function(module, exports, __webpack_require__) { + activity() { + return this._activity({}); + } -// 7.1.15 ToLength -var toInteger = __webpack_require__(142) - , min = Math.min; -module.exports = function(it){ - return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 -}; + _activity(data) { + if (!this.isTTY || this.noProgress) { + return { + tick() {}, + end() {} + }; + } -/***/ }), -/* 145 */ -/***/ (function(module, exports, __webpack_require__) { + const id = this._activityId++; + this._dump('activityStart', (0, (_extends2 || _load_extends()).default)({ id }, data)); -// 7.1.13 ToObject(argument) -var defined = __webpack_require__(136); -module.exports = function(it){ - return Object(defined(it)); -}; + return { + tick: name => { + this._dump('activityTick', { id, name }); + }, -/***/ }), -/* 146 */ -/***/ (function(module, exports, __webpack_require__) { + end: () => { + this._dump('activityEnd', { id }); + } + }; + } -var classof = __webpack_require__(135) - , ITERATOR = __webpack_require__(26)('iterator') - , Iterators = __webpack_require__(55); -module.exports = __webpack_require__(31).getIteratorMethod = function(it){ - if(it != undefined)return it[ITERATOR] - || it['@@iterator'] - || Iterators[classof(it)]; -}; + progress(total) { + if (this.noProgress) { + return function () { + // noop + }; + } -/***/ }), -/* 147 */ -/***/ (function(module, exports, __webpack_require__) { + const id = this._progressId++; + let current = 0; + this._dump('progressStart', { id, total }); -__webpack_require__(445); -var global = __webpack_require__(29) - , hide = __webpack_require__(54) - , Iterators = __webpack_require__(55) - , TO_STRING_TAG = __webpack_require__(26)('toStringTag'); + return () => { + current++; + this._dump('progressTick', { id, current }); -for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ - var NAME = collections[i] - , Collection = global[NAME] - , proto = Collection && Collection.prototype; - if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); - Iterators[NAME] = Iterators.Array; + if (current === total) { + this._dump('progressFinish', { id }); + } + }; + } } +exports.default = JSONReporter; /***/ }), -/* 148 */ +/* 162 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.FILE_PROTOCOL_PREFIX = undefined; -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } +var _asyncToGenerator2; - return toStr.call(arr) === '[object Array]'; -}; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } +var _path; - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } +function _load_path() { + return _path = _interopRequireDefault(__webpack_require__(0)); +} - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) { /**/ } +var _invariant; - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; +function _load_invariant() { + return _invariant = _interopRequireDefault(__webpack_require__(7)); +} -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; +var _uuid; - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { - target = {}; - } +function _load_uuid() { + return _uuid = _interopRequireDefault(__webpack_require__(88)); +} - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = target[name]; - copy = options[name]; +var _errors; - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } +function _load_errors() { + return _errors = __webpack_require__(3); +} - // Never move original objects, clone them - target[name] = extend(deep, clone, copy); +var _exoticResolver; - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - target[name] = copy; - } - } - } - } - } +function _load_exoticResolver() { + return _exoticResolver = _interopRequireDefault(__webpack_require__(61)); +} - // Return the modified object - return target; -}; +var _misc; +function _load_misc() { + return _misc = _interopRequireWildcard(__webpack_require__(10)); +} -/***/ }), -/* 149 */ -/***/ (function(module, exports, __webpack_require__) { +var _fs; -"use strict"; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} -const escapeStringRegexp = __webpack_require__(231); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -const platform = process.platform; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const main = { - tick: '✔', - cross: '✖', - star: '★', - square: 'â–‡', - squareSmall: 'â—»', - squareSmallFilled: 'â—¼', - play: 'â–¶', - circle: 'â—¯', - circleFilled: 'â—‰', - circleDotted: 'â—Œ', - circleDouble: 'â—Ž', - circleCircle: 'â“ž', - circleCross: 'ⓧ', - circlePipe: 'â’¾', - circleQuestionMark: '?âƒ', - bullet: 'â—', - dot: '․', - line: '─', - ellipsis: '…', - pointer: 'â¯', - pointerSmall: '›', - info: 'ℹ', - warning: 'âš ', - hamburger: '☰', - smiley: 'ã‹¡', - mustache: 'à·´', - heart: '♥', - arrowUp: '↑', - arrowDown: '↓', - arrowLeft: 'â†', - arrowRight: '→', - radioOn: 'â—‰', - radioOff: 'â—¯', - checkboxOn: '☒', - checkboxOff: 'â˜', - checkboxCircleOn: 'ⓧ', - checkboxCircleOff: 'â’¾', - questionMarkPrefix: '?âƒ', - oneHalf: '½', - oneThird: 'â…“', - oneQuarter: '¼', - oneFifth: 'â…•', - oneSixth: 'â…™', - oneSeventh: 'â…', - oneEighth: 'â…›', - oneNinth: 'â…‘', - oneTenth: 'â…’', - twoThirds: 'â…”', - twoFifths: 'â…–', - threeQuarters: '¾', - threeFifths: 'â…—', - threeEighths: 'â…œ', - fourFifths: 'â…˜', - fiveSixths: 'â…š', - fiveEighths: 'â…', - sevenEighths: 'â…ž' -}; +const FILE_PROTOCOL_PREFIX = exports.FILE_PROTOCOL_PREFIX = 'file:'; -const win = { - tick: '√', - cross: '×', - star: '*', - square: 'â–ˆ', - squareSmall: '[ ]', - squareSmallFilled: '[â–ˆ]', - play: 'â–º', - circle: '( )', - circleFilled: '(*)', - circleDotted: '( )', - circleDouble: '( )', - circleCircle: '(â—‹)', - circleCross: '(×)', - circlePipe: '(│)', - circleQuestionMark: '(?)', - bullet: '*', - dot: '.', - line: '─', - ellipsis: '...', - pointer: '>', - pointerSmall: '»', - info: 'i', - warning: '‼', - hamburger: '≡', - smiley: '☺', - mustache: '┌─â”', - heart: main.heart, - arrowUp: main.arrowUp, - arrowDown: main.arrowDown, - arrowLeft: main.arrowLeft, - arrowRight: main.arrowRight, - radioOn: '(*)', - radioOff: '( )', - checkboxOn: '[×]', - checkboxOff: '[ ]', - checkboxCircleOn: '(×)', - checkboxCircleOff: '( )', - questionMarkPrefix: '?', - oneHalf: '1/2', - oneThird: '1/3', - oneQuarter: '1/4', - oneFifth: '1/5', - oneSixth: '1/6', - oneSeventh: '1/7', - oneEighth: '1/8', - oneNinth: '1/9', - oneTenth: '1/10', - twoThirds: '2/3', - twoFifths: '2/5', - threeQuarters: '3/4', - threeFifths: '3/5', - threeEighths: '3/8', - fourFifths: '4/5', - fiveSixths: '5/6', - fiveEighths: '5/8', - sevenEighths: '7/8' -}; +class FileResolver extends (_exoticResolver || _load_exoticResolver()).default { + constructor(request, fragment) { + super(request, fragment); + this.loc = (_misc || _load_misc()).removePrefix(fragment, FILE_PROTOCOL_PREFIX); + } -if (platform === 'linux') { - // the main one doesn't look that good on Ubuntu - main.questionMarkPrefix = '?'; -} + static isVersion(pattern) { + return super.isVersion.call(this, pattern) || this.prefixMatcher.test(pattern) || (_path || _load_path()).default.isAbsolute(pattern); + } -const figures = platform === 'win32' ? win : main; + resolve() { + var _this = this; -const fn = str => { - if (figures === main) { - return str; - } + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let loc = _this.loc; + if (!(_path || _load_path()).default.isAbsolute(loc)) { + loc = (_path || _load_path()).default.resolve(_this.config.lockfileFolder, loc); + } - Object.keys(main).forEach(key => { - if (main[key] === figures[key]) { - return; - } + if (_this.config.linkFileDependencies) { + const registry = 'npm'; + const manifest = { _uid: '', name: '', version: '0.0.0', _registry: registry }; + manifest._remote = { + type: 'link', + registry, + hash: null, + reference: loc + }; + manifest._uid = manifest.version; + return manifest; + } + if (!(yield (_fs || _load_fs()).exists(loc))) { + throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('doesntExist', loc)); + } - str = str.replace(new RegExp(escapeStringRegexp(main[key]), 'g'), figures[key]); - }); + const manifest = yield (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + try { + return yield _this.config.readManifest(loc, _this.registry); + } catch (e) { + if (e.code === 'ENOENT') { + return { + // This is just the default, it can be overridden with key of dependencies + name: (_path || _load_path()).default.dirname(loc), + version: '0.0.0', + _uid: '0.0.0', + _registry: 'npm' + }; + } - return str; -}; + throw e; + } + })(); + const registry = manifest._registry; + (0, (_invariant || _load_invariant()).default)(registry, 'expected registry'); -module.exports = Object.assign(fn, figures); + manifest._remote = { + type: 'copy', + registry, + hash: `${(_uuid || _load_uuid()).default.v4()}-${new Date().getTime()}`, + reference: loc + }; + + manifest._uid = manifest.version; + return manifest; + })(); + } +} +exports.default = FileResolver; +FileResolver.protocol = 'file'; +FileResolver.prefixMatcher = /^.{1,2}\//; /***/ }), -/* 150 */ +/* 163 */ /***/ (function(module, exports, __webpack_require__) { -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. +"use strict"; -module.exports = glob -var fs = __webpack_require__(6) -var rp = __webpack_require__(233) -var minimatch = __webpack_require__(159) -var Minimatch = minimatch.Minimatch -var inherits = __webpack_require__(37) -var EE = __webpack_require__(49).EventEmitter -var path = __webpack_require__(1) -var assert = __webpack_require__(22) -var isAbsolute = __webpack_require__(161) -var globSync = __webpack_require__(478) -var common = __webpack_require__(234) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __webpack_require__(514) -var util = __webpack_require__(2) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.explodeGistFragment = explodeGistFragment; -var once = __webpack_require__(104) +var _errors; -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} +function _load_errors() { + return _errors = __webpack_require__(3); +} - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) - } +var _gitResolver; - return new Glob(pattern, options, cb) +function _load_gitResolver() { + return _gitResolver = _interopRequireDefault(__webpack_require__(96)); } -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync +var _exoticResolver; -// old api surface -glob.glob = glob +function _load_exoticResolver() { + return _exoticResolver = _interopRequireDefault(__webpack_require__(61)); +} -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } +var _misc; - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] - } - return origin +function _load_misc() { + return _misc = _interopRequireWildcard(__webpack_require__(10)); } -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - var g = new Glob(pattern, options) - var set = g.minimatch.set +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (!pattern) - return false +function explodeGistFragment(fragment, reporter) { + fragment = (_misc || _load_misc()).removePrefix(fragment, 'gist:'); - if (set.length > 1) - return true + const parts = fragment.split('#'); - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true + if (parts.length <= 2) { + return { + id: parts[0], + hash: parts[1] || '' + }; + } else { + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidGistFragment', fragment)); } - - return false } -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) - } +class GistResolver extends (_exoticResolver || _load_exoticResolver()).default { - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) + constructor(request, fragment) { + super(request, fragment); - setopts(this, pattern, options) - this._didRealPath = false + var _explodeGistFragment = explodeGistFragment(fragment, this.reporter); - // process each pattern in the minimatch set - var n = this.minimatch.set.length + const id = _explodeGistFragment.id, + hash = _explodeGistFragment.hash; - // The matches are stored as {<filename>: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) + this.id = id; + this.hash = hash; + } - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) + resolve() { + return this.fork((_gitResolver || _load_gitResolver()).default, false, `https://gist.github.com/${this.id}.git#${this.hash}`); } +} +exports.default = GistResolver; +GistResolver.protocol = 'gist'; - var self = this - this._processing = 0 +/***/ }), +/* 164 */ +/***/ (function(module, exports, __webpack_require__) { - this._emitQueue = [] - this._processQueue = [] - this.paused = false +"use strict"; - if (this.noprocess) - return this - if (n === 0) - return done() +Object.defineProperty(exports, "__esModule", { + value: true +}); - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) - } - sync = false +var _asyncToGenerator2; - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } - } - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - - if (this.realpath && !this._didRealpath) - return this._realpath() +var _errors; - common.finish(this) - this.emit('end', this.found) +function _load_errors() { + return _errors = __webpack_require__(3); } -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - - this._didRealpath = true - - var n = this.matches.length - if (n === 0) - return this._finish() - - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) +var _registryResolver; - function next () { - if (--n === 0) - self._finish() - } +function _load_registryResolver() { + return _registryResolver = _interopRequireDefault(__webpack_require__(433)); } -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() - - var found = Object.keys(matchset) - var self = this - var n = found.length +var _npmRegistry; - if (n === 0) - return cb() +function _load_npmRegistry() { + return _npmRegistry = _interopRequireDefault(__webpack_require__(52)); +} - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here +var _npmRegistry2; - if (--n === 0) { - self.matches[index] = set - cb() - } - }) - }) +function _load_npmRegistry2() { + return _npmRegistry2 = __webpack_require__(52); } -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} +var _map; -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); } -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} +var _fs; -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } - } - } +var _constants; + +function _load_constants() { + return _constants = __webpack_require__(6); } -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (this.aborted) - return +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return - } +const inquirer = __webpack_require__(212); - //console.error('PROCESS %d', this._processing, pattern) +const tty = __webpack_require__(90); +const invariant = __webpack_require__(7); +const path = __webpack_require__(0); - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. +const NPM_REGISTRY = /http[s]:\/\/registry.npmjs.org/g; +const NPM_REGISTRY_ID = 'npm'; - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return +class NpmResolver extends (_registryResolver || _load_registryResolver()).default { - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + static findVersionInRegistryResponse(config, range, body, request) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (!body['dist-tags']) { + throw new (_errors || _load_errors()).MessageError(config.reporter.lang('malformedRegistryResponse', body.name)); + } - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break + if (range in body['dist-tags']) { + range = body['dist-tags'][range]; + } + + const satisfied = yield config.resolveConstraints(Object.keys(body.versions), range); + if (satisfied) { + return body.versions[satisfied]; + } else if (request && !config.nonInteractive) { + if (request.resolver && request.resolver.activity) { + request.resolver.activity.end(); + } + config.reporter.log(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range)); + let pageSize; + if (process.stdout instanceof tty.WriteStream) { + pageSize = process.stdout.rows - 2; + } + const response = yield inquirer.prompt([{ + name: 'package', + type: 'list', + message: config.reporter.lang('chooseVersionFromList', body.name), + choices: Object.keys(body.versions).reverse(), + pageSize + }]); + if (response && response.package) { + return body.versions[response.package]; + } + } + throw new (_errors || _load_errors()).MessageError(config.reporter.lang('couldntFindVersionThatMatchesRange', body.name, range)); + })(); } - var remain = pattern.slice(n) + resolveRequest() { + var _this = this; - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (_this.config.offline) { + const res = yield _this.resolveRequestOffline(); + if (res != null) { + return res; + } + } - var abs = this._makeAbs(read) + const body = yield _this.config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(_this.name)); - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() + if (body) { + return NpmResolver.findVersionInRegistryResponse(_this.config, _this.range, body, _this.request); + } else { + return null; + } + })(); + } - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) -} + resolveRequestOffline() { + var _this2 = this; -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const escapedName = (_npmRegistry || _load_npmRegistry()).default.escapeName(_this2.name); + const scope = _this2.config.registries.npm.getScope(escapedName); -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + // find modules of this name + const prefix = scope ? escapedName.split((_npmRegistry2 || _load_npmRegistry2()).SCOPE_SEPARATOR)[1] : `${NPM_REGISTRY_ID}-${_this2.name}-`; - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() + invariant(_this2.config.cacheFolder, 'expected packages root'); + const cacheFolder = path.join(_this2.config.cacheFolder, scope ? `${NPM_REGISTRY_ID}-${scope}` : ''); - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + const files = yield _this2.config.getCache('cachedPackages', (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const files = yield (_fs || _load_fs()).readdir(cacheFolder); + const validFiles = []; - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } - } + for (const name of files) { + // no hidden files + if (name[0] === '.') { + continue; + } - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + // ensure valid module cache + const dir = path.join(cacheFolder, name); + if (yield _this2.config.isValidModuleDest(dir)) { + validFiles.push(name); + } + } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() + return validFiles; + })); - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + const versions = (0, (_map || _load_map()).default)(); - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + for (const name of files) { + // check if folder starts with our prefix + if (name.indexOf(prefix) !== 0) { + continue; + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e + const dir = path.join(cacheFolder, name); + + // read manifest and validate correct name + const pkg = yield _this2.config.readManifest(dir, NPM_REGISTRY_ID); + if (pkg.name !== _this2.name) { + continue; + } + + // read package metadata + const metadata = yield _this2.config.readPackageMetadata(dir); + if (!metadata.remote) { + continue; // old yarn metadata + } + + versions[pkg.version] = Object.assign({}, pkg, { + _remote: metadata.remote + }); } - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) + const satisfied = yield _this2.config.resolveConstraints(Object.keys(versions), _this2.range); + if (satisfied) { + return versions[satisfied]; + } else if (!_this2.config.preferOffline) { + throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('couldntFindPackageInCache', _this2.name, _this2.range, Object.keys(versions).join(', '))); + } else { + return null; } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return cb() + })(); } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e + cleanRegistry(url) { + if (this.config.getOption('registry') === (_constants || _load_constants()).YARN_REGISTRY) { + return url.replace(NPM_REGISTRY, (_constants || _load_constants()).YARN_REGISTRY); + } else { + return url; } - this._process([e].concat(remain), index, inGlobStar, cb) } - cb() -} -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return + resolve() { + var _this3 = this; - if (isIgnored(this, e)) - return + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // lockfile + const shrunk = _this3.request.getLocked('tarball'); + if (shrunk) { + return shrunk; + } - if (this.paused) { - this._emitQueue.push([index, e]) - return - } + const info = yield _this3.resolveRequest(); + if (info == null) { + throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('packageNotFoundRegistry', _this3.name, NPM_REGISTRY_ID)); + } - var abs = isAbsolute(e) ? e : this._makeAbs(e) + const deprecated = info.deprecated, + dist = info.dist; - if (this.mark) - e = this._mark(e) + if (typeof deprecated === 'string') { + let human = `${info.name}@${info.version}`; + const parentNames = _this3.request.parentNames; + if (parentNames.length) { + human = parentNames.concat(human).join(' > '); + } + _this3.reporter.warn(`${human}: ${deprecated}`); + } - if (this.absolute) - e = abs + if (dist != null && dist.tarball) { + info._remote = { + resolved: `${_this3.cleanRegistry(dist.tarball)}#${dist.shasum}`, + type: 'tarball', + reference: _this3.cleanRegistry(dist.tarball), + hash: dist.shasum, + registry: NPM_REGISTRY_ID, + packageName: info.name + }; + } - if (this.matches[index][e]) - return + info._uid = info.version; - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return + return info; + })(); } - - this.matches[index][e] = true - - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) - - this.emit('match', e) } +exports.default = NpmResolver; +NpmResolver.registry = NPM_REGISTRY_ID; -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return - - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) +/***/ }), +/* 165 */ +/***/ (function(module, exports, __webpack_require__) { - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) +"use strict"; - if (lstatcb) - fs.lstat(abs, lstatcb) - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() +Object.defineProperty(exports, "__esModule", { + value: true +}); - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym +var _slicedToArray2; - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) - } +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return +var _asyncToGenerator2; - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) +var _errors; - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() +function _load_errors() { + return _errors = __webpack_require__(3); +} - if (Array.isArray(c)) - return cb(null, c) - } +var _gitSpawn; - var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) +function _load_gitSpawn() { + return _gitSpawn = __webpack_require__(274); } -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) - } -} +var _gitRefResolver; -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return +function _load_gitRefResolver() { + return _gitRefResolver = __webpack_require__(436); +} - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } - } +var _crypto; - this.cache[abs] = entries - return cb(null, entries) +function _load_crypto() { + return _crypto = _interopRequireWildcard(__webpack_require__(123)); } -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return - - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break +var _fs; - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() - } - if (!this.silent) - console.error('glob error', er) - break - } +var _map; - return cb() +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); } -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) +var _fs2; + +function _load_fs2() { + return _fs2 = __webpack_require__(5); } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() +const invariant = __webpack_require__(7); - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) +const StringDecoder = __webpack_require__(229).StringDecoder; +const tarFs = __webpack_require__(145); +const tarStream = __webpack_require__(322); +const url = __webpack_require__(14); - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) - var isSym = this.symlinks[abs] - var len = entries.length +const supportsArchiveCache = (0, (_map || _load_map()).default)({ + 'github.com': false }); - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() +const handleSpawnError = err => { + if (err instanceof (_errors || _load_errors()).ProcessSpawnError) { + throw err; + } +}; - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue +class Git { + constructor(config, gitUrl, hash) { + this.supportsArchive = false; + this.fetched = false; + this.config = config; + this.reporter = config.reporter; + this.hash = hash; + this.ref = hash; + this.gitUrl = gitUrl; + this.cwd = this.config.getTemp((_crypto || _load_crypto()).hash(this.gitUrl.repository)); + } - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) + /** + * npm URLs contain a 'git+' scheme prefix, which is not understood by git. + * git "URLs" also allow an alternative scp-like syntax, so they're not standard URLs. + */ + static npmUrlToGitUrl(npmUrl) { + // Expand shortened format first if needed + npmUrl = npmUrl.replace(/^github:/, 'git+ssh://git@github.com/'); - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) + // Special case in npm, where ssh:// prefix is stripped to pass scp-like syntax + // which in git works as remote path only if there are no slashes before ':'. + const match = npmUrl.match(/^git\+ssh:\/\/((?:[^@:\/]+@)?([^@:\/]+):([^/]*).*)/); + // Additionally, if the host part is digits-only, npm falls back to + // interpreting it as an SSH URL with a port number. + if (match && /[^0-9]/.test(match[3])) { + return { + hostname: match[2], + protocol: 'ssh:', + repository: match[1] + }; + } + + const repository = npmUrl.replace(/^git\+/, ''); + const parsed = url.parse(repository); + return { + hostname: parsed.hostname || null, + protocol: parsed.protocol || 'file:', + repository + }; } - cb() -} + /** + * Check if the host specified in the input `gitUrl` has archive capability. + */ -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) -} -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + static hasArchiveCapability(ref) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const hostname = ref.hostname; + if (ref.protocol !== 'ssh:' || hostname == null) { + return false; + } - //console.error('ps2', prefix, exists) + if (hostname in supportsArchiveCache) { + return supportsArchiveCache[hostname]; + } - if (!this.matches[index]) - this.matches[index] = Object.create(null) + try { + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['archive', `--remote=${ref.repository}`, 'HEAD', Date.now() + '']); + throw new Error(); + } catch (err) { + handleSpawnError(err); + const supports = err.message.indexOf('did not match any files') >= 0; + return supportsArchiveCache[hostname] = supports; + } + })(); + } - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() + /** + * Check if the input `target` is a 5-40 character hex commit hash. + */ - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } + static repoExists(ref) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + try { + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['ls-remote', '-t', ref.repository]); + return true; + } catch (err) { + handleSpawnError(err); + return false; + } + })(); } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') - - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} - -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - - if (f.length > this.maxLength) - return cb() - - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + static replaceProtocol(ref, protocol) { + return { + hostname: ref.hostname, + protocol, + repository: ref.repository.replace(/^(?:git|http):/, protocol) + }; + } - if (Array.isArray(c)) - c = 'DIR' + /** + * Attempt to upgrade insecure protocols to secure protocol + */ + static secureGitUrl(ref, hash, reporter) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if ((0, (_gitRefResolver || _load_gitRefResolver()).isCommitSha)(hash)) { + // this is cryptographically secure + return ref; + } - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) + if (ref.protocol === 'git:') { + const secureUrl = Git.replaceProtocol(ref, 'https:'); + if (yield Git.repoExists(secureUrl)) { + return secureUrl; + } else { + throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadGitWithoutCommit', ref)); + } + } - if (needDir && c === 'FILE') - return cb() + if (ref.protocol === 'http:') { + const secureRef = Git.replaceProtocol(ref, 'https:'); + if (yield Git.repoExists(secureRef)) { + return secureRef; + } else { + if (yield Git.repoExists(ref)) { + return ref; + } else { + throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadHTTPWithoutCommit', ref)); + } + } + } - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } + if (ref.protocol === 'https:') { + if (yield Git.repoExists(ref)) { + return ref; + } else { + throw new (_errors || _load_errors()).SecurityError(reporter.lang('refusingDownloadHTTPSWithoutCommit', ref)); + } + } - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } + return ref; + })(); } - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - fs.lstat(abs, statcb) + /** + * Archive a repo to destination + */ - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) + archive(dest) { + if (this.supportsArchive) { + return this._archiveViaRemoteArchive(dest); } else { - self._stat2(f, abs, er, lstat, cb) + return this._archiveViaLocalFetched(dest); } } -} - -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat + _archiveViaRemoteArchive(dest) { + var _this = this; - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const hashStream = new (_crypto || _load_crypto()).HashStream(); + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['archive', `--remote=${_this.gitUrl.repository}`, _this.ref], { + process(proc, resolve, reject, done) { + const writeStream = (0, (_fs2 || _load_fs2()).createWriteStream)(dest); + proc.on('error', reject); + writeStream.on('error', reject); + writeStream.on('end', done); + writeStream.on('open', function () { + proc.stdout.pipe(hashStream).pipe(writeStream); + }); + writeStream.once('finish', done); + } + }); + return hashStream.getHash(); + })(); + } - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c + _archiveViaLocalFetched(dest) { + var _this2 = this; - if (needDir && c === 'FILE') - return cb() + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const hashStream = new (_crypto || _load_crypto()).HashStream(); + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['archive', _this2.hash], { + cwd: _this2.cwd, + process(proc, resolve, reject, done) { + const writeStream = (0, (_fs2 || _load_fs2()).createWriteStream)(dest); + proc.on('error', reject); + writeStream.on('error', reject); + writeStream.on('open', function () { + proc.stdout.pipe(hashStream).pipe(writeStream); + }); + writeStream.once('finish', done); + } + }); + return hashStream.getHash(); + })(); + } - return cb(null, c, stat) -} + /** + * Clone a repo to the input `dest`. Use `git archive` if it's available, otherwise fall + * back to `git clone`. + */ + clone(dest) { + if (this.supportsArchive) { + return this._cloneViaRemoteArchive(dest); + } else { + return this._cloneViaLocalFetched(dest); + } + } -/***/ }), -/* 151 */ -/***/ (function(module, exports, __webpack_require__) { + _cloneViaRemoteArchive(dest) { + var _this3 = this; -// Load modules + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['archive', `--remote=${_this3.gitUrl.repository}`, _this3.ref], { + process(proc, update, reject, done) { + const extractor = tarFs.extract(dest, { + dmode: 0o555, // all dirs should be readable + fmode: 0o444 }); + extractor.on('error', reject); + extractor.on('finish', done); -var Crypto = __webpack_require__(7); -var Url = __webpack_require__(11); -var Utils = __webpack_require__(94); + proc.stdout.pipe(extractor); + proc.on('error', reject); + } + }); + })(); + } + _cloneViaLocalFetched(dest) { + var _this4 = this; -// Declare internals + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['archive', _this4.hash], { + cwd: _this4.cwd, + process(proc, resolve, reject, done) { + const extractor = tarFs.extract(dest, { + dmode: 0o555, // all dirs should be readable + fmode: 0o444 }); -var internals = {}; + extractor.on('error', reject); + extractor.on('finish', done); + proc.stdout.pipe(extractor); + } + }); + })(); + } -// MAC normalization format version + /** + * Clone this repo. + */ -exports.headerVersion = '1'; // Prevent comparison of mac values generated with different normalized string formats + fetch() { + var _this5 = this; + const gitUrl = this.gitUrl, + cwd = this.cwd; -// Supported HMAC algorithms -exports.algorithms = ['sha1', 'sha256']; + return (_fs || _load_fs()).lockQueue.push(gitUrl.repository, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (yield (_fs || _load_fs()).exists(cwd)) { + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['pull'], { cwd }); + } else { + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['clone', gitUrl.repository, cwd]); + } + _this5.fetched = true; + })); + } -// Calculate the request MAC + /** + * Fetch the file by cloning the repo and reading it. + */ -/* - type: 'header', // 'header', 'bewit', 'response' - credentials: { - key: 'aoijedoaijsdlaksjdl', - algorithm: 'sha256' // 'sha1', 'sha256' - }, - options: { - method: 'GET', - resource: '/resource?a=1&b=2', - host: 'example.com', - port: 8080, - ts: 1357718381034, - nonce: 'd3d345f', - hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=', - ext: 'app-specific-data', - app: 'hf48hd83qwkj', // Application id (Oz) - dlg: 'd8djwekds9cj' // Delegated by application id (Oz), requires options.app + getFile(filename) { + if (this.supportsArchive) { + return this._getFileFromArchive(filename); + } else { + return this._getFileFromClone(filename); } -*/ - -exports.calculateMac = function (type, credentials, options) { - - var normalized = exports.generateNormalizedString(type, options); - - var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized); - var digest = hmac.digest('base64'); - return digest; -}; - - -exports.generateNormalizedString = function (type, options) { - - var resource = options.resource || ''; - if (resource && - resource[0] !== '/') { + } - var url = Url.parse(resource, false); - resource = url.path; // Includes query - } + _getFileFromArchive(filename) { + var _this6 = this; - var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' + - options.ts + '\n' + - options.nonce + '\n' + - (options.method || '').toUpperCase() + '\n' + - resource + '\n' + - options.host.toLowerCase() + '\n' + - options.port + '\n' + - (options.hash || '') + '\n'; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + try { + return yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['archive', `--remote=${_this6.gitUrl.repository}`, _this6.ref, filename], { + process(proc, update, reject, done) { + const parser = tarStream.extract(); - if (options.ext) { - normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n'); - } + parser.on('error', reject); + parser.on('finish', done); - normalized += '\n'; + parser.on('entry', (header, stream, next) => { + const decoder = new StringDecoder('utf8'); + let fileContent = ''; - if (options.app) { - normalized += options.app + '\n' + - (options.dlg || '') + '\n'; - } + stream.on('data', buffer => { + fileContent += decoder.write(buffer); + }); + stream.on('end', () => { + const remaining = decoder.end(); + update(fileContent + remaining); + next(); + }); + stream.resume(); + }); - return normalized; -}; + proc.stdout.pipe(parser); + } + }); + } catch (err) { + if (err.message.indexOf('did not match any files') >= 0) { + return false; + } else { + throw err; + } + } + })(); + } + _getFileFromClone(filename) { + var _this7 = this; -exports.calculatePayloadHash = function (payload, algorithm, contentType) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + invariant(_this7.fetched, 'Repo not fetched'); - var hash = exports.initializePayloadHash(algorithm, contentType); - hash.update(payload || ''); - return exports.finalizePayloadHash(hash); -}; + try { + return yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['show', `${_this7.hash}:${filename}`], { + cwd: _this7.cwd + }); + } catch (err) { + handleSpawnError(err); + // file doesn't exist + return false; + } + })(); + } + /** + * Initialize the repo, find a secure url to use and + * set the ref to match an input `target`. + */ + init() { + var _this8 = this; -exports.initializePayloadHash = function (algorithm, contentType) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this8.gitUrl = yield Git.secureGitUrl(_this8.gitUrl, _this8.hash, _this8.reporter); - var hash = Crypto.createHash(algorithm); - hash.update('hawk.' + exports.headerVersion + '.payload\n'); - hash.update(Utils.parseContentType(contentType) + '\n'); - return hash; -}; + yield _this8.setRefRemote(); + // check capabilities + if (_this8.ref !== '' && (yield Git.hasArchiveCapability(_this8.gitUrl))) { + _this8.supportsArchive = true; + } else { + yield _this8.fetch(); + } -exports.finalizePayloadHash = function (hash) { + return _this8.hash; + })(); + } - hash.update('\n'); - return hash.digest('base64'); -}; + setRefRemote() { + var _this9 = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const stdout = yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['ls-remote', '--tags', '--heads', _this9.gitUrl.repository]); + const refs = (0, (_gitRefResolver || _load_gitRefResolver()).parseRefs)(stdout); + return _this9.setRef(refs); + })(); + } -exports.calculateTsMac = function (ts, credentials) { + setRefHosted(hostedRefsList) { + const refs = (0, (_gitRefResolver || _load_gitRefResolver()).parseRefs)(hostedRefsList); + return this.setRef(refs); + } - var hmac = Crypto.createHmac(credentials.algorithm, credentials.key); - hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n'); - return hmac.digest('base64'); -}; + /** + * Resolves the default branch of a remote repository (not always "master") + */ + resolveDefaultBranch() { + var _this10 = this; -exports.timestampMessage = function (credentials, localtimeOffsetMsec) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + try { + const stdout = yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['ls-remote', '--symref', _this10.gitUrl.repository, 'HEAD']); + const lines = stdout.split('\n'); - var now = Utils.nowSecs(localtimeOffsetMsec); - var tsm = exports.calculateTsMac(now, credentials); - return { ts: now, tsm: tsm }; -}; + var _lines$0$split = lines[0].split(/\s+/), + _lines$0$split2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_lines$0$split, 2); + const ref = _lines$0$split2[1]; -/***/ }), -/* 152 */ -/***/ (function(module, exports, __webpack_require__) { + var _lines$1$split = lines[1].split(/\s+/), + _lines$1$split2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_lines$1$split, 1); -/** - * Inquirer.js - * A collection of common interactive command line user interfaces. - */ + const sha = _lines$1$split2[0]; -var inquirer = module.exports; + return { sha, ref }; + } catch (err) { + handleSpawnError(err); + // older versions of git don't support "--symref" + const stdout = yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['ls-remote', _this10.gitUrl.repository, 'HEAD']); -/** - * Client interfaces - */ + var _stdout$split = stdout.split(/\s+/), + _stdout$split2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_stdout$split, 1); -inquirer.prompts = {}; + const sha = _stdout$split2[0]; -inquirer.Separator = __webpack_require__(98); + return { sha, ref: undefined }; + } + })(); + } -inquirer.ui = { - BottomBar: __webpack_require__(527), - Prompt: __webpack_require__(528) -}; + /** + * Resolve a git commit to it's 40-chars format and ensure it exists in the repository + * We need to use the 40-chars format to avoid multiple folders in the cache + */ -/** - * Create a new self-contained prompt module. - */ -inquirer.createPromptModule = function (opt) { - var promptModule = function (questions) { - var ui = new inquirer.ui.Prompt(promptModule.prompts, opt); - var promise = ui.run(questions); + resolveCommit(shaToResolve) { + var _this11 = this; - // Monkey patch the UI on the promise object so - // that it remains publicly accessible. - promise.ui = ui; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + try { + yield _this11.fetch(); + const revListArgs = ['rev-list', '-n', '1', '--no-abbrev-commit', '--format=oneline', shaToResolve]; + const stdout = yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(revListArgs, { cwd: _this11.cwd }); - return promise; - }; - promptModule.prompts = {}; + var _stdout$split3 = stdout.split(/\s+/), + _stdout$split4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_stdout$split3, 1); - /** - * Register a prompt type - * @param {String} name Prompt type name - * @param {Function} prompt Prompt constructor - * @return {inquirer} - */ + const sha = _stdout$split4[0]; - promptModule.registerPrompt = function (name, prompt) { - promptModule.prompts[name] = prompt; - return this; - }; + return { sha, ref: undefined }; + } catch (err) { + handleSpawnError(err); + // assuming commit not found, let's try something else + return null; + } + })(); + } /** - * Register the defaults provider prompts + * Resolves the input hash / ref / semver range to a valid commit sha + * If possible also resolves the sha to a valid ref in order to use "git archive" */ - promptModule.restoreDefaultPrompts = function () { - this.registerPrompt('list', __webpack_require__(524)); - this.registerPrompt('input', __webpack_require__(523)); - this.registerPrompt('confirm', __webpack_require__(520)); - this.registerPrompt('rawlist', __webpack_require__(526)); - this.registerPrompt('expand', __webpack_require__(522)); - this.registerPrompt('checkbox', __webpack_require__(519)); - this.registerPrompt('password', __webpack_require__(525)); - this.registerPrompt('editor', __webpack_require__(521)); - }; - - promptModule.restoreDefaultPrompts(); - - return promptModule; -}; + setRef(refs) { + var _this12 = this; -/** - * Public CLI helper interface - * @param {Array|Object|rx.Observable} questions - Questions settings array - * @param {Function} cb - Callback being passed the user answers - * @return {inquirer.ui.Prompt} - */ + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + // get commit ref + const version = _this12.hash; -inquirer.prompt = inquirer.createPromptModule(); -// Expose helper functions on the top level for easiest usage by common users -inquirer.registerPrompt = function (name, prompt) { - inquirer.prompt.registerPrompt(name, prompt); -}; -inquirer.restoreDefaultPrompts = function () { - inquirer.prompt.restoreDefaultPrompts(); -}; + const resolvedResult = yield (0, (_gitRefResolver || _load_gitRefResolver()).resolveVersion)({ + config: _this12.config, + git: _this12, + version, + refs + }); + if (!resolvedResult) { + throw new (_errors || _load_errors()).MessageError(_this12.reporter.lang('couldntFindMatch', version, Object.keys(refs).join(','), _this12.gitUrl.repository)); + } + _this12.hash = resolvedResult.sha; + _this12.ref = resolvedResult.ref || ''; + return _this12.hash; + })(); + } +} +exports.default = Git; /***/ }), -/* 153 */ +/* 166 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = __webpack_require__(408).isCI +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = guessName; +var _url; -/***/ }), -/* 154 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_url() { + return _url = _interopRequireDefault(__webpack_require__(14)); +} -"use strict"; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function cleanup(name) { + name = name.replace(/-\d+\.\d+\.\d+/, ''); + return name.split('.')[0]; +} -/* - * Copyright (c) 2014 Mega Limited - * under the MIT License. - * - * Authors: Guy K. Kloss - * - * You should have received a copy of the license along with this program. - */ +function guessNameFallback(source) { + // If cannot parse as url, just return cleaned up last part + const parts = source.split('/'); + return cleanup(parts[parts.length - 1]); +} -var dh = __webpack_require__(544); -var eddsa = __webpack_require__(545); -var curve255 = __webpack_require__(155); -var utils = __webpack_require__(103); - - /** - * @exports jodid25519 - * Curve 25519-based cryptography collection. - * - * @description - * EC Diffie-Hellman (ECDH) based on Curve25519 and digital signatures - * (EdDSA) based on Ed25519. - */ - var ns = {}; - - /** Module version indicator as string (format: [major.minor.patch]). */ - ns.VERSION = '0.7.1'; +function guessName(source) { + try { + const parsed = (_url || _load_url()).default.parse(source); - ns.dh = dh; - ns.eddsa = eddsa; - ns.curve255 = curve255; - ns.utils = utils; + if (!parsed.pathname) { + return guessNameFallback(source); + } -module.exports = ns; + const parts = parsed.pathname.split('/'); + // Priority goes to part that ends with .git + for (const part of parts) { + if (part.match(/\.git$/)) { + return cleanup(part); + } + } + + // Most likely a directory + if (parsed.host == null) { + return cleanup(parts[parts.length - 1]); + } + + // A site like github or gitlab + if (parts.length > 2) { + return cleanup(parts[2]); + } + + // Privately hosted package? + if (parts.length > 1) { + return cleanup(parts[1]); + } + + return guessNameFallback(source); + } catch (e) { + return guessNameFallback(source); + } +} /***/ }), -/* 155 */ +/* 167 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/** - * @fileOverview - * Core operations on curve 25519 required for the higher level modules. - */ -/* - * Copyright (c) 2007, 2013, 2014 Michele Bini - * Copyright (c) 2014 Mega Limited - * under the MIT License. - * - * Authors: Guy K. Kloss, Michele Bini - * - * You should have received a copy of the license along with this program. - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); -var core = __webpack_require__(102); -var utils = __webpack_require__(103); +var _asyncToGenerator2; - /** - * @exports jodid25519/curve255 - * Legacy compatibility module for Michele Bini's previous curve255.js. - * - * @description - * Legacy compatibility module for Michele Bini's previous curve255.js. - * - * <p> - * This code presents an API with all key formats as previously available - * from Michele Bini's curve255.js implementation. - * </p> - */ - var ns = {}; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - function curve25519_raw(f, c) { - var a, x_1, q; +var _resolveRelative; - x_1 = c; - a = core.dbl(x_1, core.ONE()); - q = [x_1, core.ONE()]; +function _load_resolveRelative() { + return _resolveRelative = _interopRequireDefault(__webpack_require__(441)); +} - var n = 255; +var _validate; - while (core.getbit(f, n) == 0) { - n--; - // For correct constant-time operation, bit 255 should always be - // set to 1 so the following 'while' loop is never entered. - if (n < 0) { - return core.ZERO(); - } - } - n--; +function _load_validate() { + return _validate = _interopRequireDefault(__webpack_require__(98)); +} - var aq = [a, q]; +var _fix; - while (n >= 0) { - var r, s; - var b = core.getbit(f, n); - r = core.sum(aq[0][0], aq[0][1], aq[1][0], aq[1][1], x_1); - s = core.dbl(aq[1 - b][0], aq[1 - b][1]); - aq[1 - b] = s; - aq[b] = r; - n--; - } - q = aq[1]; +function _load_fix() { + return _fix = _interopRequireDefault(__webpack_require__(438)); +} - q[1] = core.invmodp(q[1]); - q[0] = core.mulmodp(q[0], q[1]); - core.reduce(q[0]); - return q[0]; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - function curve25519b32(a, b) { - return _base32encode(curve25519(_base32decode(a), - _base32decode(b))); - } +const path = __webpack_require__(0); - function curve25519(f, c) { - if (!c) { - c = core.BASE(); - } - f[0] &= 0xFFF8; - f[15] = (f[15] & 0x7FFF) | 0x4000; - return curve25519_raw(f, c); +exports.default = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, config, isRoot) { + // create human readable name + const name = info.name, + version = info.version; + + let human; + if (typeof name === 'string') { + human = name; + } + if (human && typeof version === 'string' && version) { + human += `@${version}`; + } + if (isRoot && info._loc) { + human = path.relative(config.cwd, info._loc); } - function _hexEncodeVector(k) { - var hexKey = utils.hexEncode(k); - // Pad with '0' at the front. - hexKey = new Array(64 + 1 - hexKey.length).join('0') + hexKey; - // Invert bytes. - return hexKey.split(/(..)/).reverse().join(''); + function warn(msg) { + if (human) { + msg = `${human}: ${msg}`; + } + config.reporter.warn(msg); } - function _hexDecodeVector(v) { - // assert(length(x) == 64); - // Invert bytes. - var hexKey = v.split(/(..)/).reverse().join(''); - return utils.hexDecode(hexKey); + yield (0, (_fix || _load_fix()).default)(info, moduleLoc, config.reporter, warn, config.looseSemver); + (0, (_resolveRelative || _load_resolveRelative()).default)(info, moduleLoc, config.lockfileFolder); + + if (config.cwd === config.globalFolder) { + return info; } + try { + (0, (_validate || _load_validate()).default)(info, isRoot, config.reporter, warn); + } catch (err) { + if (human) { + err.message = `${human}: ${err.message}`; + } + throw err; + } - // Expose some functions to the outside through this name space. + return info; + }); - /** - * Computes the scalar product of a point on the curve 25519. - * - * This function is used for the DH key-exchange protocol. - * - * Before multiplication, some bit operations are applied to the - * private key to ensure it is a valid Curve25519 secret key. - * It is the user's responsibility to make sure that the private - * key is a uniformly random, secret value. - * - * @function - * @param f {array} - * Private key. - * @param c {array} - * Public point on the curve. If not given, the curve's base point is used. - * @returns {array} - * Key point resulting from scalar product. - */ - ns.curve25519 = curve25519; + return function (_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); - /** - * Computes the scalar product of a point on the curve 25519. - * - * This variant does not make sure that the private key is valid. - * The user has the responsibility to ensure the private key is - * valid or that this results in a safe protocol. Unless you know - * exactly what you are doing, you should not use this variant, - * please use 'curve25519' instead. - * - * @function - * @param f {array} - * Private key. - * @param c {array} - * Public point on the curve. If not given, the curve's base point is used. - * @returns {array} - * Key point resulting from scalar product. - */ - ns.curve25519_raw = curve25519_raw; +/***/ }), +/* 168 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Encodes the internal representation of a key to a canonical hex - * representation. - * - * This is the format commonly used in other libraries and for - * test vectors, and is equivalent to the hex dump of the key in - * little-endian binary format. - * - * @function - * @param n {array} - * Array representation of key. - * @returns {string} - * Hexadecimal string representation of key. - */ - ns.hexEncodeVector = _hexEncodeVector; +"use strict"; - /** - * Decodes a canonical hex representation of a key - * to an internally compatible array representation. - * - * @function - * @param n {string} - * Hexadecimal string representation of key. - * @returns {array} - * Array representation of key. - */ - ns.hexDecodeVector = _hexDecodeVector; - /** - * Encodes the internal representation of a key into a - * hexadecimal representation. - * - * This is a strict positional notation, most significant digit first. - * - * @function - * @param n {array} - * Array representation of key. - * @returns {string} - * Hexadecimal string representation of key. - */ - ns.hexencode = utils.hexEncode; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isValidLicense = isValidLicense; +exports.stringifyPerson = stringifyPerson; +exports.parsePerson = parsePerson; +exports.normalizePerson = normalizePerson; +exports.extractDescription = extractDescription; +exports.extractRepositoryUrl = extractRepositoryUrl; - /** - * Decodes a hex representation of a key to an internally - * compatible array representation. - * - * @function - * @param n {string} - * Hexadecimal string representation of key. - * @returns {array} - * Array representation of key. - */ - ns.hexdecode = utils.hexDecode; - /** - * Encodes the internal representation of a key to a base32 - * representation. - * - * @function - * @param n {array} - * Array representation of key. - * @returns {string} - * Base32 string representation of key. - */ - ns.base32encode = utils.base32encode; +const validateLicense = __webpack_require__(650); - /** - * Decodes a base32 representation of a key to an internally - * compatible array representation. - * - * @function - * @param n {string} - * Base32 string representation of key. - * @returns {array} - * Array representation of key. - */ - ns.base32decode = utils.base32decode; +function isValidLicense(license) { + return !!license && validateLicense(license).validForNewPackages; +} -module.exports = ns; +function stringifyPerson(person) { + if (!person || typeof person !== 'object') { + return person; + } + const parts = []; + if (person.name) { + parts.push(person.name); + } -/***/ }), -/* 156 */ -/***/ (function(module, exports, __webpack_require__) { + const email = person.email || person.mail; + if (typeof email === 'string') { + parts.push(`<${email}>`); + } -var json = typeof JSON !== 'undefined' ? JSON : __webpack_require__(548); + const url = person.url || person.web; + if (typeof url === 'string') { + parts.push(`(${url})`); + } -module.exports = function (obj, opts) { - if (!opts) opts = {}; - if (typeof opts === 'function') opts = { cmp: opts }; - var space = opts.space || ''; - if (typeof space === 'number') space = Array(space+1).join(' '); - var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; - var replacer = opts.replacer || function(key, value) { return value; }; + return parts.join(' '); +} - var cmp = opts.cmp && (function (f) { - return function (node) { - return function (a, b) { - var aobj = { key: a, value: node[a] }; - var bobj = { key: b, value: node[b] }; - return f(aobj, bobj); - }; - }; - })(opts.cmp); +function parsePerson(person) { + if (typeof person !== 'string') { + return person; + } - var seen = []; - return (function stringify (parent, key, node, level) { - var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; - var colonSeparator = space ? ': ' : ':'; + // format: name (url) <email> + const obj = {}; - if (node && node.toJSON && typeof node.toJSON === 'function') { - node = node.toJSON(); - } + let name = person.match(/^([^\(<]+)/); + if (name) { + name = name[0].trim(); + if (name) { + obj.name = name; + } + } - node = replacer.call(parent, key, node); + const email = person.match(/<([^>]+)>/); + if (email) { + obj.email = email[1]; + } - if (node === undefined) { - return; - } - if (typeof node !== 'object' || node === null) { - return json.stringify(node); - } - if (isArray(node)) { - var out = []; - for (var i = 0; i < node.length; i++) { - var item = stringify(node, i, node[i], level+1) || json.stringify(null); - out.push(indent + space + item); - } - return '[' + out.join(',') + indent + ']'; - } - else { - if (seen.indexOf(node) !== -1) { - if (cycles) return json.stringify('__cycle__'); - throw new TypeError('Converting circular structure to JSON'); - } - else seen.push(node); + const url = person.match(/\(([^\)]+)\)/); + if (url) { + obj.url = url[1]; + } - var keys = objectKeys(node).sort(cmp && cmp(node)); - var out = []; - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = stringify(node, key, node[key], level+1); + return obj; +} - if(!value) continue; +function normalizePerson(person) { + return parsePerson(stringifyPerson(person)); +} - var keyValue = json.stringify(key) - + colonSeparator - + value; - ; - out.push(indent + space + keyValue); - } - seen.splice(seen.indexOf(node), 1); - return '{' + out.join(',') + indent + '}'; - } - })({ '': obj }, '', obj, 0); -}; +function extractDescription(readme) { + if (typeof readme !== 'string' || readme === '') { + return undefined; + } -var isArray = Array.isArray || function (x) { - return {}.toString.call(x) === '[object Array]'; -}; + // split into lines + const lines = readme.trim().split('\n').map(line => line.trim()); -var objectKeys = Object.keys || function (obj) { - var has = Object.prototype.hasOwnProperty || function () { return true }; - var keys = []; - for (var key in obj) { - if (has.call(obj, key)) keys.push(key); + // find the start of the first paragraph, ignore headings + let start = 0; + for (; start < lines.length; start++) { + const line = lines[start]; + if (line && line.match(/^(#|$)/)) { + // line isn't empty and isn't a heading so this is the start of a paragraph + start++; + break; } - return keys; -}; + } + + // skip newlines from the header to the first line + while (start < lines.length && !lines[start]) { + start++; + } + + // continue to the first non empty line + let end = start; + while (end < lines.length && lines[end]) { + end++; + } + + return lines.slice(start, end).join(' '); +} +function extractRepositoryUrl(repository) { + if (!repository || typeof repository !== 'object') { + return repository; + } + return repository.url; +} /***/ }), -/* 157 */ +/* 169 */ /***/ (function(module, exports, __webpack_require__) { -var isBuffer = __webpack_require__(533); -var toString = Object.prototype.toString; +"use strict"; -/** - * Get the native `typeof` a value. - * - * @param {*} `val` - * @return {*} Native javascript type - */ -module.exports = function kindOf(val) { - // primitivies - if (typeof val === 'undefined') { - return 'undefined'; - } - if (val === null) { - return 'null'; - } - if (val === true || val === false || val instanceof Boolean) { - return 'boolean'; - } - if (typeof val === 'string' || val instanceof String) { - return 'string'; - } - if (typeof val === 'number' || val instanceof Number) { - return 'number'; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isNotFakeRoot = isNotFakeRoot; +exports.isRootUser = isRootUser; +function getUid() { + if (process.platform !== 'win32' && process.getuid) { + return process.getuid(); } + return null; +} - // functions - if (typeof val === 'function' || val instanceof Function) { - return 'function'; - } - - // array - if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { - return 'array'; - } - - // check for instances of RegExp and Date before calling `toString` - if (val instanceof RegExp) { - return 'regexp'; - } - if (val instanceof Date) { - return 'date'; - } - - // other objects - var type = toString.call(val); - - if (type === '[object RegExp]') { - return 'regexp'; - } - if (type === '[object Date]') { - return 'date'; - } - if (type === '[object Arguments]') { - return 'arguments'; - } - if (type === '[object Error]') { - return 'error'; - } - - // buffer - if (isBuffer(val)) { - return 'buffer'; - } - - // es6: Map, WeakMap, Set, WeakSet - if (type === '[object Set]') { - return 'set'; - } - if (type === '[object WeakSet]') { - return 'weakset'; - } - if (type === '[object Map]') { - return 'map'; - } - if (type === '[object WeakMap]') { - return 'weakmap'; - } - if (type === '[object Symbol]') { - return 'symbol'; - } - - // typed arrays - if (type === '[object Int8Array]') { - return 'int8array'; - } - if (type === '[object Uint8Array]') { - return 'uint8array'; - } - if (type === '[object Uint8ClampedArray]') { - return 'uint8clampedarray'; - } - if (type === '[object Int16Array]') { - return 'int16array'; - } - if (type === '[object Uint16Array]') { - return 'uint16array'; - } - if (type === '[object Int32Array]') { - return 'int32array'; - } - if (type === '[object Uint32Array]') { - return 'uint32array'; - } - if (type === '[object Float32Array]') { - return 'float32array'; - } - if (type === '[object Float64Array]') { - return 'float64array'; - } - - // must be a plain object - return 'object'; -}; +exports.default = isRootUser(getUid()) && isNotFakeRoot(); +function isNotFakeRoot() { + return Boolean(process.env.FAKEROOTKEY); +} +function isRootUser(uid) { + return uid === 0; +} /***/ }), -/* 158 */ +/* 170 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var win32 = process && process.platform === 'win32'; -var path = __webpack_require__(1); -var fileRe = __webpack_require__(468); -var utils = module.exports; - -/** - * Module dependencies - */ - -utils.diff = __webpack_require__(317); -utils.unique = __webpack_require__(320); -utils.braces = __webpack_require__(402); -utils.brackets = __webpack_require__(460); -utils.extglob = __webpack_require__(467); -utils.isExtglob = __webpack_require__(100); -utils.isGlob = __webpack_require__(101); -utils.typeOf = __webpack_require__(157); -utils.normalize = __webpack_require__(563); -utils.omit = __webpack_require__(565); -utils.parseGlob = __webpack_require__(568); -utils.cache = __webpack_require__(583); - -/** - * Get the filename of a filepath - * - * @param {String} `string` - * @return {String} - */ - -utils.filename = function filename(fp) { - var seg = fp.match(fileRe()); - return seg && seg[0]; -}; - -/** - * Returns a function that returns true if the given - * pattern is the same as a given `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.explodeHashedUrl = explodeHashedUrl; +function explodeHashedUrl(url) { + const parts = url.split('#'); -utils.isPath = function isPath(pattern, opts) { - opts = opts || {}; - return function(fp) { - var unixified = utils.unixify(fp, opts); - if(opts.nocase){ - return pattern.toLowerCase() === unixified.toLowerCase(); - } - return pattern === unixified; + return { + hash: parts[1] || '', + url: parts[0] }; -}; +} -/** - * Returns a function that returns true if the given - * pattern contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ +/***/ }), +/* 171 */ +/***/ (function(module, exports, __webpack_require__) { -utils.hasPath = function hasPath(pattern, opts) { - return function(fp) { - return utils.unixify(pattern, opts).indexOf(fp) !== -1; - }; -}; +module.exports = { "default": __webpack_require__(178), __esModule: true }; -/** - * Returns a function that returns true if the given - * pattern matches or contains a `filepath` - * - * @param {String} `pattern` - * @return {Function} - */ +/***/ }), +/* 172 */ +/***/ (function(module, exports) { -utils.matchPath = function matchPath(pattern, opts) { - var fn = (opts && opts.contains) - ? utils.hasPath(pattern, opts) - : utils.isPath(pattern, opts); - return fn; -}; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); -/** - * Returns a function that returns true if the given - * regex matches the `filename` of a file path. - * - * @param {RegExp} `re` - * @return {Boolean} - */ + var r = range(a, b, str); -utils.hasFilename = function hasFilename(re) { - return function(fp) { - var name = utils.filename(fp); - return name && re.test(name); + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) }; -}; - -/** - * Coerce `val` to an array - * - * @param {*} val - * @return {Array} - */ - -utils.arrayify = function arrayify(val) { - return !Array.isArray(val) - ? [val] - : val; -}; +} -/** - * Normalize all slashes in a file path or glob pattern to - * forward slashes. - */ +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} -utils.unixify = function unixify(fp, opts) { - if (opts && opts.unixify === false) return fp; - if (opts && opts.unixify === true || win32 || path.sep === '\\') { - return utils.normalize(fp, false); - } - if (opts && opts.unescape === true) { - return fp ? fp.toString().replace(/\\(\w)/g, '$1') : ''; - } - return fp; -}; +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; -/** - * Escape/unescape utils - */ + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; -utils.escapePath = function escapePath(fp) { - return fp.replace(/[\\.]/g, '\\$&'); -}; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } -utils.unescapeGlob = function unescapeGlob(fp) { - return fp.replace(/[\\"']/g, ''); -}; + bi = str.indexOf(b, i + 1); + } -utils.escapeRe = function escapeRe(str) { - return str.replace(/[-[\\$*+?.#^\s{}(|)\]]/g, '\\$&'); -}; + i = ai < bi && ai >= 0 ? ai : bi; + } -/** - * Expose `utils` - */ + if (begs.length) { + result = [ left, right ]; + } + } -module.exports = utils; + return result; +} /***/ }), -/* 159 */ +/* 173 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = minimatch -minimatch.Minimatch = Minimatch +var concatMap = __webpack_require__(177); +var balanced = __webpack_require__(172); -var path = { sep: '/' } -try { - path = __webpack_require__(1) -} catch (er) {} +module.exports = expandTop; -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __webpack_require__(401) +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); } -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => any number of characters -var star = qmark + '*?' - -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); } -// normalizes slashes. -var slashSplit = /\/+/ -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - return t -} + var parts = []; + var m = balanced('{', '}', str); -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch + if (!m) + return str.split(','); - var orig = minimatch + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); } - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } + parts.push.apply(parts, p); - return m + return parts; } -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} +function expandTop(str) { + if (!str) + return []; -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); } - if (!options) options = {} + return expand(escapeBraces(str), true).map(unescapeBraces); +} - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } +function identity(e) { + return e; +} - // "" only matches "" - if (pattern.trim() === '') return p === '' +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} - return new Minimatch(pattern, options).match(p) +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; } -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } +function expand(str, isTop) { + var expansions = []; - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; - if (!options) options = {} - pattern = pattern.trim() + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } } - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. - // make the set of regexps etc. - this.make() -} + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; -Minimatch.prototype.debug = function () {} + var N; -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - var pattern = this.pattern - var options = this.options + N = []; - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); } - // step 1: figure out negation, etc. - this.parseNegate() + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } - // step 2: expand braces - var set = this.globSet = this.braceExpand() + return expansions; +} - if (options.debug) this.debug = console.error - this.debug(this.pattern, set) - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) +/***/ }), +/* 174 */ +/***/ (function(module, exports, __webpack_require__) { - this.debug(this.pattern, set) +"use strict"; - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - this.debug(this.pattern, set) +var buffer = __webpack_require__(120); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} - this.debug(this.pattern, set) - this.set = set -} +/***/ }), +/* 175 */ +/***/ (function(module, exports, __webpack_require__) { -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 +"use strict"; - if (options.nonegate) return - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } +function preserveCamelCase(str) { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + for (let i = 0; i < str.length; i++) { + const c = str[i]; -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) { + str = str.substr(0, i) + '-' + str.substr(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) { + str = str.substr(0, i - 1) + '-' + str.substr(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = c.toLowerCase() === c; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = c.toUpperCase() === c; + } + } -Minimatch.prototype.braceExpand = braceExpand + return str; +} -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } +module.exports = function (str) { + if (arguments.length > 1) { + str = Array.from(arguments) + .map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + str = str.trim(); + } - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + if (str.length === 0) { + return ''; + } - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } + if (str.length === 1) { + return str.toLowerCase(); + } - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } + if (/^[a-z0-9]+$/.test(str)) { + return str; + } - return expand(pattern) -} + const hasUpperCase = str !== str.toLowerCase(); -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } + if (hasUpperCase) { + str = preserveCamelCase(str); + } - var options = this.options + return str + .replace(/^[_.\- ]+/, '') + .toLowerCase() + .replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase()); +}; - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this +/***/ }), +/* 176 */ +/***/ (function(module, exports) { - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false +function Caseless (dict) { + this.dict = dict || {} +} +Caseless.prototype.set = function (name, value, clobber) { + if (typeof name === 'object') { + for (var i in name) { + this.set(i, name[i], value) } + } else { + if (typeof clobber === 'undefined') clobber = true + var has = this.has(name) + + if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value + else this.dict[has || name] = value + return has + } +} +Caseless.prototype.has = function (name) { + var keys = Object.keys(this.dict) + , name = name.toLowerCase() + ; + for (var i=0;i<keys.length;i++) { + if (keys[i].toLowerCase() === name) return keys[i] } + return false +} +Caseless.prototype.get = function (name) { + name = name.toLowerCase() + var result, _key + var headers = this.dict + Object.keys(headers).forEach(function (key) { + _key = key.toLowerCase() + if (name === _key) result = headers[key] + }) + return result +} +Caseless.prototype.swap = function (name) { + var has = this.has(name) + if (has === name) return + if (!has) throw new Error('There is no header than matches "'+name+'"') + this.dict[name] = this.dict[has] + delete this.dict[has] +} +Caseless.prototype.del = function (name) { + var has = this.has(name) + return delete this.dict[has || name] +} - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) +module.exports = function (dict) {return new Caseless(dict)} +module.exports.httpify = function (resp, headers) { + var c = new Caseless(headers) + resp.setHeader = function (key, value, clobber) { + if (typeof value === 'undefined') return + return c.set(key, value, clobber) + } + resp.hasHeader = function (key) { + return c.has(key) + } + resp.getHeader = function (key) { + return c.get(key) + } + resp.removeHeader = function (key) { + return c.del(key) + } + resp.headers = c.dict + return c +} - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false +/***/ }), +/* 177 */ +/***/ (function(module, exports) { - case '\\': - clearStateChar() - escaping = true - continue +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue - } - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue +/***/ }), +/* 178 */ +/***/ (function(module, exports, __webpack_require__) { - case '(': - if (inClass) { - re += '(' - continue - } +__webpack_require__(200); +__webpack_require__(85); +__webpack_require__(109); +__webpack_require__(201); +module.exports = __webpack_require__(21).Promise; - if (!stateChar) { - re += '\\(' - continue - } +/***/ }), +/* 179 */ +/***/ (function(module, exports) { - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue +module.exports = function(){ /* empty */ }; - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } +/***/ }), +/* 180 */ +/***/ (function(module, exports) { - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:<pattern>)<type> - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue +module.exports = function(it, Constructor, name, forbiddenField){ + if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ + throw TypeError(name + ': incorrect invocation!'); + } return it; +}; - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } +/***/ }), +/* 181 */ +/***/ (function(module, exports, __webpack_require__) { - clearStateChar() - re += '|' - continue +// false -> Array#indexOf +// true -> Array#includes +var toIObject = __webpack_require__(70) + , toLength = __webpack_require__(84) + , toIndex = __webpack_require__(197); +module.exports = function(IS_INCLUDES){ + return function($this, el, fromIndex){ + var O = toIObject($this) + , length = toLength(O.length) + , index = toIndex(fromIndex, length) + , value; + // Array#includes uses SameValueZero equality algorithm + if(IS_INCLUDES && el != el)while(length > index){ + value = O[index++]; + if(value != value)return true; + // Array#toIndex ignores holes, Array#includes - not + } else for(;length > index; index++)if(IS_INCLUDES || index in O){ + if(O[index] === el)return IS_INCLUDES || index || 0; + } return !IS_INCLUDES && -1; + }; +}; - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() +/***/ }), +/* 182 */ +/***/ (function(module, exports, __webpack_require__) { - if (inClass) { - re += '\\' + c - continue - } +var ctx = __webpack_require__(37) + , call = __webpack_require__(127) + , isArrayIter = __webpack_require__(126) + , anObject = __webpack_require__(27) + , toLength = __webpack_require__(84) + , getIterFn = __webpack_require__(108) + , BREAK = {} + , RETURN = {}; +var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ + var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) + , f = ctx(fn, that, entries ? 2 : 1) + , index = 0 + , length, step, iterator, result; + if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); + // fast case for arrays with default iterator + if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ + result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); + if(result === BREAK || result === RETURN)return result; + } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ + result = call(iterator, f, step.value, entries); + if(result === BREAK || result === RETURN)return result; + } +}; +exports.BREAK = BREAK; +exports.RETURN = RETURN; - inClass = true - classStart = i - reClassStart = re.length - re += c - continue +/***/ }), +/* 183 */ +/***/ (function(module, exports, __webpack_require__) { - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } +module.exports = !__webpack_require__(33) && !__webpack_require__(82)(function(){ + return Object.defineProperty(__webpack_require__(65)('div'), 'a', {get: function(){ return 7; }}).a != 7; +}); - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue - } - } +/***/ }), +/* 184 */ +/***/ (function(module, exports) { - // finish up the class. - hasMagic = true - inClass = false - re += c - continue +// fast apply, http://jsperf.lnkit.com/fast-apply/5 +module.exports = function(fn, args, that){ + var un = that === undefined; + switch(args.length){ + case 0: return un ? fn() + : fn.call(that); + case 1: return un ? fn(args[0]) + : fn.call(that, args[0]); + case 2: return un ? fn(args[0], args[1]) + : fn.call(that, args[0], args[1]); + case 3: return un ? fn(args[0], args[1], args[2]) + : fn.call(that, args[0], args[1], args[2]); + case 4: return un ? fn(args[0], args[1], args[2], args[3]) + : fn.call(that, args[0], args[1], args[2], args[3]); + } return fn.apply(that, args); +}; - default: - // swallow any state char that wasn't consumed - clearStateChar() +/***/ }), +/* 185 */ +/***/ (function(module, exports, __webpack_require__) { - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } +"use strict"; - re += c +var create = __webpack_require__(188) + , descriptor = __webpack_require__(83) + , setToStringTag = __webpack_require__(67) + , IteratorPrototype = {}; - } // switch - } // for +// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() +__webpack_require__(29)(IteratorPrototype, __webpack_require__(9)('iterator'), function(){ return this; }); - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } +module.exports = function(Constructor, NAME, next){ + Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); + setToStringTag(Constructor, NAME + ' Iterator'); +}; - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } +/***/ }), +/* 186 */ +/***/ (function(module, exports) { - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) +module.exports = function(done, value){ + return {value: value, done: !!done}; +}; - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type +/***/ }), +/* 187 */ +/***/ (function(module, exports, __webpack_require__) { - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } +var global = __webpack_require__(13) + , macrotask = __webpack_require__(105).set + , Observer = global.MutationObserver || global.WebKitMutationObserver + , process = global.process + , Promise = global.Promise + , isNode = __webpack_require__(41)(process) == 'process'; - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } +module.exports = function(){ + var head, last, notify; - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } + var flush = function(){ + var parent, fn; + if(isNode && (parent = process.domain))parent.exit(); + while(head){ + fn = head.fn; + head = head.next; + try { + fn(); + } catch(e){ + if(head)notify(); + else last = undefined; + throw e; + } + } last = undefined; + if(parent)parent.enter(); + }; - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] + // Node.js + if(isNode){ + notify = function(){ + process.nextTick(flush); + }; + // browsers with MutationObserver + } else if(Observer){ + var toggle = true + , node = document.createTextNode(''); + new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new + notify = function(){ + node.data = toggle = !toggle; + }; + // environments with maybe non-completely correct, but existent Promise + } else if(Promise && Promise.resolve){ + var promise = Promise.resolve(); + notify = function(){ + promise.then(flush); + }; + // for other environments - macrotask based on: + // - setImmediate + // - MessageChannel + // - window.postMessag + // - onreadystatechange + // - setTimeout + } else { + notify = function(){ + // strange IE + webpack dev server bug - use .call(global) + macrotask.call(global, flush); + }; + } - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) + return function(fn){ + var task = {fn: fn, next: undefined}; + if(last)last.next = task; + if(!head){ + head = task; + notify(); + } last = task; + }; +}; - nlLast += nlAfter +/***/ }), +/* 188 */ +/***/ (function(module, exports, __webpack_require__) { - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') - } - nlAfter = cleanAfter +// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) +var anObject = __webpack_require__(27) + , dPs = __webpack_require__(189) + , enumBugKeys = __webpack_require__(100) + , IE_PROTO = __webpack_require__(68)('IE_PROTO') + , Empty = function(){ /* empty */ } + , PROTOTYPE = 'prototype'; - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' - } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } +// Create object with fake `null` prototype: use iframe Object with cleared prototype +var createDict = function(){ + // Thrash, waste and sodomy: IE GC bug + var iframe = __webpack_require__(65)('iframe') + , i = enumBugKeys.length + , lt = '<' + , gt = '>' + , iframeDocument; + iframe.style.display = 'none'; + __webpack_require__(101).appendChild(iframe); + iframe.src = 'javascript:'; // eslint-disable-line no-script-url + // createDict = iframe.contentWindow.Object; + // html.removeChild(iframe); + iframeDocument = iframe.contentWindow.document; + iframeDocument.open(); + iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); + iframeDocument.close(); + createDict = iframeDocument.F; + while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; + return createDict(); +}; - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } +module.exports = Object.create || function create(O, Properties){ + var result; + if(O !== null){ + Empty[PROTOTYPE] = anObject(O); + result = new Empty; + Empty[PROTOTYPE] = null; + // add "__proto__" for Object.getPrototypeOf polyfill + result[IE_PROTO] = O; + } else result = createDict(); + return Properties === undefined ? result : dPs(result, Properties); +}; - if (addPatternStart) { - re = patternStart + re - } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } +/***/ }), +/* 189 */ +/***/ (function(module, exports, __webpack_require__) { - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } +var dP = __webpack_require__(38) + , anObject = __webpack_require__(27) + , getKeys = __webpack_require__(129); - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } +module.exports = __webpack_require__(33) ? Object.defineProperties : function defineProperties(O, Properties){ + anObject(O); + var keys = getKeys(Properties) + , length = keys.length + , i = 0 + , P; + while(length > i)dP.f(O, P = keys[i++], Properties[P]); + return O; +}; - regExp._glob = pattern - regExp._src = re +/***/ }), +/* 190 */ +/***/ (function(module, exports, __webpack_require__) { - return regExp -} +// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) +var has = __webpack_require__(42) + , toObject = __webpack_require__(106) + , IE_PROTO = __webpack_require__(68)('IE_PROTO') + , ObjectProto = Object.prototype; -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} +module.exports = Object.getPrototypeOf || function(O){ + O = toObject(O); + if(has(O, IE_PROTO))return O[IE_PROTO]; + if(typeof O.constructor == 'function' && O instanceof O.constructor){ + return O.constructor.prototype; + } return O instanceof Object ? ObjectProto : null; +}; -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp +/***/ }), +/* 191 */ +/***/ (function(module, exports, __webpack_require__) { - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set +var has = __webpack_require__(42) + , toIObject = __webpack_require__(70) + , arrayIndexOf = __webpack_require__(181)(false) + , IE_PROTO = __webpack_require__(68)('IE_PROTO'); - if (!set.length) { - this.regexp = false - return this.regexp +module.exports = function(object, names){ + var O = toIObject(object) + , i = 0 + , result = [] + , key; + for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); + // Don't enum bug & hidden keys + while(names.length > i)if(has(O, key = names[i++])){ + ~arrayIndexOf(result, key) || result.push(key); } - var options = this.options + return result; +}; - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' +/***/ }), +/* 192 */ +/***/ (function(module, exports, __webpack_require__) { - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') +var hide = __webpack_require__(29); +module.exports = function(target, src, safe){ + for(var key in src){ + if(safe && target[key])target[key] = src[key]; + else hide(target, key, src[key]); + } return target; +}; - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' +/***/ }), +/* 193 */ +/***/ (function(module, exports, __webpack_require__) { - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' +module.exports = __webpack_require__(29); - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} +/***/ }), +/* 194 */ +/***/ (function(module, exports, __webpack_require__) { -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} +"use strict"; -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' +var global = __webpack_require__(13) + , core = __webpack_require__(21) + , dP = __webpack_require__(38) + , DESCRIPTORS = __webpack_require__(33) + , SPECIES = __webpack_require__(9)('species'); - if (f === '/' && partial) return true +module.exports = function(KEY){ + var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; + if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { + configurable: true, + get: function(){ return this; } + }); +}; - var options = this.options +/***/ }), +/* 195 */ +/***/ (function(module, exports, __webpack_require__) { - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } +// 7.3.20 SpeciesConstructor(O, defaultConstructor) +var anObject = __webpack_require__(27) + , aFunction = __webpack_require__(63) + , SPECIES = __webpack_require__(9)('species'); +module.exports = function(O, D){ + var C = anObject(O).constructor, S; + return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); +}; - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - this.debug(this.pattern, 'set', set) - - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } - - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } - - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd - } - - // should be unreachable. - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} +/***/ }), +/* 196 */ +/***/ (function(module, exports, __webpack_require__) { +var toInteger = __webpack_require__(69) + , defined = __webpack_require__(64); +// true -> String#at +// false -> String#codePointAt +module.exports = function(TO_STRING){ + return function(that, pos){ + var s = String(defined(that)) + , i = toInteger(pos) + , l = s.length + , a, b; + if(i < 0 || i >= l)return TO_STRING ? '' : undefined; + a = s.charCodeAt(i); + return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff + ? TO_STRING ? s.charAt(i) : a + : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; + }; +}; /***/ }), -/* 160 */ +/* 197 */ /***/ (function(module, exports, __webpack_require__) { -var path = __webpack_require__(1); -var fs = __webpack_require__(6); -var _0777 = parseInt('0777', 8); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 & (~process.umask()); - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; +var toInteger = __webpack_require__(69) + , max = Math.max + , min = Math.min; +module.exports = function(index, length){ + index = toInteger(index); + return index < 0 ? max(index + length, 0) : min(index, length); +}; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } +/***/ }), +/* 198 */ +/***/ (function(module, exports, __webpack_require__) { - return made; +// 7.1.1 ToPrimitive(input [, PreferredType]) +var isObject = __webpack_require__(43); +// instead of the ES6 spec version, we didn't implement @@toPrimitive case +// and the second argument - flag - preferred type is a string +module.exports = function(it, S){ + if(!isObject(it))return it; + var fn, val; + if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; + if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; + if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; + throw TypeError("Can't convert object to primitive value"); }; - /***/ }), -/* 161 */ +/* 199 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var addToUnscopables = __webpack_require__(179) + , step = __webpack_require__(186) + , Iterators = __webpack_require__(32) + , toIObject = __webpack_require__(70); -function posix(path) { - return path.charAt(0) === '/'; -} - -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} +// 22.1.3.4 Array.prototype.entries() +// 22.1.3.13 Array.prototype.keys() +// 22.1.3.29 Array.prototype.values() +// 22.1.3.30 Array.prototype[@@iterator]() +module.exports = __webpack_require__(102)(Array, 'Array', function(iterated, kind){ + this._t = toIObject(iterated); // target + this._i = 0; // next index + this._k = kind; // kind +// 22.1.5.2.1 %ArrayIteratorPrototype%.next() +}, function(){ + var O = this._t + , kind = this._k + , index = this._i++; + if(!O || index >= O.length){ + this._t = undefined; + return step(1); + } + if(kind == 'keys' )return step(0, index); + if(kind == 'values')return step(0, O[index]); + return step(0, [index, O[index]]); +}, 'values'); -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; +// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) +Iterators.Arguments = Iterators.Array; +addToUnscopables('keys'); +addToUnscopables('values'); +addToUnscopables('entries'); /***/ }), -/* 162 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = nextTick; -} else { - module.exports = process.nextTick; -} +/* 200 */ +/***/ (function(module, exports) { -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} /***/ }), -/* 163 */ +/* 201 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var LIBRARY = __webpack_require__(103) + , global = __webpack_require__(13) + , ctx = __webpack_require__(37) + , classof = __webpack_require__(81) + , $export = __webpack_require__(66) + , isObject = __webpack_require__(43) + , aFunction = __webpack_require__(63) + , anInstance = __webpack_require__(180) + , forOf = __webpack_require__(182) + , speciesConstructor = __webpack_require__(195) + , task = __webpack_require__(105).set + , microtask = __webpack_require__(187)() + , PROMISE = 'Promise' + , TypeError = global.TypeError + , process = global.process + , $Promise = global[PROMISE] + , process = global.process + , isNode = classof(process) == 'process' + , empty = function(){ /* empty */ } + , Internal, GenericPromiseCapability, Wrapper; -var jsonSafeStringify = __webpack_require__(547) - , crypto = __webpack_require__(7) - , Buffer = __webpack_require__(57).Buffer - -var defer = typeof setImmediate === 'undefined' - ? process.nextTick - : setImmediate - -function paramsHaveRequestBody(params) { - return ( - params.body || - params.requestBodyStream || - (params.json && typeof params.json !== 'boolean') || - params.multipart - ) -} +var USE_NATIVE = !!function(){ + try { + // correct subclassing with @@species support + var promise = $Promise.resolve(1) + , FakePromise = (promise.constructor = {})[__webpack_require__(9)('species')] = function(exec){ exec(empty, empty); }; + // unhandled rejections tracking support, NodeJS Promise without it fails @@species test + return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; + } catch(e){ /* empty */ } +}(); -function safeStringify (obj, replacer) { - var ret +// helpers +var sameConstructor = function(a, b){ + // with library wrapper special case + return a === b || a === $Promise && b === Wrapper; +}; +var isThenable = function(it){ + var then; + return isObject(it) && typeof (then = it.then) == 'function' ? then : false; +}; +var newPromiseCapability = function(C){ + return sameConstructor($Promise, C) + ? new PromiseCapability(C) + : new GenericPromiseCapability(C); +}; +var PromiseCapability = GenericPromiseCapability = function(C){ + var resolve, reject; + this.promise = new C(function($$resolve, $$reject){ + if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); + resolve = $$resolve; + reject = $$reject; + }); + this.resolve = aFunction(resolve); + this.reject = aFunction(reject); +}; +var perform = function(exec){ try { - ret = JSON.stringify(obj, replacer) - } catch (e) { - ret = jsonSafeStringify(obj, replacer) + exec(); + } catch(e){ + return {error: e}; } - return ret -} - -function md5 (str) { - return crypto.createHash('md5').update(str).digest('hex') -} - -function isReadStream (rs) { - return rs.readable && rs.path && rs.mode -} - -function toBase64 (str) { - return Buffer.from(str || '', 'utf8').toString('base64') -} - -function copy (obj) { - var o = {} - Object.keys(obj).forEach(function (i) { - o[i] = obj[i] - }) - return o -} - -function version () { - var numbers = process.version.replace('v', '').split('.') - return { - major: parseInt(numbers[0], 10), - minor: parseInt(numbers[1], 10), - patch: parseInt(numbers[2], 10) +}; +var notify = function(promise, isReject){ + if(promise._n)return; + promise._n = true; + var chain = promise._c; + microtask(function(){ + var value = promise._v + , ok = promise._s == 1 + , i = 0; + var run = function(reaction){ + var handler = ok ? reaction.ok : reaction.fail + , resolve = reaction.resolve + , reject = reaction.reject + , domain = reaction.domain + , result, then; + try { + if(handler){ + if(!ok){ + if(promise._h == 2)onHandleUnhandled(promise); + promise._h = 1; + } + if(handler === true)result = value; + else { + if(domain)domain.enter(); + result = handler(value); + if(domain)domain.exit(); + } + if(result === reaction.promise){ + reject(TypeError('Promise-chain cycle')); + } else if(then = isThenable(result)){ + then.call(result, resolve, reject); + } else resolve(result); + } else reject(value); + } catch(e){ + reject(e); + } + }; + while(chain.length > i)run(chain[i++]); // variable length - can't use forEach + promise._c = []; + promise._n = false; + if(isReject && !promise._h)onUnhandled(promise); + }); +}; +var onUnhandled = function(promise){ + task.call(global, function(){ + var value = promise._v + , abrupt, handler, console; + if(isUnhandled(promise)){ + abrupt = perform(function(){ + if(isNode){ + process.emit('unhandledRejection', value, promise); + } else if(handler = global.onunhandledrejection){ + handler({promise: promise, reason: value}); + } else if((console = global.console) && console.error){ + console.error('Unhandled promise rejection', value); + } + }); + // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should + promise._h = isNode || isUnhandled(promise) ? 2 : 1; + } promise._a = undefined; + if(abrupt)throw abrupt.error; + }); +}; +var isUnhandled = function(promise){ + if(promise._h == 1)return false; + var chain = promise._a || promise._c + , i = 0 + , reaction; + while(chain.length > i){ + reaction = chain[i++]; + if(reaction.fail || !isUnhandled(reaction.promise))return false; + } return true; +}; +var onHandleUnhandled = function(promise){ + task.call(global, function(){ + var handler; + if(isNode){ + process.emit('rejectionHandled', promise); + } else if(handler = global.onrejectionhandled){ + handler({promise: promise, reason: promise._v}); + } + }); +}; +var $reject = function(value){ + var promise = this; + if(promise._d)return; + promise._d = true; + promise = promise._w || promise; // unwrap + promise._v = value; + promise._s = 2; + if(!promise._a)promise._a = promise._c.slice(); + notify(promise, true); +}; +var $resolve = function(value){ + var promise = this + , then; + if(promise._d)return; + promise._d = true; + promise = promise._w || promise; // unwrap + try { + if(promise === value)throw TypeError("Promise can't be resolved itself"); + if(then = isThenable(value)){ + microtask(function(){ + var wrapper = {_w: promise, _d: false}; // wrap + try { + then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); + } catch(e){ + $reject.call(wrapper, e); + } + }); + } else { + promise._v = value; + promise._s = 1; + notify(promise, false); + } + } catch(e){ + $reject.call({_w: promise, _d: false}, e); // wrap } +}; + +// constructor polyfill +if(!USE_NATIVE){ + // 25.4.3.1 Promise(executor) + $Promise = function Promise(executor){ + anInstance(this, $Promise, PROMISE, '_h'); + aFunction(executor); + Internal.call(this); + try { + executor(ctx($resolve, this, 1), ctx($reject, this, 1)); + } catch(err){ + $reject.call(this, err); + } + }; + Internal = function Promise(executor){ + this._c = []; // <- awaiting reactions + this._a = undefined; // <- checked in isUnhandled reactions + this._s = 0; // <- state + this._d = false; // <- done + this._v = undefined; // <- value + this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled + this._n = false; // <- notify + }; + Internal.prototype = __webpack_require__(192)($Promise.prototype, { + // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) + then: function then(onFulfilled, onRejected){ + var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); + reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; + reaction.fail = typeof onRejected == 'function' && onRejected; + reaction.domain = isNode ? process.domain : undefined; + this._c.push(reaction); + if(this._a)this._a.push(reaction); + if(this._s)notify(this, false); + return reaction.promise; + }, + // 25.4.5.1 Promise.prototype.catch(onRejected) + 'catch': function(onRejected){ + return this.then(undefined, onRejected); + } + }); + PromiseCapability = function(){ + var promise = new Internal; + this.promise = promise; + this.resolve = ctx($resolve, promise, 1); + this.reject = ctx($reject, promise, 1); + }; } -exports.paramsHaveRequestBody = paramsHaveRequestBody -exports.safeStringify = safeStringify -exports.md5 = md5 -exports.isReadStream = isReadStream -exports.toBase64 = toBase64 -exports.copy = copy -exports.version = version -exports.defer = defer +$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); +__webpack_require__(67)($Promise, PROMISE); +__webpack_require__(194)(PROMISE); +Wrapper = __webpack_require__(21)[PROMISE]; +// statics +$export($export.S + $export.F * !USE_NATIVE, PROMISE, { + // 25.4.4.5 Promise.reject(r) + reject: function reject(r){ + var capability = newPromiseCapability(this) + , $$reject = capability.reject; + $$reject(r); + return capability.promise; + } +}); +$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { + // 25.4.4.6 Promise.resolve(x) + resolve: function resolve(x){ + // instanceof instead of internal slot check because we should fix it without replacement native Promise core + if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; + var capability = newPromiseCapability(this) + , $$resolve = capability.resolve; + $$resolve(x); + return capability.promise; + } +}); +$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(128)(function(iter){ + $Promise.all(iter)['catch'](empty); +})), PROMISE, { + // 25.4.4.1 Promise.all(iterable) + all: function all(iterable){ + var C = this + , capability = newPromiseCapability(C) + , resolve = capability.resolve + , reject = capability.reject; + var abrupt = perform(function(){ + var values = [] + , index = 0 + , remaining = 1; + forOf(iterable, false, function(promise){ + var $index = index++ + , alreadyCalled = false; + values.push(undefined); + remaining++; + C.resolve(promise).then(function(value){ + if(alreadyCalled)return; + alreadyCalled = true; + values[$index] = value; + --remaining || resolve(values); + }, reject); + }); + --remaining || resolve(values); + }); + if(abrupt)reject(abrupt.error); + return capability.promise; + }, + // 25.4.4.4 Promise.race(iterable) + race: function race(iterable){ + var C = this + , capability = newPromiseCapability(C) + , reject = capability.reject; + var abrupt = perform(function(){ + forOf(iterable, false, function(promise){ + C.resolve(promise).then(capability.resolve, reject); + }); + }); + if(abrupt)reject(abrupt.error); + return capability.promise; + } +}); /***/ }), -/* 164 */ +/* 202 */ /***/ (function(module, exports, __webpack_require__) { -// Copyright 2015 Joyent, Inc. +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ -module.exports = { - read: read, - readPkcs1: readPkcs1, - write: write, - writePkcs1: writePkcs1 -}; +exports = module.exports = __webpack_require__(111); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); -var assert = __webpack_require__(9); -var asn1 = __webpack_require__(34); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); +/** + * Colors. + */ -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var pem = __webpack_require__(41); +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; -var pkcs8 = __webpack_require__(74); -var readECDSACurve = pkcs8.readECDSACurve; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ -function read(buf, options) { - return (pem.read(buf, options, 'pkcs1')); -} +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } -function write(key, options) { - return (pem.write(key, options, 'pkcs1')); + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } -/* Helper to read in a single mpint */ -function readMPInt(der, nm) { - assert.strictEqual(der.peek(), asn1.Ber.Integer, - nm + ' is not an Integer'); - return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); -} +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -function readPkcs1(alg, type, der) { - switch (alg) { - case 'RSA': - if (type === 'public') - return (readPkcs1RSAPublic(der)); - else if (type === 'private') - return (readPkcs1RSAPrivate(der)); - throw (new Error('Unknown key type: ' + type)); - case 'DSA': - if (type === 'public') - return (readPkcs1DSAPublic(der)); - else if (type === 'private') - return (readPkcs1DSAPrivate(der)); - throw (new Error('Unknown key type: ' + type)); - case 'EC': - case 'ECDSA': - if (type === 'private') - return (readPkcs1ECDSAPrivate(der)); - else if (type === 'public') - return (readPkcs1ECDSAPublic(der)); - throw (new Error('Unknown key type: ' + type)); - default: - throw (new Error('Unknown key algo: ' + alg)); - } -} +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; -function readPkcs1RSAPublic(der) { - // modulus and exponent - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'exponent'); - // now, make the key - var key = { - type: 'rsa', - parts: [ - { name: 'e', data: e }, - { name: 'n', data: n } - ] - }; +/** + * Colorize log arguments if enabled. + * + * @api public + */ - return (new Key(key)); -} +function formatArgs(args) { + var useColors = this.useColors; -function readPkcs1RSAPrivate(der) { - var version = readMPInt(der, 'version'); - assert.strictEqual(version[0], 0); + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); - // modulus then public exponent - var n = readMPInt(der, 'modulus'); - var e = readMPInt(der, 'public exponent'); - var d = readMPInt(der, 'private exponent'); - var p = readMPInt(der, 'prime1'); - var q = readMPInt(der, 'prime2'); - var dmodp = readMPInt(der, 'exponent1'); - var dmodq = readMPInt(der, 'exponent2'); - var iqmp = readMPInt(der, 'iqmp'); + if (!useColors) return; - // now, make the key - var key = { - type: 'rsa', - parts: [ - { name: 'n', data: n }, - { name: 'e', data: e }, - { name: 'd', data: d }, - { name: 'iqmp', data: iqmp }, - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'dmodp', data: dmodp }, - { name: 'dmodq', data: dmodq } - ] - }; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - return (new PrivateKey(key)); + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); } -function readPkcs1DSAPrivate(der) { - var version = readMPInt(der, 'version'); - assert.strictEqual(version.readUInt8(0), 0); +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); - var y = readMPInt(der, 'y'); - var x = readMPInt(der, 'x'); +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} - // now, make the key - var key = { - type: 'dsa', - parts: [ - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g }, - { name: 'y', data: y }, - { name: 'x', data: x } - ] - }; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - return (new PrivateKey(key)); +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} } -function readPkcs1DSAPublic(der) { - var y = readMPInt(der, 'y'); - var p = readMPInt(der, 'p'); - var q = readMPInt(der, 'q'); - var g = readMPInt(der, 'g'); +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - var key = { - type: 'dsa', - parts: [ - { name: 'y', data: y }, - { name: 'p', data: p }, - { name: 'q', data: q }, - { name: 'g', data: g } - ] - }; +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - return (new Key(key)); -} + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } -function readPkcs1ECDSAPublic(der) { - der.readSequence(); + return r; +} - var oid = der.readOID(); - assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey'); +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - var curveOid = der.readOID(); +exports.enable(load()); - var curve; - var curves = Object.keys(algs.curves); - for (var j = 0; j < curves.length; ++j) { - var c = curves[j]; - var cd = algs.curves[c]; - if (cd.pkcs8oid === curveOid) { - curve = c; - break; - } - } - assert.string(curve, 'a known ECDSA named curve'); +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - var Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: new Buffer(curve) }, - { name: 'Q', data: Q } - ] - }; - return (new Key(key)); +/***/ }), +/* 203 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __webpack_require__(202); +} else { + module.exports = __webpack_require__(204); } -function readPkcs1ECDSAPrivate(der) { - var version = readMPInt(der, 'version'); - assert.strictEqual(version.readUInt8(0), 1); - // private key - var d = der.readString(asn1.Ber.OctetString, true); +/***/ }), +/* 204 */ +/***/ (function(module, exports, __webpack_require__) { - der.readSequence(0xa0); - var curve = readECDSACurve(der); - assert.string(curve, 'a known elliptic curve'); +/** + * Module dependencies. + */ - der.readSequence(0xa1); - var Q = der.readString(asn1.Ber.BitString, true); - Q = utils.ecNormalize(Q); +var tty = __webpack_require__(90); +var util = __webpack_require__(2); - var key = { - type: 'ecdsa', - parts: [ - { name: 'curve', data: new Buffer(curve) }, - { name: 'Q', data: Q }, - { name: 'd', data: d } - ] - }; +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - return (new PrivateKey(key)); -} +exports = module.exports = __webpack_require__(111); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; -function writePkcs1(der, key) { - der.startSequence(); +/** + * Colors. + */ - switch (key.type) { - case 'rsa': - if (PrivateKey.isPrivateKey(key)) - writePkcs1RSAPrivate(der, key); - else - writePkcs1RSAPublic(der, key); - break; - case 'dsa': - if (PrivateKey.isPrivateKey(key)) - writePkcs1DSAPrivate(der, key); - else - writePkcs1DSAPublic(der, key); - break; - case 'ecdsa': - if (PrivateKey.isPrivateKey(key)) - writePkcs1ECDSAPrivate(der, key); - else - writePkcs1ECDSAPublic(der, key); - break; - default: - throw (new Error('Unknown key algo: ' + key.type)); - } +exports.colors = [6, 2, 3, 4, 5, 1]; - der.endSequence(); -} +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -function writePkcs1RSAPublic(der, key) { - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); -} +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); -function writePkcs1RSAPrivate(der, key) { - var ver = new Buffer(1); - ver[0] = 0; - der.writeBuffer(ver, asn1.Ber.Integer); + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); - der.writeBuffer(key.part.n.data, asn1.Ber.Integer); - der.writeBuffer(key.part.e.data, asn1.Ber.Integer); - der.writeBuffer(key.part.d.data, asn1.Ber.Integer); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - if (!key.part.dmodp || !key.part.dmodq) - utils.addRSAMissing(key); - der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); - der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); - der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); -} + obj[prop] = val; + return obj; +}, {}); -function writePkcs1DSAPrivate(der, key) { - var ver = new Buffer(1); - ver[0] = 0; - der.writeBuffer(ver, asn1.Ber.Integer); +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); - der.writeBuffer(key.part.y.data, asn1.Ber.Integer); - der.writeBuffer(key.part.x.data, asn1.Ber.Integer); +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() } -function writePkcs1DSAPublic(der, key) { - der.writeBuffer(key.part.y.data, asn1.Ber.Integer); - der.writeBuffer(key.part.p.data, asn1.Ber.Integer); - der.writeBuffer(key.part.q.data, asn1.Ber.Integer); - der.writeBuffer(key.part.g.data, asn1.Ber.Integer); +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); } -function writePkcs1ECDSAPublic(der, key) { - der.startSequence(); +/** + * Map %o to `util.inspect()`, all on a single line. + */ - der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */ - var curve = key.part.curve.data.toString(); - var curveOid = algs.curves[curve].pkcs8oid; - assert.string(curveOid, 'a known ECDSA named curve'); - der.writeOID(curveOid); +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .replace(/\s*\n\s*/g, ' '); +}; - der.endSequence(); +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); -} +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; -function writePkcs1ECDSAPrivate(der, key) { - var ver = new Buffer(1); - ver[0] = 1; - der.writeBuffer(ver, asn1.Ber.Integer); +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - der.startSequence(0xa0); - var curve = key.part.curve.data.toString(); - var curveOid = algs.curves[curve].pkcs8oid; - assert.string(curveOid, 'a known ECDSA named curve'); - der.writeOID(curveOid); - der.endSequence(); + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - der.startSequence(0xa1); - var Q = utils.ecNormalize(key.part.Q.data, true); - der.writeBuffer(Q, asn1.Ber.BitString); - der.endSequence(); + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } } +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ -/***/ }), -/* 165 */ -/***/ (function(module, exports, __webpack_require__) { +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} -// Copyright 2015 Joyent, Inc. +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -var Key = __webpack_require__(17); -var Fingerprint = __webpack_require__(73); -var Signature = __webpack_require__(33); -var PrivateKey = __webpack_require__(18); -var Certificate = __webpack_require__(72); -var Identity = __webpack_require__(75); -var errs = __webpack_require__(32); +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} -module.exports = { - /* top-level classes */ - Key: Key, - parseKey: Key.parse, - Fingerprint: Fingerprint, - parseFingerprint: Fingerprint.parse, - Signature: Signature, - parseSignature: Signature.parse, - PrivateKey: PrivateKey, - parsePrivateKey: PrivateKey.parse, - generatePrivateKey: PrivateKey.generate, - Certificate: Certificate, - parseCertificate: Certificate.parse, - createSelfSignedCertificate: Certificate.createSelfSigned, - createCertificate: Certificate.create, - Identity: Identity, - identityFromDN: Identity.parseDN, - identityForHost: Identity.forHost, - identityForUser: Identity.forUser, - identityForEmail: Identity.forEmail, +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - /* errors */ - FingerprintFormatError: errs.FingerprintFormatError, - InvalidAlgorithmError: errs.InvalidAlgorithmError, - KeyParseError: errs.KeyParseError, - SignatureParseError: errs.SignatureParseError, - KeyEncryptedError: errs.KeyEncryptedError, - CertificateParseError: errs.CertificateParseError -}; +function load() { + return process.env.DEBUG; +} +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ -/***/ }), -/* 166 */ -/***/ (function(module, exports, __webpack_require__) { +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); -"use strict"; + // Note stream._type is used for test-module-load-list.js -var ansiRegex = __webpack_require__(181)(); + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; -module.exports = function (str) { - return typeof str === 'string' ? str.replace(ansiRegex, '') : str; -}; + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + case 'FILE': + var fs = __webpack_require__(5); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; -/***/ }), -/* 167 */ -/***/ (function(module, exports) { + case 'PIPE': + case 'TCP': + var net = __webpack_require__(59); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } - return wrapper + // For supporting legacy API we put the FD here. + stream.fd = fd; - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} + stream._isStdio = true; + return stream; +} -/***/ }), -/* 168 */ -/***/ (function(module, exports) { +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ -module.exports = require("string_decoder"); +function init (debug) { + debug.inspectOpts = {}; -/***/ }), -/* 169 */ -/***/ (function(module, exports) { + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -module.exports = require("zlib"); +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ -/***/ }), -/* 170 */ -/***/ (function(module, exports) { +exports.enable(load()); -function webpackEmptyContext(req) { - throw new Error("Cannot find module '" + req + "'."); -} -webpackEmptyContext.keys = function() { return []; }; -webpackEmptyContext.resolve = webpackEmptyContext; -module.exports = webpackEmptyContext; -webpackEmptyContext.id = 170; /***/ }), -/* 171 */ +/* 205 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = { - setup: setupAsync, - compile: compileAsync +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; + +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; }; +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } -var util = __webpack_require__(42); + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } -var ASYNC = { - '*': checkGenerators, - 'co*': checkGenerators, - 'es7': checkAsyncFunction -}; + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } -var TRANSPILE = { - 'nodent': getNodent, - 'regenerator': getRegenerator + return typeof key === 'undefined' || hasOwn.call(obj, key); }; -var MODES = [ - { async: 'co*' }, - { async: 'es7', transpile: 'nodent' }, - { async: 'co*', transpile: 'regenerator' } -]; +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } -var regenerator, nodent; + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = target[name]; + copy = options[name]; + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } -function setupAsync(opts, required) { - if (required !== false) required = true; - var async = opts.async - , transpile = opts.transpile - , check; + // Never move original objects, clone them + target[name] = extend(deep, clone, copy); - switch (typeof transpile) { - case 'string': - var get = TRANSPILE[transpile]; - if (!get) throw new Error('bad transpiler: ' + transpile); - return (opts._transpileFunc = get(opts, required)); - case 'undefined': - case 'boolean': - if (typeof async == 'string') { - check = ASYNC[async]; - if (!check) throw new Error('bad async mode: ' + async); - return (opts.transpile = check(opts, required)); - } + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + target[name] = copy; + } + } + } + } + } - for (var i=0; i<MODES.length; i++) { - var _opts = MODES[i]; - if (setupAsync(_opts, false)) { - util.copy(_opts, opts); - return opts.transpile; - } - } - /* istanbul ignore next */ - throw new Error('generators, nodent and regenerator are not available'); - case 'function': - return (opts._transpileFunc = opts.transpile); - default: - throw new Error('bad transpiler: ' + transpile); - } -} + // Return the modified object + return target; +}; -function checkGenerators(opts, required) { - /* jshint evil: true */ - try { - (new Function('(function*(){})()'))(); - return true; - } catch(e) { - /* istanbul ignore next */ - if (required) throw new Error('generators not supported'); - } -} +/***/ }), +/* 206 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -function checkAsyncFunction(opts, required) { - /* jshint evil: true */ - try { - (new Function('(async function(){})()'))(); - /* istanbul ignore next */ - return true; - } catch(e) { - if (required) throw new Error('es7 async functions not supported'); - } -} +const escapeStringRegexp = __webpack_require__(286); +const platform = process.platform; -function getRegenerator(opts, required) { - try { - if (!regenerator) { - var name = 'regenerator'; - regenerator = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); - regenerator.runtime(); - } - if (!opts.async || opts.async === true) - opts.async = 'es7'; - return regeneratorTranspile; - } catch(e) { - /* istanbul ignore next */ - if (required) throw new Error('regenerator not available'); - } -} +const main = { + tick: '✔', + cross: '✖', + star: '★', + square: 'â–‡', + squareSmall: 'â—»', + squareSmallFilled: 'â—¼', + play: 'â–¶', + circle: 'â—¯', + circleFilled: 'â—‰', + circleDotted: 'â—Œ', + circleDouble: 'â—Ž', + circleCircle: 'â“ž', + circleCross: 'ⓧ', + circlePipe: 'â’¾', + circleQuestionMark: '?âƒ', + bullet: 'â—', + dot: '․', + line: '─', + ellipsis: '…', + pointer: 'â¯', + pointerSmall: '›', + info: 'ℹ', + warning: 'âš ', + hamburger: '☰', + smiley: 'ã‹¡', + mustache: 'à·´', + heart: '♥', + arrowUp: '↑', + arrowDown: '↓', + arrowLeft: 'â†', + arrowRight: '→', + radioOn: 'â—‰', + radioOff: 'â—¯', + checkboxOn: '☒', + checkboxOff: 'â˜', + checkboxCircleOn: 'ⓧ', + checkboxCircleOff: 'â’¾', + questionMarkPrefix: '?âƒ', + oneHalf: '½', + oneThird: 'â…“', + oneQuarter: '¼', + oneFifth: 'â…•', + oneSixth: 'â…™', + oneSeventh: 'â…', + oneEighth: 'â…›', + oneNinth: 'â…‘', + oneTenth: 'â…’', + twoThirds: 'â…”', + twoFifths: 'â…–', + threeQuarters: '¾', + threeFifths: 'â…—', + threeEighths: 'â…œ', + fourFifths: 'â…˜', + fiveSixths: 'â…š', + fiveEighths: 'â…', + sevenEighths: 'â…ž' +}; +const win = { + tick: '√', + cross: '×', + star: '*', + square: 'â–ˆ', + squareSmall: '[ ]', + squareSmallFilled: '[â–ˆ]', + play: 'â–º', + circle: '( )', + circleFilled: '(*)', + circleDotted: '( )', + circleDouble: '( )', + circleCircle: '(â—‹)', + circleCross: '(×)', + circlePipe: '(│)', + circleQuestionMark: '(?)', + bullet: '*', + dot: '.', + line: '─', + ellipsis: '...', + pointer: '>', + pointerSmall: '»', + info: 'i', + warning: '‼', + hamburger: '≡', + smiley: '☺', + mustache: '┌─â”', + heart: main.heart, + arrowUp: main.arrowUp, + arrowDown: main.arrowDown, + arrowLeft: main.arrowLeft, + arrowRight: main.arrowRight, + radioOn: '(*)', + radioOff: '( )', + checkboxOn: '[×]', + checkboxOff: '[ ]', + checkboxCircleOn: '(×)', + checkboxCircleOff: '( )', + questionMarkPrefix: '?', + oneHalf: '1/2', + oneThird: '1/3', + oneQuarter: '1/4', + oneFifth: '1/5', + oneSixth: '1/6', + oneSeventh: '1/7', + oneEighth: '1/8', + oneNinth: '1/9', + oneTenth: '1/10', + twoThirds: '2/3', + twoFifths: '2/5', + threeQuarters: '3/4', + threeFifths: '3/5', + threeEighths: '3/8', + fourFifths: '4/5', + fiveSixths: '5/6', + fiveEighths: '5/8', + sevenEighths: '7/8' +}; -function regeneratorTranspile(code) { - return regenerator.compile(code).code; +if (platform === 'linux') { + // the main one doesn't look that good on Ubuntu + main.questionMarkPrefix = '?'; } +const figures = platform === 'win32' ? win : main; -function getNodent(opts, required) { - /* jshint evil: true */ - try { - if (!nodent) { - var name = 'nodent'; - nodent = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())({ log: false, dontInstallRequireHook: true }); - } - if (opts.async != 'es7') { - if (opts.async && opts.async !== true) console.warn('nodent transpiles only es7 async functions'); - opts.async = 'es7'; - } - return nodentTranspile; - } catch(e) { - /* istanbul ignore next */ - if (required) throw new Error('nodent not available'); - } -} +const fn = str => { + if (figures === main) { + return str; + } + Object.keys(main).forEach(key => { + if (main[key] === figures[key]) { + return; + } -function nodentTranspile(code) { - return nodent.compile(code, '', { promises: true, sourcemap: false }).code; -} + str = str.replace(new RegExp(escapeStringRegexp(main[key]), 'g'), figures[key]); + }); + return str; +}; -/** - * Creates validating function for passed schema with asynchronous loading of missing schemas. - * `loadSchema` option should be a function that accepts schema uri and node-style callback. - * @this Ajv - * @param {Object} schema schema object - * @param {Function} callback node-style callback, it is always called with 2 parameters: error (or null) and validating function. - */ -function compileAsync(schema, callback) { - /* eslint no-shadow: 0 */ - /* jshint validthis: true */ - var schemaObj; - var self = this; - try { - schemaObj = this._addSchema(schema); - } catch(e) { - setTimeout(function() { callback(e); }); - return; - } - if (schemaObj.validate) { - setTimeout(function() { callback(null, schemaObj.validate); }); - } else { - if (typeof this._opts.loadSchema != 'function') - throw new Error('options.loadSchema should be a function'); - _compileAsync(schema, callback, true); - } +module.exports = Object.assign(fn, figures); - function _compileAsync(schema, callback, firstCall) { - var validate; - try { validate = self.compile(schema); } - catch(e) { - if (e.missingSchema) loadMissingSchema(e); - else deferCallback(e); - return; - } - deferCallback(null, validate); +/***/ }), +/* 207 */ +/***/ (function(module, exports, __webpack_require__) { - function loadMissingSchema(e) { - var ref = e.missingSchema; - if (self._refs[ref] || self._schemas[ref]) - return callback(new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved')); - var _callbacks = self._loadingSchemas[ref]; - if (_callbacks) { - if (typeof _callbacks == 'function') - self._loadingSchemas[ref] = [_callbacks, schemaLoaded]; - else - _callbacks[_callbacks.length] = schemaLoaded; - } else { - self._loadingSchemas[ref] = schemaLoaded; - self._opts.loadSchema(ref, function (err, sch) { - var _callbacks = self._loadingSchemas[ref]; - delete self._loadingSchemas[ref]; - if (typeof _callbacks == 'function') { - _callbacks(err, sch); - } else { - for (var i=0; i<_callbacks.length; i++) - _callbacks[i](err, sch); - } - }); - } +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - function schemaLoaded(err, sch) { - if (err) return callback(err); - if (!(self._refs[ref] || self._schemas[ref])) { - try { - self.addSchema(sch, ref); - } catch(e) { - callback(e); - return; - } - } - _compileAsync(schema, callback); - } +var pathModule = __webpack_require__(0); +var isWindows = process.platform === 'win32'; +var fs = __webpack_require__(5); + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); } + } - function deferCallback(err, validate) { - if (firstCall) setTimeout(function() { callback(err, validate); }); - else return callback(err, validate); + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } } } } +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} -/***/ }), -/* 172 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - +var normalize = pathModule.normalize; -/*eslint complexity: 0*/ +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} -module.exports = function equal(a, b) { - if (a === b) return true; +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} - var arrA = Array.isArray(a) - , arrB = Array.isArray(b) - , i; +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); - if (arrA && arrB) { - if (a.length != b.length) return false; - for (i = 0; i < a.length; i++) - if (!equal(a[i], b[i])) return false; - return true; + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; } - if (arrA != arrB) return false; - - if (a && b && typeof a === 'object' && typeof b === 'object') { - var keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) return false; - - var dateA = a instanceof Date - , dateB = b instanceof Date; - if (dateA && dateB) return a.getTime() == b.getTime(); - if (dateA != dateB) return false; + var original = p, + seenLinks = {}, + knownHard = {}; - var regexpA = a instanceof RegExp - , regexpB = b instanceof RegExp; - if (regexpA && regexpB) return a.toString() == b.toString(); - if (regexpA != regexpB) return false; + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; - for (i = 0; i < keys.length; i++) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + start(); - for (i = 0; i < keys.length; i++) - if(!equal(a[keys[i]], b[keys[i]])) return false; + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; - return true; + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } } - return false; -}; + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } -/***/ }), -/* 173 */ -/***/ (function(module, exports, __webpack_require__) { + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } -"use strict"; + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } -var url = __webpack_require__(11) - , equal = __webpack_require__(172) - , util = __webpack_require__(42) - , SchemaObject = __webpack_require__(174); + if (cache) cache[original] = p; -module.exports = resolve; + return p; +}; -resolve.normalizeId = normalizeId; -resolve.fullPath = getFullPath; -resolve.url = resolveUrl; -resolve.ids = resolveIds; -resolve.inlineRef = inlineRef; -resolve.schema = resolveSchema; -/** - * [resolve and compile the references ($ref)] - * @this Ajv - * @param {Function} compile reference to schema compilation funciton (localCompile) - * @param {Object} root object with information about the root schema for the current schema - * @param {String} ref reference to resolve - * @return {Object|Function} schema object (if the schema can be inlined) or validation function - */ -function resolve(compile, root, ref) { - /* jshint validthis: true */ - var refVal = this._refs[ref]; - if (typeof refVal == 'string') { - if (this._refs[refVal]) refVal = this._refs[refVal]; - else return resolve.call(this, compile, root, refVal); +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; } - refVal = refVal || this._schemas[ref]; - if (refVal instanceof SchemaObject) { - return inlineRef(refVal.schema, this._opts.inlineRefs) - ? refVal.schema - : refVal.validate || this._compile(refVal); - } + // make p is absolute + p = pathModule.resolve(p); - var res = resolveSchema.call(this, root, ref); - var schema, v, baseId; - if (res) { - schema = res.schema; - root = res.root; - baseId = res.baseId; + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); } - if (schema instanceof SchemaObject) { - v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); - } else if (schema) { - v = inlineRef(schema, this._opts.inlineRefs) - ? schema - : compile.call(this, schema, root, undefined, baseId); - } + var original = p, + seenLinks = {}, + knownHard = {}; - return v; -} + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + start(); -/** - * Resolve schema, its root and baseId - * @this Ajv - * @param {Object} root root object with properties schema, refVal, refs - * @param {String} ref reference to resolve - * @return {Object} object with properties schema, root, baseId - */ -function resolveSchema(root, ref) { - /* jshint validthis: true */ - var p = url.parse(ref, false, true) - , refPath = _getFullPath(p) - , baseId = getFullPath(root.schema.id); - if (refPath !== baseId) { - var id = normalizeId(refPath); - var refVal = this._refs[id]; - if (typeof refVal == 'string') { - return resolveRecursive.call(this, root, refVal, p); - } else if (refVal instanceof SchemaObject) { - if (!refVal.validate) this._compile(refVal); - root = refVal; + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); } else { - refVal = this._schemas[id]; - if (refVal instanceof SchemaObject) { - if (!refVal.validate) this._compile(refVal); - if (id == normalizeId(ref)) - return { schema: refVal, root: root, baseId: baseId }; - root = refVal; - } else { - return; - } + process.nextTick(LOOP); } - if (!root.schema) return; - baseId = getFullPath(root.schema.id); - } - return getJsonPointer.call(this, p, baseId, root.schema, root); -} - - -/* @this Ajv */ -function resolveRecursive(root, ref, parsedRef) { - /* jshint validthis: true */ - var res = resolveSchema.call(this, root, ref); - if (res) { - var schema = res.schema; - var baseId = res.baseId; - root = res.root; - if (schema.id) baseId = resolveUrl(baseId, schema.id); - return getJsonPointer.call(this, parsedRef, baseId, schema, root); } -} + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } -var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); -/* @this Ajv */ -function getJsonPointer(parsedRef, baseId, schema, root) { - /* jshint validthis: true */ - parsedRef.hash = parsedRef.hash || ''; - if (parsedRef.hash.slice(0,2) != '#/') return; - var parts = parsedRef.hash.split('/'); + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; - for (var i = 1; i < parts.length; i++) { - var part = parts[i]; - if (part) { - part = util.unescapeFragment(part); - schema = schema[part]; - if (!schema) break; - if (schema.id && !PREVENT_SCOPE_CHANGE[part]) baseId = resolveUrl(baseId, schema.id); - if (schema.$ref) { - var $ref = resolveUrl(baseId, schema.$ref); - var res = resolveSchema.call(this, root, $ref); - if (res) { - schema = res.schema; - root = res.root; - baseId = res.baseId; - } - } + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); } - } - if (schema && schema != root.schema) - return { schema: schema, root: root, baseId: baseId }; -} + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } -var SIMPLE_INLINED = util.toHash([ - 'type', 'format', 'pattern', - 'maxLength', 'minLength', - 'maxProperties', 'minProperties', - 'maxItems', 'minItems', - 'maximum', 'minimum', - 'uniqueItems', 'multipleOf', - 'required', 'enum' -]); -function inlineRef(schema, limit) { - if (limit === false) return false; - if (limit === undefined || limit === true) return checkNoRef(schema); - else if (limit) return countKeys(schema) <= limit; -} + return fs.lstat(base, gotStat); + } + function gotStat(err, stat) { + if (err) return cb(err); -function checkNoRef(schema) { - var item; - if (Array.isArray(schema)) { - for (var i=0; i<schema.length; i++) { - item = schema[i]; - if (typeof item == 'object' && !checkNoRef(item)) return false; + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); } - } else { - for (var key in schema) { - if (key == '$ref') return false; - item = schema[key]; - if (typeof item == 'object' && !checkNoRef(item)) return false; + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); } - return true; -} + function gotTarget(err, target, base) { + if (err) return cb(err); -function countKeys(schema) { - var count = 0, item; - if (Array.isArray(schema)) { - for (var i=0; i<schema.length; i++) { - item = schema[i]; - if (typeof item == 'object') count += countKeys(item); - if (count == Infinity) return Infinity; - } - } else { - for (var key in schema) { - if (key == '$ref') return Infinity; - if (SIMPLE_INLINED[key]) { - count++; - } else { - item = schema[key]; - if (typeof item == 'object') count += countKeys(item) + 1; - if (count == Infinity) return Infinity; - } - } + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); } - return count; -} + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; -function getFullPath(id, normalize) { - if (normalize !== false) id = normalizeId(id); - var p = url.parse(id, false, true); - return _getFullPath(p); -} +/***/ }), +/* 208 */ +/***/ (function(module, exports, __webpack_require__) { +module.exports = globSync +globSync.GlobSync = GlobSync -function _getFullPath(p) { - var protocolSeparator = p.protocol || p.href.slice(0,2) == '//' ? '//' : ''; - return (p.protocol||'') + protocolSeparator + (p.host||'') + (p.path||'') + '#'; -} +var fs = __webpack_require__(5) +var rp = __webpack_require__(112) +var minimatch = __webpack_require__(57) +var Minimatch = minimatch.Minimatch +var Glob = __webpack_require__(71).Glob +var util = __webpack_require__(2) +var path = __webpack_require__(0) +var assert = __webpack_require__(18) +var isAbsolute = __webpack_require__(73) +var common = __webpack_require__(113) +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') -var TRAILING_SLASH_HASH = /#\/?$/; -function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; + return new GlobSync(pattern, options).found } +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') -function resolveUrl(baseId, id) { - id = normalizeId(id); - return url.resolve(baseId, id); -} + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) -/* @this Ajv */ -function resolveIds(schema) { - /* eslint no-shadow: 0 */ - /* jshint validthis: true */ - var id = normalizeId(schema.id); - var localRefs = {}; - _resolveIds.call(this, schema, getFullPath(id, false), id); - return localRefs; + setopts(this, pattern, options) - /* @this Ajv */ - function _resolveIds(schema, fullPath, baseId) { - /* jshint validthis: true */ - if (Array.isArray(schema)) { - for (var i=0; i<schema.length; i++) - _resolveIds.call(this, schema[i], fullPath+'/'+i, baseId); - } else if (schema && typeof schema == 'object') { - if (typeof schema.id == 'string') { - var id = baseId = baseId - ? url.resolve(baseId, schema.id) - : schema.id; - id = normalizeId(id); + if (this.noprocess) + return this - var refVal = this._refs[id]; - if (typeof refVal == 'string') refVal = this._refs[refVal]; - if (refVal && refVal.schema) { - if (!equal(schema, refVal.schema)) - throw new Error('id "' + id + '" resolves to more than one schema'); - } else if (id != normalizeId(fullPath)) { - if (id[0] == '#') { - if (localRefs[id] && !equal(schema, localRefs[id])) - throw new Error('id "' + id + '" resolves to more than one schema'); - localRefs[id] = schema; - } else { - this._refs[id] = fullPath; - } + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er } } - for (var key in schema) - _resolveIds.call(this, schema[key], fullPath+'/'+util.escapeFragment(key), baseId); - } + }) } + common.finish(this) } -/***/ }), -/* 174 */ -/***/ (function(module, exports, __webpack_require__) { +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) -"use strict"; + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break -var util = __webpack_require__(42); + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } -module.exports = SchemaObject; + var remain = pattern.slice(n) -function SchemaObject(obj) { - util.copy(obj, this); -} + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + var abs = this._makeAbs(read) -/***/ }), -/* 175 */ -/***/ (function(module, exports, __webpack_require__) { + //if ignored, skip processing + if (childrenIgnored(this, read)) + return -"use strict"; + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} -module.exports = ValidationError; +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + // if the abs isn't a dir, then nothing can match! + if (!entries) + return -function ValidationError(errors) { - this.message = 'validation failed'; - this.errors = errors; - this.ajv = this.validation = true; -} + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } -ValidationError.prototype = Object.create(Error.prototype); -ValidationError.prototype.constructor = ValidationError; + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. -/***/ }), -/* 176 */ -/***/ (function(module, exports, __webpack_require__) { + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) -"use strict"; + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } -module.exports = function generate__limit(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return } - var $isMax = $keyword == 'maximum', - $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', - $schemaExcl = it.schema[$exclusiveKeyword], - $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data, - $op = $isMax ? '<' : '>', - $notOp = $isMax ? '>' : '<'; - if ($isDataExcl) { - var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), - $exclusive = 'exclusive' + $lvl, - $opExpr = 'op' + $lvl, - $opStr = '\' + ' + $opExpr + ' + \''; - out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; - $schemaValueExcl = 'schemaExcl' + $lvl; - out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { '; - var $errorKeyword = $exclusiveKeyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else if( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; - } else { - var $exclusive = $schemaExcl === true, - $opStr = $op; - if (!$exclusive) $opStr += '='; - var $opExpr = '\'' + $opStr + '\''; - out += ' if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - out += ' ' + ($data) + ' ' + ($notOp); - if ($exclusive) { - out += '='; - } - out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {'; + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) } - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be ' + ($opStr) + ' '; - if ($isData) { - out += '\' + ' + ($schemaValue); - } else { - out += '' + ($schema) + '\''; - } - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return } - out += ' } '; - if ($breakOnError) { - out += ' else { '; + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } } - return out; + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries } +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries -/***/ }), -/* 177 */ -/***/ (function(module, exports, __webpack_require__) { + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) -"use strict"; + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null -module.exports = function generate__limitItems(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; + if (Array.isArray(c)) + return c } - var $op = $keyword == 'maxItems' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null } - out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have '; - if ($keyword == 'maxItems') { - out += 'more'; - } else { - out += 'less'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); - } - out += ' items\' '; +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; } - return out; + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) } +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' -/***/ }), -/* 178 */ -/***/ (function(module, exports, __webpack_require__) { + if (f.length > this.maxLength) + return false -"use strict"; + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] -module.exports = function generate__limitLength(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $op = $keyword == 'maxLength' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; - } - if (it.opts.unicode === false) { - out += ' ' + ($data) + '.length '; - } else { - out += ' ucs2length(' + ($data) + ') '; + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. } - out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT be '; - if ($keyword == 'maxLength') { - out += 'longer'; - } else { - out += 'shorter'; - } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + ($schema); + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false } - out += ' characters\' '; } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; + stat = lstat } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; } - return out; + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) } /***/ }), -/* 179 */ +/* 209 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Load modules -module.exports = function generate__limitProperties(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; +var Crypto = __webpack_require__(8); +var Url = __webpack_require__(14); +var Utils = __webpack_require__(131); + + +// Declare internals + +var internals = {}; + + +// MAC normalization format version + +exports.headerVersion = '1'; // Prevent comparison of mac values generated with different normalized string formats + + +// Supported HMAC algorithms + +exports.algorithms = ['sha1', 'sha256']; + + +// Calculate the request MAC + +/* + type: 'header', // 'header', 'bewit', 'response' + credentials: { + key: 'aoijedoaijsdlaksjdl', + algorithm: 'sha256' // 'sha1', 'sha256' + }, + options: { + method: 'GET', + resource: '/resource?a=1&b=2', + host: 'example.com', + port: 8080, + ts: 1357718381034, + nonce: 'd3d345f', + hash: 'U4MKKSmiVxk37JCCrAVIjV/OhB3y+NdwoCr6RShbVkE=', + ext: 'app-specific-data', + app: 'hf48hd83qwkj', // Application id (Oz) + dlg: 'd8djwekds9cj' // Delegated by application id (Oz), requires options.app + } +*/ + +exports.calculateMac = function (type, credentials, options) { + + var normalized = exports.generateNormalizedString(type, options); + + var hmac = Crypto.createHmac(credentials.algorithm, credentials.key).update(normalized); + var digest = hmac.digest('base64'); + return digest; +}; + + +exports.generateNormalizedString = function (type, options) { + + var resource = options.resource || ''; + if (resource && + resource[0] !== '/') { + + var url = Url.parse(resource, false); + resource = url.path; // Includes query + } + + var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' + + options.ts + '\n' + + options.nonce + '\n' + + (options.method || '').toUpperCase() + '\n' + + resource + '\n' + + options.host.toLowerCase() + '\n' + + options.port + '\n' + + (options.hash || '') + '\n'; + + if (options.ext) { + normalized += options.ext.replace('\\', '\\\\').replace('\n', '\\n'); + } + + normalized += '\n'; + + if (options.app) { + normalized += options.app + '\n' + + (options.dlg || '') + '\n'; + } + + return normalized; +}; + + +exports.calculatePayloadHash = function (payload, algorithm, contentType) { + + var hash = exports.initializePayloadHash(algorithm, contentType); + hash.update(payload || ''); + return exports.finalizePayloadHash(hash); +}; + + +exports.initializePayloadHash = function (algorithm, contentType) { + + var hash = Crypto.createHash(algorithm); + hash.update('hawk.' + exports.headerVersion + '.payload\n'); + hash.update(Utils.parseContentType(contentType) + '\n'); + return hash; +}; + + +exports.finalizePayloadHash = function (hash) { + + hash.update('\n'); + return hash.digest('base64'); +}; + + +exports.calculateTsMac = function (ts, credentials) { + + var hmac = Crypto.createHmac(credentials.algorithm, credentials.key); + hmac.update('hawk.' + exports.headerVersion + '.ts\n' + ts + '\n'); + return hmac.digest('base64'); +}; + + +exports.timestampMessage = function (credentials, localtimeOffsetMsec) { + + var now = Utils.nowSecs(localtimeOffsetMsec); + var tsm = exports.calculateTsMac(now, credentials); + return { ts: now, tsm: tsm }; +}; + + +/***/ }), +/* 210 */ +/***/ (function(module, exports, __webpack_require__) { + +var wrappy = __webpack_require__(89) +var reqs = Object.create(null) +var once = __webpack_require__(72) + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null } else { - $schemaValue = $schema; - } - var $op = $keyword == 'maxProperties' ? '>' : '<'; - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + reqs[key] = [cb] + return makeres(key) } - out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have '; - if ($keyword == 'maxProperties') { - out += 'more'; - } else { - out += 'less'; +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) } - out += ' than '; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) } else { - out += '' + ($schema); + delete reqs[key] } - out += ' properties\' '; } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} + + +/***/ }), +/* 211 */ +/***/ (function(module, exports) { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor } - return out; } /***/ }), -/* 180 */ +/* 212 */ +/***/ (function(module, exports, __webpack_require__) { + +/** + * Inquirer.js + * A collection of common interactive command line user interfaces. + */ + +var inquirer = module.exports; + +/** + * Client interfaces + */ + +inquirer.prompts = {}; + +inquirer.Separator = __webpack_require__(135); + +inquirer.ui = { + BottomBar: __webpack_require__(541), + Prompt: __webpack_require__(542) +}; + +/** + * Create a new self-contained prompt module. + */ +inquirer.createPromptModule = function (opt) { + var promptModule = function (questions) { + var ui = new inquirer.ui.Prompt(promptModule.prompts, opt); + var promise = ui.run(questions); + + // Monkey patch the UI on the promise object so + // that it remains publicly accessible. + promise.ui = ui; + + return promise; + }; + promptModule.prompts = {}; + + /** + * Register a prompt type + * @param {String} name Prompt type name + * @param {Function} prompt Prompt constructor + * @return {inquirer} + */ + + promptModule.registerPrompt = function (name, prompt) { + promptModule.prompts[name] = prompt; + return this; + }; + + /** + * Register the defaults provider prompts + */ + + promptModule.restoreDefaultPrompts = function () { + this.registerPrompt('list', __webpack_require__(538)); + this.registerPrompt('input', __webpack_require__(537)); + this.registerPrompt('confirm', __webpack_require__(534)); + this.registerPrompt('rawlist', __webpack_require__(540)); + this.registerPrompt('expand', __webpack_require__(536)); + this.registerPrompt('checkbox', __webpack_require__(533)); + this.registerPrompt('password', __webpack_require__(539)); + this.registerPrompt('editor', __webpack_require__(535)); + }; + + promptModule.restoreDefaultPrompts(); + + return promptModule; +}; + +/** + * Public CLI helper interface + * @param {Array|Object|rx.Observable} questions - Questions settings array + * @param {Function} cb - Callback being passed the user answers + * @return {inquirer.ui.Prompt} + */ + +inquirer.prompt = inquirer.createPromptModule(); + +// Expose helper functions on the top level for easiest usage by common users +inquirer.registerPrompt = function (name, prompt) { + inquirer.prompt.registerPrompt(name, prompt); +}; +inquirer.restoreDefaultPrompts = function () { + inquirer.prompt.restoreDefaultPrompts(); +}; + + +/***/ }), +/* 213 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -module.exports = function generate_validate(it, $keyword) { - var out = ''; - var $async = it.schema.$async === true; - if (it.isTop) { - var $top = it.isTop, - $lvl = it.level = 0, - $dataLvl = it.dataLevel = 0, - $data = 'data'; - it.rootId = it.resolve.fullPath(it.root.schema.id); - it.baseId = it.baseId || it.rootId; - if ($async) { - it.async = true; - var $es7 = it.opts.async == 'es7'; - it.yieldAwait = $es7 ? 'await' : 'yield'; + +module.exports = __webpack_require__(456).isCI + + +/***/ }), +/* 214 */ +/***/ (function(module, exports, __webpack_require__) { + +// @flow + +/*:: +declare var __webpack_require__: mixed; +*/ + +module.exports = typeof __webpack_require__ !== "undefined"; + + +/***/ }), +/* 215 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +/* + * Copyright (c) 2014 Mega Limited + * under the MIT License. + * + * Authors: Guy K. Kloss + * + * You should have received a copy of the license along with this program. + */ + +var dh = __webpack_require__(559); +var eddsa = __webpack_require__(560); +var curve255 = __webpack_require__(216); +var utils = __webpack_require__(140); + + /** + * @exports jodid25519 + * Curve 25519-based cryptography collection. + * + * @description + * EC Diffie-Hellman (ECDH) based on Curve25519 and digital signatures + * (EdDSA) based on Ed25519. + */ + var ns = {}; + + /** Module version indicator as string (format: [major.minor.patch]). */ + ns.VERSION = '0.7.1'; + + ns.dh = dh; + ns.eddsa = eddsa; + ns.curve255 = curve255; + ns.utils = utils; + +module.exports = ns; + + +/***/ }), +/* 216 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +/** + * @fileOverview + * Core operations on curve 25519 required for the higher level modules. + */ + +/* + * Copyright (c) 2007, 2013, 2014 Michele Bini + * Copyright (c) 2014 Mega Limited + * under the MIT License. + * + * Authors: Guy K. Kloss, Michele Bini + * + * You should have received a copy of the license along with this program. + */ + +var core = __webpack_require__(139); +var utils = __webpack_require__(140); + + /** + * @exports jodid25519/curve255 + * Legacy compatibility module for Michele Bini's previous curve255.js. + * + * @description + * Legacy compatibility module for Michele Bini's previous curve255.js. + * + * <p> + * This code presents an API with all key formats as previously available + * from Michele Bini's curve255.js implementation. + * </p> + */ + var ns = {}; + + function curve25519_raw(f, c) { + var a, x_1, q; + + x_1 = c; + a = core.dbl(x_1, core.ONE()); + q = [x_1, core.ONE()]; + + var n = 255; + + while (core.getbit(f, n) == 0) { + n--; + // For correct constant-time operation, bit 255 should always be + // set to 1 so the following 'while' loop is never entered. + if (n < 0) { + return core.ZERO(); + } + } + n--; + + var aq = [a, q]; + + while (n >= 0) { + var r, s; + var b = core.getbit(f, n); + r = core.sum(aq[0][0], aq[0][1], aq[1][0], aq[1][1], x_1); + s = core.dbl(aq[1 - b][0], aq[1 - b][1]); + aq[1 - b] = s; + aq[b] = r; + n--; + } + q = aq[1]; + + q[1] = core.invmodp(q[1]); + q[0] = core.mulmodp(q[0], q[1]); + core.reduce(q[0]); + return q[0]; } - delete it.isTop; - it.dataPathArr = [undefined]; - out += ' var validate = '; - if ($async) { - if ($es7) { - out += ' (async function '; - } else { - if (it.opts.async == 'co*') { - out += 'co.wrap'; + + function curve25519b32(a, b) { + return _base32encode(curve25519(_base32decode(a), + _base32decode(b))); + } + + function curve25519(f, c) { + if (!c) { + c = core.BASE(); } - out += '(function* '; - } - } else { - out += ' (function '; + f[0] &= 0xFFF8; + f[15] = (f[15] & 0x7FFF) | 0x4000; + return curve25519_raw(f, c); } - out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; var vErrors = null; '; - out += ' var errors = 0; '; - out += ' if (rootData === undefined) rootData = data;'; - } else { - var $lvl = it.level, - $dataLvl = it.dataLevel, - $data = 'data' + ($dataLvl || ''); - if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id); - if ($async && !it.async) throw new Error('async schema in sync schema'); - out += ' var errs_' + ($lvl) + ' = errors;'; - } - var $valid = 'valid' + $lvl, - $breakOnError = !it.opts.allErrors, - $closingBraces1 = '', - $closingBraces2 = ''; - var $typeSchema = it.schema.type, - $typeIsArray = Array.isArray($typeSchema); - if ($typeSchema && it.opts.coerceTypes) { - var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); - if ($coerceToTypes) { - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type', - $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; - out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; - var $dataType = 'dataType' + $lvl, - $coerced = 'coerced' + $lvl; - out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; '; - if (it.opts.coerceTypes == 'array') { - out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; '; - } - out += ' var ' + ($coerced) + ' = undefined; '; - var $bracesCoercion = ''; - var arr1 = $coerceToTypes; - if (arr1) { - var $type, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $type = arr1[$i += 1]; - if ($i) { - out += ' if (' + ($coerced) + ' === undefined) { '; - $bracesCoercion += '}'; - } - if (it.opts.coerceTypes == 'array' && $type != 'array') { - out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } '; - } - if ($type == 'string') { - out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; - } else if ($type == 'number' || $type == 'integer') { - out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; - if ($type == 'integer') { - out += ' && !(' + ($data) + ' % 1)'; - } - out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; - } else if ($type == 'boolean') { - out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; - } else if ($type == 'null') { - out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; - } else if (it.opts.coerceTypes == 'array' && $type == 'array') { - out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; - } - } - } - out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { '; - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' ' + ($data) + ' = ' + ($coerced) + '; '; - if (!$dataLvl) { - out += 'if (' + ($parentData) + ' !== undefined)'; - } - out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } '; - } - } - var $refKeywords; - if (it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'))) { - if (it.opts.extendRefs == 'fail') { - throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"'); - } else if (it.opts.extendRefs == 'ignore') { - $refKeywords = false; - console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); - } else if (it.opts.extendRefs !== true) { - console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour'); - } - } - if (it.schema.$ref && !$refKeywords) { - out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; - if ($breakOnError) { - out += ' } if (errors === '; - if ($top) { - out += '0'; - } else { - out += 'errs_' + ($lvl); - } - out += ') { '; - $closingBraces2 += '}'; - } - } else { - var arr2 = it.RULES; - if (arr2) { - var $rulesGroup, i2 = -1, - l2 = arr2.length - 1; - while (i2 < l2) { - $rulesGroup = arr2[i2 += 1]; - if ($shouldUseGroup($rulesGroup)) { - if ($rulesGroup.type) { - out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { '; - } - if (it.opts.useDefaults && !it.compositeRule) { - if ($rulesGroup.type == 'object' && it.schema.properties) { - var $schema = it.schema.properties, - $schemaKeys = Object.keys($schema); - var arr3 = $schemaKeys; - if (arr3) { - var $propertyKey, i3 = -1, - l3 = arr3.length - 1; - while (i3 < l3) { - $propertyKey = arr3[i3 += 1]; - var $sch = $schema[$propertyKey]; - if ($sch.default !== undefined) { - var $passData = $data + it.util.getProperty($propertyKey); - out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; - if (it.opts.useDefaults == 'shared') { - out += ' ' + (it.useDefault($sch.default)) + ' '; - } else { - out += ' ' + (JSON.stringify($sch.default)) + ' '; - } - out += '; '; - } - } - } - } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { - var arr4 = it.schema.items; - if (arr4) { - var $sch, $i = -1, - l4 = arr4.length - 1; - while ($i < l4) { - $sch = arr4[$i += 1]; - if ($sch.default !== undefined) { - var $passData = $data + '[' + $i + ']'; - out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; - if (it.opts.useDefaults == 'shared') { - out += ' ' + (it.useDefault($sch.default)) + ' '; - } else { - out += ' ' + (JSON.stringify($sch.default)) + ' '; - } - out += '; '; - } - } - } - } - } - var arr5 = $rulesGroup.rules; - if (arr5) { - var $rule, i5 = -1, - l5 = arr5.length - 1; - while (i5 < l5) { - $rule = arr5[i5 += 1]; - if ($shouldUseRule($rule)) { - out += ' ' + ($rule.code(it, $rule.keyword)) + ' '; - if ($breakOnError) { - $closingBraces1 += '}'; - } - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces1) + ' '; - $closingBraces1 = ''; - } - if ($rulesGroup.type) { - out += ' } '; - if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { - var $typeChecked = true; - out += ' else { '; - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type'; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - } - } - if ($breakOnError) { - out += ' if (errors === '; - if ($top) { - out += '0'; - } else { - out += 'errs_' + ($lvl); - } - out += ') { '; - $closingBraces2 += '}'; - } - } - } - } - } - if ($typeSchema && !$typeChecked && !$coerceToTypes) { - var $schemaPath = it.schemaPath + '.type', - $errSchemaPath = it.errSchemaPath + '/type', - $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; - out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be '; - if ($typeIsArray) { - out += '' + ($typeSchema.join(",")); - } else { - out += '' + ($typeSchema); - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' }'; - } - if ($breakOnError) { - out += ' ' + ($closingBraces2) + ' '; - } - if ($top) { - if ($async) { - out += ' if (errors === 0) return true; '; - out += ' else throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; '; - out += ' return errors === 0; '; + + function _hexEncodeVector(k) { + var hexKey = utils.hexEncode(k); + // Pad with '0' at the front. + hexKey = new Array(64 + 1 - hexKey.length).join('0') + hexKey; + // Invert bytes. + return hexKey.split(/(..)/).reverse().join(''); } - out += ' }); return validate;'; - } else { - out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; - } - out = it.util.cleanUpCode(out); - if ($top && $breakOnError) { - out = it.util.cleanUpVarErrors(out, $async); - } - function $shouldUseGroup($rulesGroup) { - for (var i = 0; i < $rulesGroup.rules.length; i++) - if ($shouldUseRule($rulesGroup.rules[i])) return true; - } + function _hexDecodeVector(v) { + // assert(length(x) == 64); + // Invert bytes. + var hexKey = v.split(/(..)/).reverse().join(''); + return utils.hexDecode(hexKey); + } - function $shouldUseRule($rule) { - return it.schema[$rule.keyword] !== undefined || ($rule.keyword == 'properties' && (it.schema.additionalProperties === false || typeof it.schema.additionalProperties == 'object' || (it.schema.patternProperties && Object.keys(it.schema.patternProperties).length) || (it.opts.v5 && it.schema.patternGroups && Object.keys(it.schema.patternGroups).length))); - } - return out; -} + // Expose some functions to the outside through this name space. -/***/ }), -/* 181 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Computes the scalar product of a point on the curve 25519. + * + * This function is used for the DH key-exchange protocol. + * + * Before multiplication, some bit operations are applied to the + * private key to ensure it is a valid Curve25519 secret key. + * It is the user's responsibility to make sure that the private + * key is a uniformly random, secret value. + * + * @function + * @param f {array} + * Private key. + * @param c {array} + * Public point on the curve. If not given, the curve's base point is used. + * @returns {array} + * Key point resulting from scalar product. + */ + ns.curve25519 = curve25519; -"use strict"; + /** + * Computes the scalar product of a point on the curve 25519. + * + * This variant does not make sure that the private key is valid. + * The user has the responsibility to ensure the private key is + * valid or that this results in a safe protocol. Unless you know + * exactly what you are doing, you should not use this variant, + * please use 'curve25519' instead. + * + * @function + * @param f {array} + * Private key. + * @param c {array} + * Public point on the curve. If not given, the curve's base point is used. + * @returns {array} + * Key point resulting from scalar product. + */ + ns.curve25519_raw = curve25519_raw; -module.exports = function () { - return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; -}; + /** + * Encodes the internal representation of a key to a canonical hex + * representation. + * + * This is the format commonly used in other libraries and for + * test vectors, and is equivalent to the hex dump of the key in + * little-endian binary format. + * + * @function + * @param n {array} + * Array representation of key. + * @returns {string} + * Hexadecimal string representation of key. + */ + ns.hexEncodeVector = _hexEncodeVector; + /** + * Decodes a canonical hex representation of a key + * to an internally compatible array representation. + * + * @function + * @param n {string} + * Hexadecimal string representation of key. + * @returns {array} + * Array representation of key. + */ + ns.hexDecodeVector = _hexDecodeVector; -/***/ }), -/* 182 */ -/***/ (function(module, exports) { + /** + * Encodes the internal representation of a key into a + * hexadecimal representation. + * + * This is a strict positional notation, most significant digit first. + * + * @function + * @param n {array} + * Array representation of key. + * @returns {string} + * Hexadecimal string representation of key. + */ + ns.hexencode = utils.hexEncode; -// API -module.exports = abort; + /** + * Decodes a hex representation of a key to an internally + * compatible array representation. + * + * @function + * @param n {string} + * Hexadecimal string representation of key. + * @returns {array} + * Array representation of key. + */ + ns.hexdecode = utils.hexDecode; -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); + /** + * Encodes the internal representation of a key to a base32 + * representation. + * + * @function + * @param n {array} + * Array representation of key. + * @returns {string} + * Base32 string representation of key. + */ + ns.base32encode = utils.base32encode; - // reset leftover jobs - state.jobs = {}; -} + /** + * Decodes a base32 representation of a key to an internally + * compatible array representation. + * + * @function + * @param n {string} + * Base32 string representation of key. + * @returns {array} + * Array representation of key. + */ + ns.base32decode = utils.base32decode; -/** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort - */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); - } -} +module.exports = ns; /***/ }), -/* 183 */ +/* 217 */ /***/ (function(module, exports, __webpack_require__) { -var defer = __webpack_require__(325); - -// API -module.exports = async; +var json = typeof JSON !== 'undefined' ? JSON : __webpack_require__(563); -/** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback - */ -function async(callback) -{ - var isAsync = false; +module.exports = function (obj, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { cmp: opts }; + var space = opts.space || ''; + if (typeof space === 'number') space = Array(space+1).join(' '); + var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; + var replacer = opts.replacer || function(key, value) { return value; }; - // check if async happened - defer(function() { isAsync = true; }); + var cmp = opts.cmp && (function (f) { + return function (node) { + return function (a, b) { + var aobj = { key: a, value: node[a] }; + var bobj = { key: b, value: node[b] }; + return f(aobj, bobj); + }; + }; + })(opts.cmp); - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; -} + var seen = []; + return (function stringify (parent, key, node, level) { + var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; + var colonSeparator = space ? ': ' : ':'; + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } -/***/ }), -/* 184 */ -/***/ (function(module, exports, __webpack_require__) { + node = replacer.call(parent, key, node); -var async = __webpack_require__(183) - , abort = __webpack_require__(182) - ; + if (node === undefined) { + return; + } + if (typeof node !== 'object' || node === null) { + return json.stringify(node); + } + if (isArray(node)) { + var out = []; + for (var i = 0; i < node.length; i++) { + var item = stringify(node, i, node[i], level+1) || json.stringify(null); + out.push(indent + space + item); + } + return '[' + out.join(',') + indent + ']'; + } + else { + if (seen.indexOf(node) !== -1) { + if (cycles) return json.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } + else seen.push(node); -// API -module.exports = iterate; + var keys = objectKeys(node).sort(cmp && cmp(node)); + var out = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node, key, node[key], level+1); -/** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed - */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + if(!value) continue; - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } + var keyValue = json.stringify(key) + + colonSeparator + + value; + ; + out.push(indent + space + keyValue); + } + seen.splice(seen.indexOf(node), 1); + return '{' + out.join(',') + indent + '}'; + } + })({ '': obj }, '', obj, 0); +}; - // clean up jobs - delete state.jobs[key]; +var isArray = Array.isArray || function (x) { + return {}.toString.call(x) === '[object Array]'; +}; - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; +var objectKeys = Object.keys || function (obj) { + var has = Object.prototype.hasOwnProperty || function () { return true }; + var keys = []; + for (var key in obj) { + if (has.call(obj, key)) keys.push(key); } + return keys; +}; - // return salvaged results - callback(error, state.results); - }); -} + +/***/ }), +/* 218 */ +/***/ (function(module, exports, __webpack_require__) { + +var isBuffer = __webpack_require__(547); +var toString = Object.prototype.toString; /** - * Runs iterator over provided job element + * Get the native `typeof` a value. * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else + * @param {*} `val` + * @return {*} Native javascript type */ -function runJob(iterator, key, item, callback) -{ - var aborter; - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); +module.exports = function kindOf(val) { + // primitivies + if (typeof val === 'undefined') { + return 'undefined'; } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); + if (val === null) { + return 'null'; + } + if (val === true || val === false || val instanceof Boolean) { + return 'boolean'; + } + if (typeof val === 'string' || val instanceof String) { + return 'string'; + } + if (typeof val === 'number' || val instanceof Number) { + return 'number'; } - return aborter; -} + // functions + if (typeof val === 'function' || val instanceof Function) { + return 'function'; + } + // array + if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) { + return 'array'; + } -/***/ }), -/* 185 */ -/***/ (function(module, exports) { + // check for instances of RegExp and Date before calling `toString` + if (val instanceof RegExp) { + return 'regexp'; + } + if (val instanceof Date) { + return 'date'; + } -// API -module.exports = state; + // other objects + var type = toString.call(val); -/** - * Creates initial state object - * for iteration over list - * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object - */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length - } - ; + if (type === '[object RegExp]') { + return 'regexp'; + } + if (type === '[object Date]') { + return 'date'; + } + if (type === '[object Arguments]') { + return 'arguments'; + } + if (type === '[object Error]') { + return 'error'; + } - if (sortMethod) - { - // sort array keys based on it's values - // sort object's keys just on own merit - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) - { - return sortMethod(list[a], list[b]); - }); + // buffer + if (isBuffer(val)) { + return 'buffer'; } - return initState; -} + // es6: Map, WeakMap, Set, WeakSet + if (type === '[object Set]') { + return 'set'; + } + if (type === '[object WeakSet]') { + return 'weakset'; + } + if (type === '[object Map]') { + return 'map'; + } + if (type === '[object WeakMap]') { + return 'weakmap'; + } + if (type === '[object Symbol]') { + return 'symbol'; + } + + // typed arrays + if (type === '[object Int8Array]') { + return 'int8array'; + } + if (type === '[object Uint8Array]') { + return 'uint8array'; + } + if (type === '[object Uint8ClampedArray]') { + return 'uint8clampedarray'; + } + if (type === '[object Int16Array]') { + return 'int16array'; + } + if (type === '[object Uint16Array]') { + return 'uint16array'; + } + if (type === '[object Int32Array]') { + return 'int32array'; + } + if (type === '[object Uint32Array]') { + return 'uint32array'; + } + if (type === '[object Float32Array]') { + return 'float32array'; + } + if (type === '[object Float64Array]') { + return 'float64array'; + } + + // must be a plain object + return 'object'; +}; /***/ }), -/* 186 */ +/* 219 */ /***/ (function(module, exports, __webpack_require__) { -var abort = __webpack_require__(182) - , async = __webpack_require__(183) - ; +"use strict"; +/*! + * micromatch <https://github.com/jonschlinkert/micromatch> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ + -// API -module.exports = terminator; + +var expand = __webpack_require__(569); +var utils = __webpack_require__(220); /** - * Terminates jobs in the attached state context + * The main function. Pass an array of filepaths, + * and a string or array of glob patterns * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination + * @param {Array|String} `files` + * @param {Array|String} `patterns` + * @param {Object} `opts` + * @return {Array} Array of matches */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; + +function micromatch(files, patterns, opts) { + if (!files || !patterns) return []; + opts = opts || {}; + + if (typeof opts.cache === 'undefined') { + opts.cache = true; } - // fast forward iteration index - this.index = this.size; + if (!Array.isArray(patterns)) { + return match(files, patterns, opts); + } - // abort jobs - abort(this); + var len = patterns.length, i = 0; + var omit = [], keep = []; - // send back results we have so far - async(callback)(null, this.results); + while (len--) { + var glob = patterns[i++]; + if (typeof glob === 'string' && glob.charCodeAt(0) === 33 /* ! */) { + omit.push.apply(omit, match(files, glob.slice(1), opts)); + } else { + keep.push.apply(keep, match(files, glob, opts)); + } + } + return utils.diff(keep, omit); } +/** + * Return an array of files that match the given glob pattern. + * + * This function is called by the main `micromatch` function If you only + * need to pass a single pattern you might get very minor speed improvements + * using this function. + * + * @param {Array} `files` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Array} + */ -/***/ }), -/* 187 */ -/***/ (function(module, exports, __webpack_require__) { +function match(files, pattern, opts) { + if (utils.typeOf(files) !== 'string' && !Array.isArray(files)) { + throw new Error(msg('match', 'files', 'a string or array')); + } -var iterate = __webpack_require__(184) - , initState = __webpack_require__(185) - , terminator = __webpack_require__(186) - ; + files = utils.arrayify(files); + opts = opts || {}; -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; + var negate = opts.negate || false; + var orig = pattern; -/** - * Runs iterator over provided sorted array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); + if (typeof pattern === 'string') { + negate = pattern.charAt(0) === '!'; + if (negate) { + pattern = pattern.slice(1); + } - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; + // we need to remove the character regardless, + // so the above logic is still needed + if (opts.nonegate === true) { + negate = false; } + } - state.index++; + var _isMatch = matcher(pattern, opts); + var len = files.length, i = 0; + var res = []; - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; + while (i < len) { + var file = files[i++]; + var fp = utils.unixify(file, opts); + + if (!_isMatch(fp)) { continue; } + res.push(fp); + } + + if (res.length === 0) { + if (opts.failglob === true) { + throw new Error('micromatch.match() found no matches for: "' + orig + '".'); } - // done here - callback(null, state.results); - }); + if (opts.nonull || opts.nullglob) { + res.push(utils.unescapeGlob(orig)); + } + } - return terminator.bind(state, callback); -} + // if `negate` was defined, diff negated files + if (negate) { res = utils.diff(files, res); } -/* - * -- Sort methods - */ + // if `ignore` was defined, diff ignored filed + if (opts.ignore && opts.ignore.length) { + pattern = opts.ignore; + opts = utils.omit(opts, ['ignore']); + res = utils.diff(res, micromatch(res, pattern, opts)); + } -/** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; + if (opts.nodupes) { + return utils.unique(res); + } + return res; } /** - * sort helper to sort array elements in descending order + * Returns a function that takes a glob pattern or array of glob patterns + * to be used with `Array#filter()`. (Internally this function generates + * the matching function using the [matcher] method). * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result + * ```js + * var fn = mm.filter('[a-c]'); + * ['a', 'b', 'c', 'd', 'e'].filter(fn); + * //=> ['a', 'b', 'c'] + * ``` + * @param {String|Array} `patterns` Can be a glob or array of globs. + * @param {Options} `opts` Options to pass to the [matcher] method. + * @return {Function} Filter function to be passed to `Array#filter()`. */ -function descending(a, b) -{ - return -1 * ascending(a, b); -} - - -/***/ }), -/* 188 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.verifyTreeCheck = exports.noArguments = exports.requireLockfile = undefined; -var _slicedToArray2; +function filter(patterns, opts) { + if (!Array.isArray(patterns) && typeof patterns !== 'string') { + throw new TypeError(msg('filter', 'patterns', 'a string or array')); + } -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} + patterns = utils.arrayify(patterns); + var len = patterns.length, i = 0; + var patternMatchers = Array(len); + while (i < len) { + patternMatchers[i] = matcher(patterns[i++], opts); + } -var _asyncToGenerator2; + return function(fp) { + if (fp == null) return []; + var len = patternMatchers.length, i = 0; + var res = true; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + fp = utils.unixify(fp, opts); + while (i < len) { + var fn = patternMatchers[i++]; + if (!fn(fp)) { + res = false; + break; + } + } + return res; + }; } -let verifyTreeCheck = exports.verifyTreeCheck = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - let errCount = 0; - function reportError(msg) { - for (var _len = arguments.length, vars = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - vars[_key - 1] = arguments[_key]; - } - - reporter.error(reporter.lang(msg, ...vars)); - errCount++; - } - // check all dependencies recursively without relying on internal resolver - const registryName = 'yarn'; - const registry = config.registries[registryName]; - const rootManifest = yield config.readManifest(registry.cwd, registryName); - - const dependenciesToCheckVersion = []; - if (rootManifest.dependencies) { - for (const name in rootManifest.dependencies) { - const version = rootManifest.dependencies[name]; - // skip linked dependencies - const isLinkedDepencency = /^link:/i.test(version) || /^file:/i.test(version) && config.linkFileDependencies; - if (isLinkedDepencency) { - continue; - } - dependenciesToCheckVersion.push({ - name, - originalKey: name, - parentCwd: registry.cwd, - version - }); - } - } - if (rootManifest.devDependencies && !config.production) { - for (const name in rootManifest.devDependencies) { - const version = rootManifest.devDependencies[name]; - // skip linked dependencies - const isLinkedDepencency = /^link:/i.test(version) || /^file:/i.test(version) && config.linkFileDependencies; - if (isLinkedDepencency) { - continue; - } - dependenciesToCheckVersion.push({ - name, - originalKey: name, - parentCwd: registry.cwd, - version - }); - } - } - - const locationsVisited = new Set(); - while (dependenciesToCheckVersion.length) { - const dep = dependenciesToCheckVersion.shift(); - const manifestLoc = path.join(dep.parentCwd, registry.folder, dep.name); - if (locationsVisited.has(manifestLoc + `@${dep.version}`)) { - continue; - } - locationsVisited.add(manifestLoc + `@${dep.version}`); - if (!(yield (_fs || _load_fs()).exists(manifestLoc))) { - reportError('packageNotInstalled', `${dep.originalKey}`); - continue; - } - if (!(yield (_fs || _load_fs()).exists(path.join(manifestLoc, 'package.json')))) { - continue; - } - const pkg = yield config.readManifest(manifestLoc, registryName); - if (semver.validRange(dep.version, config.looseSemver) && !semver.satisfies(pkg.version, dep.version, config.looseSemver)) { - reportError('packageWrongVersion', dep.originalKey, dep.version, pkg.version); - continue; - } - const dependencies = pkg.dependencies; - if (dependencies) { - for (const subdep in dependencies) { - const subDepPath = path.join(manifestLoc, registry.folder, subdep); - let found = false; - const relative = path.relative(registry.cwd, subDepPath); - const locations = path.normalize(relative).split(registry.folder + path.sep).filter(function (dir) { - return !!dir; - }); - locations.pop(); - while (locations.length >= 0) { - let possiblePath; - if (locations.length > 0) { - possiblePath = path.join(registry.cwd, registry.folder, locations.join(path.sep + registry.folder + path.sep)); - } else { - possiblePath = registry.cwd; - } - if (yield (_fs || _load_fs()).exists(path.join(possiblePath, registry.folder, subdep))) { - dependenciesToCheckVersion.push({ - name: subdep, - originalKey: `${dep.originalKey}#${subdep}`, - parentCwd: possiblePath, - version: dependencies[subdep] - }); - found = true; - break; - } - if (!locations.length) { - break; - } - locations.pop(); - } - if (!found) { - reportError('packageNotInstalled', `${dep.originalKey}#${subdep}`); - } - } - } - } +/** + * Returns true if the filepath contains the given + * pattern. Can also return a function for matching. + * + * ```js + * isMatch('foo.md', '*.md', {}); + * //=> true + * + * isMatch('*.md', {})('foo.md') + * //=> true + * ``` + * @param {String} `fp` + * @param {String} `pattern` + * @param {Object} `opts` + * @return {Boolean} + */ - if (errCount > 0) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount)); - } else { - reporter.success(reporter.lang('folderInSync')); - } - }); +function isMatch(fp, pattern, opts) { + if (typeof fp !== 'string') { + throw new TypeError(msg('isMatch', 'filepath', 'a string')); + } - return function verifyTreeCheck(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); + fp = utils.unixify(fp, opts); + if (utils.typeOf(pattern) === 'object') { + return matcher(fp, pattern); + } + return matcher(pattern, opts)(fp); +} -let integrityHashCheck = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - let errCount = 0; - function reportError(msg) { - for (var _len2 = arguments.length, vars = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - vars[_key2 - 1] = arguments[_key2]; - } +/** + * Returns true if the filepath matches the + * given pattern. + */ - reporter.error(reporter.lang(msg, ...vars)); - errCount++; - } - const integrityChecker = new (_integrityChecker || _load_integrityChecker()).default(config); +function contains(fp, pattern, opts) { + if (typeof fp !== 'string') { + throw new TypeError(msg('contains', 'pattern', 'a string')); + } - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); - const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); + opts = opts || {}; + opts.contains = (pattern !== ''); + fp = utils.unixify(fp, opts); - // get patterns that are installed when running `yarn install` + if (opts.contains && !utils.isGlob(pattern)) { + return fp.indexOf(pattern) !== -1; + } + return matcher(pattern, opts)(fp); +} - var _ref3 = yield install.fetchRequestFromCwd(); +/** + * Returns true if a file path matches any of the + * given patterns. + * + * @param {String} `fp` The filepath to test. + * @param {String|Array} `patterns` Glob patterns to use. + * @param {Object} `opts` Options to pass to the `matcher()` function. + * @return {String} + */ - const patterns = _ref3.patterns, - workspaceLayout = _ref3.workspaceLayout; +function any(fp, patterns, opts) { + if (!Array.isArray(patterns) && typeof patterns !== 'string') { + throw new TypeError(msg('any', 'patterns', 'a string or array')); + } + patterns = utils.arrayify(patterns); + var len = patterns.length; - const match = yield integrityChecker.check(patterns, lockfile.cache, flags, workspaceLayout); - for (const pattern of match.missingPatterns) { - reportError('lockfileNotContainPattern', pattern); - } - if (match.integrityFileMissing) { - reportError('noIntegrityFile'); - } - if (match.integrityMatches === false) { - reporter.warn(reporter.lang((_integrityChecker2 || _load_integrityChecker2()).integrityErrors[match.integrityError])); - reportError('integrityCheckFailed'); + fp = utils.unixify(fp, opts); + while (len--) { + var isMatch = matcher(patterns[len], opts); + if (isMatch(fp)) { + return true; } + } + return false; +} - if (errCount > 0) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount)); - } else { - reporter.success(reporter.lang('folderInSync')); - } - }); +/** + * Filter the keys of an object with the given `glob` pattern + * and `options` + * + * @param {Object} `object` + * @param {Pattern} `object` + * @return {Array} + */ - return function integrityHashCheck(_x5, _x6, _x7, _x8) { - return _ref2.apply(this, arguments); - }; -})(); +function matchKeys(obj, glob, options) { + if (utils.typeOf(obj) !== 'object') { + throw new TypeError(msg('matchKeys', 'first argument', 'an object')); + } -let run = exports.run = (() => { - var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (flags.verifyTree) { - yield verifyTreeCheck(config, reporter, flags, args); - return; - } else if (flags.integrity) { - yield integrityHashCheck(config, reporter, flags, args); - return; + var fn = matcher(glob, options); + var res = {}; + + for (var key in obj) { + if (obj.hasOwnProperty(key) && fn(key)) { + res[key] = obj[key]; } + } + return res; +} - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); - const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); +/** + * Return a function for matching based on the + * given `pattern` and `options`. + * + * @param {String} `pattern` + * @param {Object} `options` + * @return {Function} + */ - function humaniseLocation(loc) { - const relative = path.relative(path.join(config.cwd, 'node_modules'), loc); - const normalized = path.normalize(relative).split(path.sep); - return normalized.filter(p => p !== 'node_modules').reduce((result, part) => { - const length = result.length; - if (length && result[length - 1].startsWith('@') && !result[length - 1].includes(path.sep)) { - result[length - 1] += path.sep + part; - } else { - result.push(part); - } - return result; - }, []); - } +function matcher(pattern, opts) { + // pattern is a function + if (typeof pattern === 'function') { + return pattern; + } + // pattern is a regex + if (pattern instanceof RegExp) { + return function(fp) { + return pattern.test(fp); + }; + } - let warningCount = 0; - let errCount = 0; - function reportError(msg) { - for (var _len3 = arguments.length, vars = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { - vars[_key3 - 1] = arguments[_key3]; - } + if (typeof pattern !== 'string') { + throw new TypeError(msg('matcher', 'pattern', 'a string, regex, or function')); + } - reporter.error(reporter.lang(msg, ...vars)); - errCount++; - } + // strings, all the way down... + pattern = utils.unixify(pattern, opts); - // get patterns that are installed when running `yarn install` + // pattern is a non-glob string + if (!utils.isGlob(pattern)) { + return utils.matchPath(pattern, opts); + } + // pattern is a glob string + var re = makeRe(pattern, opts); - var _ref5 = yield install.hydrate(); + // `matchBase` is defined + if (opts && opts.matchBase) { + return utils.hasFilename(re, opts); + } + // `matchBase` is not defined + return function(fp) { + fp = utils.unixify(fp, opts); + return re.test(fp); + }; +} - const rawPatterns = _ref5.patterns, - workspaceLayout = _ref5.workspaceLayout; +/** + * Create and cache a regular expression for matching + * file paths. + * + * If the leading character in the `glob` is `!`, a negation + * regex is returned. + * + * @param {String} `glob` + * @param {Object} `options` + * @return {RegExp} + */ - const patterns = yield install.flatten(rawPatterns); +function toRegex(glob, options) { + // clone options to prevent mutating the original object + var opts = Object.create(options || {}); + var flags = opts.flags || ''; + if (opts.nocase && flags.indexOf('i') === -1) { + flags += 'i'; + } - // check if patterns exist in lockfile - for (const pattern of patterns) { - if (!lockfile.getLocked(pattern) && (!workspaceLayout || !workspaceLayout.getManifestByPattern(pattern))) { - reportError('lockfileNotContainPattern', pattern); - } - } + var parsed = expand(glob, opts); - const bundledDeps = {}; - // check if any of the node_modules are out of sync - const res = yield install.linker.getFlatHoistedTree(patterns); - for (const _ref6 of res) { - var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2); + // pass in tokens to avoid parsing more than once + opts.negated = opts.negated || parsed.negated; + opts.negate = opts.negated; + glob = wrapGlob(parsed.pattern, opts); + var re; - const loc = _ref7[0]; - var _ref7$ = _ref7[1]; - const originalKey = _ref7$.originalKey; - const pkg = _ref7$.pkg; - const ignore = _ref7$.ignore; + try { + re = new RegExp(glob, flags); + return re; + } catch (err) { + err.reason = 'micromatch invalid regex: (' + re + ')'; + if (opts.strict) throw new SyntaxError(err); + } - if (ignore) { - continue; - } + // we're only here if a bad pattern was used and the user + // passed `options.silent`, so match nothing + return /$^/; +} - const parts = humaniseLocation(loc); +/** + * Create the regex to do the matching. If the leading + * character in the `glob` is `!` a negation regex is returned. + * + * @param {String} `glob` + * @param {Boolean} `negate` + */ - // grey out hoisted portions of key - let human = originalKey; - const hoistedParts = parts.slice(); - const hoistedKey = parts.join('#'); - if (human !== hoistedKey) { - const humanParts = human.split('#'); +function wrapGlob(glob, opts) { + var prefix = (opts && !opts.contains) ? '^' : ''; + var after = (opts && !opts.contains) ? '$' : ''; + glob = ('(?:' + glob + ')' + after); + if (opts && opts.negate) { + return prefix + ('(?!^' + glob + ').*$'); + } + return prefix + glob; +} - for (let i = 0; i < humanParts.length; i++) { - const humanPart = humanParts[i]; +/** + * Create and cache a regular expression for matching file paths. + * If the leading character in the `glob` is `!`, a negation + * regex is returned. + * + * @param {String} `glob` + * @param {Object} `options` + * @return {RegExp} + */ - if (hoistedParts[0] === humanPart) { - hoistedParts.shift(); +function makeRe(glob, opts) { + if (utils.typeOf(glob) !== 'string') { + throw new Error(msg('makeRe', 'glob', 'a string')); + } + return utils.cache(toRegex, glob, opts); +} - if (i < humanParts.length - 1) { - humanParts[i] += '#'; - } - } else { - humanParts[i] = reporter.format.dim(`${humanPart}#`); - } - } +/** + * Make error messages consistent. Follows this format: + * + * ```js + * msg(methodName, argNumber, nativeType); + * // example: + * msg('matchKeys', 'first', 'an object'); + * ``` + * + * @param {String} `method` + * @param {String} `num` + * @param {String} `type` + * @return {String} + */ - human = humanParts.join(''); - } +function msg(method, what, type) { + return 'micromatch.' + method + '(): ' + what + ' should be ' + type + '.'; +} - // skip unnecessary checks for linked dependencies - const remoteType = pkg._reference.remote.type; - const isLinkedDepencency = remoteType === 'link' || remoteType === 'workspace' || remoteType === 'file' && config.linkFileDependencies; - if (isLinkedDepencency) { - continue; - } +/** + * Public methods + */ - if (!(yield (_fs || _load_fs()).exists(loc))) { - if (pkg._reference.optional) { - reporter.warn(reporter.lang('optionalDepNotInstalled', human)); - } else { - reportError('packageNotInstalled', human); - } - continue; - } +/* eslint no-multi-spaces: 0 */ +micromatch.any = any; +micromatch.braces = micromatch.braceExpand = utils.braces; +micromatch.contains = contains; +micromatch.expand = expand; +micromatch.filter = filter; +micromatch.isMatch = isMatch; +micromatch.makeRe = makeRe; +micromatch.match = match; +micromatch.matcher = matcher; +micromatch.matchKeys = matchKeys; - const pkgLoc = path.join(loc, 'package.json'); +/** + * Expose `micromatch` + */ - if (yield (_fs || _load_fs()).exists(pkgLoc)) { - const packageJson = yield config.readJson(pkgLoc); - if (pkg.version !== packageJson.version) { - // node_modules contains wrong version - reportError('packageWrongVersion', human, pkg.version, packageJson.version); - } +module.exports = micromatch; - const deps = Object.assign({}, packageJson.dependencies, packageJson.peerDependencies); - bundledDeps[packageJson.name] = packageJson.bundledDependencies || []; - for (const name in deps) { - const range = deps[name]; - if (!semver.validRange(range, config.looseSemver)) { - continue; // exotic - } +/***/ }), +/* 220 */ +/***/ (function(module, exports, __webpack_require__) { - const subHuman = `${human}#${name}@${range}`; +"use strict"; - // find the package that this will resolve to, factoring in hoisting - const possibles = []; - let depLoc; - for (let i = parts.length; i >= 0; i--) { - const myParts = parts.slice(0, i).concat(name); - // build package.json location for this position - const myDepPkgLoc = path.join(config.cwd, 'node_modules', myParts.join(`${path.sep}node_modules${path.sep}`)); +var win32 = process && process.platform === 'win32'; +var path = __webpack_require__(0); +var fileRe = __webpack_require__(486); +var utils = module.exports; - possibles.push(myDepPkgLoc); - } - while (possibles.length) { - const myDepPkgLoc = possibles.shift(); - if (yield (_fs || _load_fs()).exists(myDepPkgLoc)) { - depLoc = myDepPkgLoc; - break; - } - } - if (!depLoc) { - // we'll hit the module not install error above when this module is hit - continue; - } +/** + * Module dependencies + */ - const depPkgLoc = path.join(depLoc, 'package.json'); +utils.diff = __webpack_require__(372); +utils.unique = __webpack_require__(375); +utils.braces = __webpack_require__(451); +utils.brackets = __webpack_require__(478); +utils.extglob = __webpack_require__(485); +utils.isExtglob = __webpack_require__(137); +utils.isGlob = __webpack_require__(138); +utils.typeOf = __webpack_require__(218); +utils.normalize = __webpack_require__(576); +utils.omit = __webpack_require__(579); +utils.parseGlob = __webpack_require__(582); +utils.cache = __webpack_require__(598); - if (yield (_fs || _load_fs()).exists(depPkgLoc)) { - const depPkg = yield config.readJson(depPkgLoc); - const foundHuman = `${humaniseLocation(path.dirname(depPkgLoc)).join('#')}@${depPkg.version}`; - if (!semver.satisfies(depPkg.version, range, config.looseSemver)) { - // module isn't correct semver - reportError('packageDontSatisfy', subHuman, foundHuman); - continue; - } - - // check for modules above us that this could be deduped to - for (const loc of possibles) { - const locPkg = path.join(loc, 'package.json'); - - if (!(yield (_fs || _load_fs()).exists(locPkg))) { - continue; - } - - const packageJson = yield config.readJson(locPkg); - const packagePath = originalKey.split('#'); - const rootDep = packagePath[0]; - const packageName = packagePath[1] || packageJson.name; +/** + * Get the filename of a filepath + * + * @param {String} `string` + * @return {String} + */ - const bundledDep = bundledDeps[rootDep] && bundledDeps[rootDep].indexOf(packageName) !== -1; - if (!bundledDep && (packageJson.version === depPkg.version || semver.satisfies(packageJson.version, range, config.looseSemver) && semver.gt(packageJson.version, depPkg.version, config.looseSemver))) { - reporter.warn(reporter.lang('couldBeDeduped', subHuman, packageJson.version, `${humaniseLocation(path.dirname(locPkg)).join('#')}@${packageJson.version}`)); - warningCount++; - } - break; - } - } - } - } - } +utils.filename = function filename(fp) { + var seg = fp.match(fileRe()); + return seg && seg[0]; +}; - if (warningCount > 1) { - reporter.info(reporter.lang('foundWarnings', warningCount)); - } +/** + * Returns a function that returns true if the given + * pattern is the same as a given `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ - if (errCount > 0) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount)); - } else { - reporter.success(reporter.lang('folderInSync')); +utils.isPath = function isPath(pattern, opts) { + opts = opts || {}; + return function(fp) { + var unixified = utils.unixify(fp, opts); + if(opts.nocase){ + return pattern.toLowerCase() === unixified.toLowerCase(); } - }); - - return function run(_x9, _x10, _x11, _x12) { - return _ref4.apply(this, arguments); + return pattern === unixified; }; -})(); - -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); -} +}; -var _integrityChecker; +/** + * Returns a function that returns true if the given + * pattern contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ -function _load_integrityChecker() { - return _integrityChecker = _interopRequireDefault(__webpack_require__(121)); -} +utils.hasPath = function hasPath(pattern, opts) { + return function(fp) { + return utils.unixify(pattern, opts).indexOf(fp) !== -1; + }; +}; -var _integrityChecker2; +/** + * Returns a function that returns true if the given + * pattern matches or contains a `filepath` + * + * @param {String} `pattern` + * @return {Function} + */ -function _load_integrityChecker2() { - return _integrityChecker2 = __webpack_require__(121); -} +utils.matchPath = function matchPath(pattern, opts) { + var fn = (opts && opts.contains) + ? utils.hasPath(pattern, opts) + : utils.isPath(pattern, opts); + return fn; +}; -var _wrapper; +/** + * Returns a function that returns true if the given + * regex matches the `filename` of a file path. + * + * @param {RegExp} `re` + * @return {Boolean} + */ -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} +utils.hasFilename = function hasFilename(re) { + return function(fp) { + var name = utils.filename(fp); + return name && re.test(name); + }; +}; -var _fs; +/** + * Coerce `val` to an array + * + * @param {*} val + * @return {Array} + */ -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} +utils.arrayify = function arrayify(val) { + return !Array.isArray(val) + ? [val] + : val; +}; -var _install; +/** + * Normalize all slashes in a file path or glob pattern to + * forward slashes. + */ -function _load_install() { - return _install = __webpack_require__(23); -} +utils.unixify = function unixify(fp, opts) { + if (opts && opts.unixify === false) return fp; + if (opts && opts.unixify === true || win32 || path.sep === '\\') { + return utils.normalize(fp, false); + } + if (opts && opts.unescape === true) { + return fp ? fp.toString().replace(/\\(\w)/g, '$1') : ''; + } + return fp; +}; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +/** + * Escape/unescape utils + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +utils.escapePath = function escapePath(fp) { + return fp.replace(/[\\.]/g, '\\$&'); +}; -const semver = __webpack_require__(27); +utils.unescapeGlob = function unescapeGlob(fp) { + return fp.replace(/[\\"']/g, ''); +}; -const path = __webpack_require__(1); +utils.escapeRe = function escapeRe(str) { + return str.replace(/[-[\\$*+?.#^\s{}(|)\]]/g, '\\$&'); +}; -const requireLockfile = exports.requireLockfile = false; -const noArguments = exports.noArguments = true; +/** + * Expose `utils` + */ -function hasWrapper(commander) { - return true; -} +module.exports = utils; -function setFlags(commander) { - commander.option('--integrity'); - commander.option('--verify-tree'); -} /***/ }), -/* 189 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - +/* 221 */ +/***/ (function(module, exports) { -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.clean = exports.noArguments = exports.requireLockfile = undefined; +/** + * Helpers. + */ -var _asyncToGenerator2; +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ -let clean = exports.clean = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) { - const loc = path.join(config.cwd, (_constants || _load_constants()).CLEAN_FILENAME); - const file = yield (_fs || _load_fs()).readFile(loc); - const lines = file.split('\n'); - const filters = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines); +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - let removedFiles = 0; - let removedSize = 0; +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - // build list of possible module folders - const locs = new Set(); - if (config.modulesFolder) { - locs.add(config.modulesFolder); - } - for (const name of (_index || _load_index()).registryNames) { - const registry = config.registries[name]; - locs.add(path.join(config.cwd, registry.folder)); - } +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - for (const folder of locs) { - if (!(yield (_fs || _load_fs()).exists(folder))) { - continue; - } +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - const spinner = reporter.activity(); - const files = yield (_fs || _load_fs()).walk(folder); +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} - var _sortFilter = (0, (_filter || _load_filter()).sortFilter)(files, filters); +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - const ignoreFiles = _sortFilter.ignoreFiles; +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} - spinner.end(); +/** + * Pluralization helper. + */ - const tick = reporter.progress(ignoreFiles.size); - // TODO make sure `main` field of all modules isn't ignored +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} - for (const file of ignoreFiles) { - const loc = path.join(folder, file); - const stat = yield (_fs || _load_fs()).lstat(loc); - removedSize += stat.size; - removedFiles++; - } - for (const file of ignoreFiles) { - const loc = path.join(folder, file); - yield (_fs || _load_fs()).unlink(loc); - tick(); - } - } +/***/ }), +/* 222 */ +/***/ (function(module, exports, __webpack_require__) { - return { removedFiles, removedSize }; - }); +"use strict"; - return function clean(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); -let run = exports.run = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - reporter.step(1, 2, reporter.lang('cleanCreatingFile', (_constants || _load_constants()).CLEAN_FILENAME)); +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} - const cleanLoc = path.join(config.cwd, (_constants || _load_constants()).CLEAN_FILENAME); - if (!(yield (_fs || _load_fs()).exists(cleanLoc))) { - yield (_fs || _load_fs()).writeFile(cleanLoc, `${DEFAULT_FILTER}\n`, { flag: 'wx' }); +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} - reporter.step(2, 2, reporter.lang('cleaning')); - - var _ref3 = yield clean(config, reporter); - const removedFiles = _ref3.removedFiles, - removedSize = _ref3.removedSize; +/***/ }), +/* 223 */ +/***/ (function(module, exports, __webpack_require__) { - reporter.info(reporter.lang('cleanRemovedFiles', removedFiles)); - reporter.info(reporter.lang('cleanSavedSize', Number((removedSize / 1024 / 1024).toFixed(2)))); - }); +"use strict"; - return function run(_x3, _x4, _x5, _x6) { - return _ref2.apply(this, arguments); - }; -})(); -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; +var jsonSafeStringify = __webpack_require__(562) + , crypto = __webpack_require__(8) + , Buffer = __webpack_require__(87).Buffer -var _index; +var defer = typeof setImmediate === 'undefined' + ? process.nextTick + : setImmediate -function _load_index() { - return _index = __webpack_require__(24); +function paramsHaveRequestBody(params) { + return ( + params.body || + params.requestBodyStream || + (params.json && typeof params.json !== 'boolean') || + params.multipart + ) } -var _filter; +function safeStringify (obj, replacer) { + var ret + try { + ret = JSON.stringify(obj, replacer) + } catch (e) { + ret = jsonSafeStringify(obj, replacer) + } + return ret +} -function _load_filter() { - return _filter = __webpack_require__(206); +function md5 (str) { + return crypto.createHash('md5').update(str).digest('hex') } -var _constants; +function isReadStream (rs) { + return rs.readable && rs.path && rs.mode +} -function _load_constants() { - return _constants = __webpack_require__(8); +function toBase64 (str) { + return Buffer.from(str || '', 'utf8').toString('base64') } -var _fs; +function copy (obj) { + var o = {} + Object.keys(obj).forEach(function (i) { + o[i] = obj[i] + }) + return o +} -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); +function version () { + var numbers = process.version.replace('v', '').split('.') + return { + major: parseInt(numbers[0], 10), + minor: parseInt(numbers[1], 10), + patch: parseInt(numbers[2], 10) + } } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +exports.paramsHaveRequestBody = paramsHaveRequestBody +exports.safeStringify = safeStringify +exports.md5 = md5 +exports.isReadStream = isReadStream +exports.toBase64 = toBase64 +exports.copy = copy +exports.version = version +exports.defer = defer -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const path = __webpack_require__(1); +/***/ }), +/* 224 */ +/***/ (function(module, exports, __webpack_require__) { -const requireLockfile = exports.requireLockfile = true; -const noArguments = exports.noArguments = true; +module.exports = rimraf +rimraf.sync = rimrafSync -const DEFAULT_FILTER = ` -# test directories -__tests__ -test -tests -powered-test +var assert = __webpack_require__(18) +var path = __webpack_require__(0) +var fs = __webpack_require__(5) +var glob = __webpack_require__(71) -# asset directories -docs -doc -website -images -assets - -# examples -example -examples - -# code coverage directories -coverage -.nyc_output - -# build scripts -Makefile -Gulpfile.js -Gruntfile.js +var defaultGlobOpts = { + nosort: true, + silent: true +} -# configs -.tern-project -.gitattributes -.editorconfig -.*ignore -.eslintrc -.jshintrc -.flowconfig -.documentup.json -.yarn-metadata.json -.*.yml -*.yml +// for EMFILE handling +var timeout = 0 -# misc -*.gz -*.md -`.trim(); +var isWindows = (process.platform === "win32") -function setFlags(commander) {} +function defaults (options) { + var methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(function(m) { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) -function hasWrapper(commander) { - return true; + options.maxBusyTries = options.maxBusyTries || 3 + options.emfileWait = options.emfileWait || 1000 + if (options.glob === false) { + options.disableGlob = true + } + options.disableGlob = options.disableGlob || false + options.glob = options.glob || defaultGlobOpts } -/***/ }), -/* 190 */ -/***/ (function(module, exports, __webpack_require__) { +function rimraf (p, options, cb) { + if (typeof options === 'function') { + cb = options + options = {} + } -"use strict"; + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + defaults(options) -Object.defineProperty(exports, "__esModule", { - value: true -}); + var busyTries = 0 + var errState = null + var n = 0 -var _index; + if (options.disableGlob || !glob.hasMagic(p)) + return afterGlob(null, [p]) -function _load_index() { - return _index = __webpack_require__(82); -} + options.lstat(p, function (er, stat) { + if (!er) + return afterGlob(null, [p]) -var _constants; + glob(p, options.glob, afterGlob) + }) -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + function next (er) { + errState = errState || er + if (--n === 0) + cb(errState) + } -var _errors; + function afterGlob (er, results) { + if (er) + return cb(er) -function _load_errors() { - return _errors = __webpack_require__(3); -} + n = results.length + if (n === 0) + return cb() -var _config; + results.forEach(function (p) { + rimraf_(p, options, function CB (er) { + if (er) { + if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && + busyTries < options.maxBusyTries) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, options, CB) + }, time) + } -function _load_config() { - return _config = _interopRequireDefault(__webpack_require__(120)); -} + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < options.emfileWait) { + return setTimeout(function () { + rimraf_(p, options, CB) + }, timeout ++) + } -var _access; + // already gone + if (er.code === "ENOENT") er = null + } -function _load_access() { - return _access = _interopRequireWildcard(__webpack_require__(333)); + timeout = 0 + next(er) + }) + }) + } } -var _add; - -function _load_add() { - return _add = _interopRequireWildcard(__webpack_require__(78)); -} +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') -var _bin; + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, function (er, st) { + if (er && er.code === "ENOENT") + return cb(null) -function _load_bin() { - return _bin = _interopRequireWildcard(__webpack_require__(334)); -} + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === "EPERM" && isWindows) + fixWinEPERM(p, options, er, cb) -var _cache; + if (st && st.isDirectory()) + return rmdir(p, options, er, cb) -function _load_cache() { - return _cache = _interopRequireWildcard(__webpack_require__(335)); + options.unlink(p, function (er) { + if (er) { + if (er.code === "ENOENT") + return cb(null) + if (er.code === "EPERM") + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + if (er.code === "EISDIR") + return rmdir(p, options, er, cb) + } + return cb(er) + }) + }) } -var _check; +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) + assert(er instanceof Error) -function _load_check() { - return _check = _interopRequireWildcard(__webpack_require__(188)); + options.chmod(p, 666, function (er2) { + if (er2) + cb(er2.code === "ENOENT" ? null : er) + else + options.stat(p, function(er3, stats) { + if (er3) + cb(er3.code === "ENOENT" ? null : er) + else if (stats.isDirectory()) + rmdir(p, options, er, cb) + else + options.unlink(p, cb) + }) + }) } -var _clean; +function fixWinEPERMSync (p, options, er) { + assert(p) + assert(options) + if (er) + assert(er instanceof Error) -function _load_clean() { - return _clean = _interopRequireWildcard(__webpack_require__(189)); -} + try { + options.chmodSync(p, 666) + } catch (er2) { + if (er2.code === "ENOENT") + return + else + throw er + } -var _config2; + try { + var stats = options.statSync(p) + } catch (er3) { + if (er3.code === "ENOENT") + return + else + throw er + } -function _load_config2() { - return _config2 = _interopRequireWildcard(__webpack_require__(336)); + if (stats.isDirectory()) + rmdirSync(p, options, er) + else + options.unlinkSync(p) } -var _create; +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) + assert(typeof cb === 'function') -function _load_create() { - return _create = _interopRequireWildcard(__webpack_require__(337)); + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, function (er) { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) + rmkids(p, options, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) } -var _exec; +function rmkids(p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') -function _load_exec() { - return _exec = _interopRequireWildcard(__webpack_require__(338)); + options.readdir(p, function (er, files) { + if (er) + return cb(er) + var n = files.length + if (n === 0) + return options.rmdir(p, cb) + var errState + files.forEach(function (f) { + rimraf(path.join(p, f), options, function (er) { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + options.rmdir(p, cb) + }) + }) + }) } -var _generateLockEntry; +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + options = options || {} + defaults(options) -function _load_generateLockEntry() { - return _generateLockEntry = _interopRequireWildcard(__webpack_require__(339)); -} + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') -var _global; + var results -function _load_global() { - return _global = _interopRequireWildcard(__webpack_require__(59)); -} + if (options.disableGlob || !glob.hasMagic(p)) { + results = [p] + } else { + try { + options.lstatSync(p) + results = [p] + } catch (er) { + results = glob.sync(p, options.glob) + } + } -var _help; + if (!results.length) + return -function _load_help() { - return _help = _interopRequireWildcard(__webpack_require__(340)); -} + for (var i = 0; i < results.length; i++) { + var p = results[i] -var _import; + try { + var st = options.lstatSync(p) + } catch (er) { + if (er.code === "ENOENT") + return -function _load_import() { - return _import = _interopRequireWildcard(__webpack_require__(341)); -} + // Windows can EPERM on stat. Life is suffering. + if (er.code === "EPERM" && isWindows) + fixWinEPERMSync(p, options, er) + } -var _info; + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) + rmdirSync(p, options, null) + else + options.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "EPERM") + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + if (er.code !== "EISDIR") + throw er -function _load_info() { - return _info = _interopRequireWildcard(__webpack_require__(342)); + rmdirSync(p, options, er) + } + } } -var _init; +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) + assert(originalEr instanceof Error) -function _load_init() { - return _init = _interopRequireWildcard(__webpack_require__(343)); + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code === "ENOTDIR") + throw originalEr + if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") + rmkidsSync(p, options) + } } -var _install; +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f), options) + }) -function _load_install() { - return _install = _interopRequireWildcard(__webpack_require__(23)); + // We only end up here once we got ENOTEMPTY at least once, and + // at this point, we are guaranteed to have removed all the kids. + // So, we know that it won't be ENOENT or ENOTDIR or anything else. + // try really hard to delete stuff on windows, because it has a + // PROFOUNDLY annoying habit of not closing handles promptly when + // files are deleted, resulting in spurious ENOTEMPTY errors. + var retries = isWindows ? 100 : 1 + var i = 0 + do { + var threw = true + try { + var ret = options.rmdirSync(p, options) + threw = false + return ret + } finally { + if (++i < retries && threw) + continue + } + } while (true) } -var _licenses; -function _load_licenses() { - return _licenses = _interopRequireWildcard(__webpack_require__(344)); -} +/***/ }), +/* 225 */ +/***/ (function(module, exports, __webpack_require__) { -var _link; +// Copyright 2015 Joyent, Inc. -function _load_link() { - return _link = _interopRequireWildcard(__webpack_require__(191)); -} +module.exports = { + read: read, + readPkcs1: readPkcs1, + write: write, + writePkcs1: writePkcs1 +}; -var _login; +var assert = __webpack_require__(11); +var asn1 = __webpack_require__(50); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); -function _load_login() { - return _login = _interopRequireWildcard(__webpack_require__(60)); -} +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var pem = __webpack_require__(58); -var _logout; +var pkcs8 = __webpack_require__(117); +var readECDSACurve = pkcs8.readECDSACurve; -function _load_logout() { - return _logout = _interopRequireWildcard(__webpack_require__(345)); +function read(buf, options) { + return (pem.read(buf, options, 'pkcs1')); } -var _list; - -function _load_list() { - return _list = _interopRequireWildcard(__webpack_require__(192)); +function write(key, options) { + return (pem.write(key, options, 'pkcs1')); } -var _outdated; - -function _load_outdated() { - return _outdated = _interopRequireWildcard(__webpack_require__(346)); +/* Helper to read in a single mpint */ +function readMPInt(der, nm) { + assert.strictEqual(der.peek(), asn1.Ber.Integer, + nm + ' is not an Integer'); + return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } -var _owner; - -function _load_owner() { - return _owner = _interopRequireWildcard(__webpack_require__(347)); +function readPkcs1(alg, type, der) { + switch (alg) { + case 'RSA': + if (type === 'public') + return (readPkcs1RSAPublic(der)); + else if (type === 'private') + return (readPkcs1RSAPrivate(der)); + throw (new Error('Unknown key type: ' + type)); + case 'DSA': + if (type === 'public') + return (readPkcs1DSAPublic(der)); + else if (type === 'private') + return (readPkcs1DSAPrivate(der)); + throw (new Error('Unknown key type: ' + type)); + case 'EC': + case 'ECDSA': + if (type === 'private') + return (readPkcs1ECDSAPrivate(der)); + else if (type === 'public') + return (readPkcs1ECDSAPublic(der)); + throw (new Error('Unknown key type: ' + type)); + default: + throw (new Error('Unknown key algo: ' + alg)); + } } -var _pack; - -function _load_pack() { - return _pack = _interopRequireWildcard(__webpack_require__(119)); -} +function readPkcs1RSAPublic(der) { + // modulus and exponent + var n = readMPInt(der, 'modulus'); + var e = readMPInt(der, 'exponent'); -var _publish; + // now, make the key + var key = { + type: 'rsa', + parts: [ + { name: 'e', data: e }, + { name: 'n', data: n } + ] + }; -function _load_publish() { - return _publish = _interopRequireWildcard(__webpack_require__(348)); + return (new Key(key)); } -var _remove; +function readPkcs1RSAPrivate(der) { + var version = readMPInt(der, 'version'); + assert.strictEqual(version[0], 0); -function _load_remove() { - return _remove = _interopRequireWildcard(__webpack_require__(193)); -} + // modulus then public exponent + var n = readMPInt(der, 'modulus'); + var e = readMPInt(der, 'public exponent'); + var d = readMPInt(der, 'private exponent'); + var p = readMPInt(der, 'prime1'); + var q = readMPInt(der, 'prime2'); + var dmodp = readMPInt(der, 'exponent1'); + var dmodq = readMPInt(der, 'exponent2'); + var iqmp = readMPInt(der, 'iqmp'); -var _run; + // now, make the key + var key = { + type: 'rsa', + parts: [ + { name: 'n', data: n }, + { name: 'e', data: e }, + { name: 'd', data: d }, + { name: 'iqmp', data: iqmp }, + { name: 'p', data: p }, + { name: 'q', data: q }, + { name: 'dmodp', data: dmodp }, + { name: 'dmodq', data: dmodq } + ] + }; -function _load_run() { - return _run = _interopRequireWildcard(__webpack_require__(349)); + return (new PrivateKey(key)); } -var _tag; +function readPkcs1DSAPrivate(der) { + var version = readMPInt(der, 'version'); + assert.strictEqual(version.readUInt8(0), 0); -function _load_tag() { - return _tag = _interopRequireWildcard(__webpack_require__(194)); + var p = readMPInt(der, 'p'); + var q = readMPInt(der, 'q'); + var g = readMPInt(der, 'g'); + var y = readMPInt(der, 'y'); + var x = readMPInt(der, 'x'); + + // now, make the key + var key = { + type: 'dsa', + parts: [ + { name: 'p', data: p }, + { name: 'q', data: q }, + { name: 'g', data: g }, + { name: 'y', data: y }, + { name: 'x', data: x } + ] + }; + + return (new PrivateKey(key)); +} + +function readPkcs1DSAPublic(der) { + var y = readMPInt(der, 'y'); + var p = readMPInt(der, 'p'); + var q = readMPInt(der, 'q'); + var g = readMPInt(der, 'g'); + + var key = { + type: 'dsa', + parts: [ + { name: 'y', data: y }, + { name: 'p', data: p }, + { name: 'q', data: q }, + { name: 'g', data: g } + ] + }; + + return (new Key(key)); +} + +function readPkcs1ECDSAPublic(der) { + der.readSequence(); + + var oid = der.readOID(); + assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey'); + + var curveOid = der.readOID(); + + var curve; + var curves = Object.keys(algs.curves); + for (var j = 0; j < curves.length; ++j) { + var c = curves[j]; + var cd = algs.curves[c]; + if (cd.pkcs8oid === curveOid) { + curve = c; + break; + } + } + assert.string(curve, 'a known ECDSA named curve'); + + var Q = der.readString(asn1.Ber.BitString, true); + Q = utils.ecNormalize(Q); + + var key = { + type: 'ecdsa', + parts: [ + { name: 'curve', data: new Buffer(curve) }, + { name: 'Q', data: Q } + ] + }; + + return (new Key(key)); +} + +function readPkcs1ECDSAPrivate(der) { + var version = readMPInt(der, 'version'); + assert.strictEqual(version.readUInt8(0), 1); + + // private key + var d = der.readString(asn1.Ber.OctetString, true); + + der.readSequence(0xa0); + var curve = readECDSACurve(der); + assert.string(curve, 'a known elliptic curve'); + + der.readSequence(0xa1); + var Q = der.readString(asn1.Ber.BitString, true); + Q = utils.ecNormalize(Q); + + var key = { + type: 'ecdsa', + parts: [ + { name: 'curve', data: new Buffer(curve) }, + { name: 'Q', data: Q }, + { name: 'd', data: d } + ] + }; + + return (new PrivateKey(key)); +} + +function writePkcs1(der, key) { + der.startSequence(); + + switch (key.type) { + case 'rsa': + if (PrivateKey.isPrivateKey(key)) + writePkcs1RSAPrivate(der, key); + else + writePkcs1RSAPublic(der, key); + break; + case 'dsa': + if (PrivateKey.isPrivateKey(key)) + writePkcs1DSAPrivate(der, key); + else + writePkcs1DSAPublic(der, key); + break; + case 'ecdsa': + if (PrivateKey.isPrivateKey(key)) + writePkcs1ECDSAPrivate(der, key); + else + writePkcs1ECDSAPublic(der, key); + break; + default: + throw (new Error('Unknown key algo: ' + key.type)); + } + + der.endSequence(); +} + +function writePkcs1RSAPublic(der, key) { + der.writeBuffer(key.part.n.data, asn1.Ber.Integer); + der.writeBuffer(key.part.e.data, asn1.Ber.Integer); +} + +function writePkcs1RSAPrivate(der, key) { + var ver = new Buffer(1); + ver[0] = 0; + der.writeBuffer(ver, asn1.Ber.Integer); + + der.writeBuffer(key.part.n.data, asn1.Ber.Integer); + der.writeBuffer(key.part.e.data, asn1.Ber.Integer); + der.writeBuffer(key.part.d.data, asn1.Ber.Integer); + der.writeBuffer(key.part.p.data, asn1.Ber.Integer); + der.writeBuffer(key.part.q.data, asn1.Ber.Integer); + if (!key.part.dmodp || !key.part.dmodq) + utils.addRSAMissing(key); + der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer); + der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer); + der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer); +} + +function writePkcs1DSAPrivate(der, key) { + var ver = new Buffer(1); + ver[0] = 0; + der.writeBuffer(ver, asn1.Ber.Integer); + + der.writeBuffer(key.part.p.data, asn1.Ber.Integer); + der.writeBuffer(key.part.q.data, asn1.Ber.Integer); + der.writeBuffer(key.part.g.data, asn1.Ber.Integer); + der.writeBuffer(key.part.y.data, asn1.Ber.Integer); + der.writeBuffer(key.part.x.data, asn1.Ber.Integer); +} + +function writePkcs1DSAPublic(der, key) { + der.writeBuffer(key.part.y.data, asn1.Ber.Integer); + der.writeBuffer(key.part.p.data, asn1.Ber.Integer); + der.writeBuffer(key.part.q.data, asn1.Ber.Integer); + der.writeBuffer(key.part.g.data, asn1.Ber.Integer); +} + +function writePkcs1ECDSAPublic(der, key) { + der.startSequence(); + + der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */ + var curve = key.part.curve.data.toString(); + var curveOid = algs.curves[curve].pkcs8oid; + assert.string(curveOid, 'a known ECDSA named curve'); + der.writeOID(curveOid); + + der.endSequence(); + + var Q = utils.ecNormalize(key.part.Q.data, true); + der.writeBuffer(Q, asn1.Ber.BitString); +} + +function writePkcs1ECDSAPrivate(der, key) { + var ver = new Buffer(1); + ver[0] = 1; + der.writeBuffer(ver, asn1.Ber.Integer); + + der.writeBuffer(key.part.d.data, asn1.Ber.OctetString); + + der.startSequence(0xa0); + var curve = key.part.curve.data.toString(); + var curveOid = algs.curves[curve].pkcs8oid; + assert.string(curveOid, 'a known ECDSA named curve'); + der.writeOID(curveOid); + der.endSequence(); + + der.startSequence(0xa1); + var Q = utils.ecNormalize(key.part.Q.data, true); + der.writeBuffer(Q, asn1.Ber.BitString); + der.endSequence(); +} + + +/***/ }), +/* 226 */ +/***/ (function(module, exports, __webpack_require__) { + +// Copyright 2015 Joyent, Inc. + +var Key = __webpack_require__(24); +var Fingerprint = __webpack_require__(116); +var Signature = __webpack_require__(45); +var PrivateKey = __webpack_require__(25); +var Certificate = __webpack_require__(115); +var Identity = __webpack_require__(118); +var errs = __webpack_require__(44); + +module.exports = { + /* top-level classes */ + Key: Key, + parseKey: Key.parse, + Fingerprint: Fingerprint, + parseFingerprint: Fingerprint.parse, + Signature: Signature, + parseSignature: Signature.parse, + PrivateKey: PrivateKey, + parsePrivateKey: PrivateKey.parse, + generatePrivateKey: PrivateKey.generate, + Certificate: Certificate, + parseCertificate: Certificate.parse, + createSelfSignedCertificate: Certificate.createSelfSigned, + createCertificate: Certificate.create, + Identity: Identity, + identityFromDN: Identity.parseDN, + identityForHost: Identity.forHost, + identityForUser: Identity.forUser, + identityForEmail: Identity.forEmail, + + /* errors */ + FingerprintFormatError: errs.FingerprintFormatError, + InvalidAlgorithmError: errs.InvalidAlgorithmError, + KeyParseError: errs.KeyParseError, + SignatureParseError: errs.SignatureParseError, + KeyEncryptedError: errs.KeyEncryptedError, + CertificateParseError: errs.CertificateParseError +}; + + +/***/ }), +/* 227 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var ansiRegex = __webpack_require__(245)(); + +module.exports = function (str) { + return typeof str === 'string' ? str.replace(ansiRegex, '') : str; +}; + + +/***/ }), +/* 228 */ +/***/ (function(module, exports) { + +module.exports = require("punycode"); + +/***/ }), +/* 229 */ +/***/ (function(module, exports) { + +module.exports = require("string_decoder"); + +/***/ }), +/* 230 */ +/***/ (function(module, exports) { + +module.exports = require("zlib"); + +/***/ }), +/* 231 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _constants; + +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} + +var _access; + +function _load_access() { + return _access = _interopRequireWildcard(__webpack_require__(387)); +} + +var _add; + +function _load_add() { + return _add = _interopRequireWildcard(__webpack_require__(121)); +} + +var _autoclean; + +function _load_autoclean() { + return _autoclean = _interopRequireWildcard(__webpack_require__(253)); +} + +var _bin; + +function _load_bin() { + return _bin = _interopRequireWildcard(__webpack_require__(388)); +} + +var _cache; + +function _load_cache() { + return _cache = _interopRequireWildcard(__webpack_require__(389)); +} + +var _check; + +function _load_check() { + return _check = _interopRequireWildcard(__webpack_require__(254)); +} + +var _config; + +function _load_config() { + return _config = _interopRequireWildcard(__webpack_require__(390)); +} + +var _create; + +function _load_create() { + return _create = _interopRequireWildcard(__webpack_require__(391)); +} + +var _exec; + +function _load_exec() { + return _exec = _interopRequireWildcard(__webpack_require__(392)); +} + +var _generateLockEntry; + +function _load_generateLockEntry() { + return _generateLockEntry = _interopRequireWildcard(__webpack_require__(393)); +} + +var _global; + +function _load_global() { + return _global = _interopRequireWildcard(__webpack_require__(92)); +} + +var _help; + +function _load_help() { + return _help = _interopRequireWildcard(__webpack_require__(394)); +} + +var _import; + +function _load_import() { + return _import = _interopRequireWildcard(__webpack_require__(395)); +} + +var _info; + +function _load_info() { + return _info = _interopRequireWildcard(__webpack_require__(396)); +} + +var _init; + +function _load_init() { + return _init = _interopRequireWildcard(__webpack_require__(397)); +} + +var _install; + +function _load_install() { + return _install = _interopRequireWildcard(__webpack_require__(31)); +} + +var _licenses; + +function _load_licenses() { + return _licenses = _interopRequireWildcard(__webpack_require__(398)); +} + +var _link; + +function _load_link() { + return _link = _interopRequireWildcard(__webpack_require__(255)); +} + +var _login; + +function _load_login() { + return _login = _interopRequireWildcard(__webpack_require__(93)); +} + +var _logout; + +function _load_logout() { + return _logout = _interopRequireWildcard(__webpack_require__(399)); +} + +var _list; + +function _load_list() { + return _list = _interopRequireWildcard(__webpack_require__(256)); +} + +var _outdated; + +function _load_outdated() { + return _outdated = _interopRequireWildcard(__webpack_require__(400)); +} + +var _owner; + +function _load_owner() { + return _owner = _interopRequireWildcard(__webpack_require__(401)); +} + +var _pack; + +function _load_pack() { + return _pack = _interopRequireWildcard(__webpack_require__(156)); +} + +var _publish; + +function _load_publish() { + return _publish = _interopRequireWildcard(__webpack_require__(402)); +} + +var _remove; + +function _load_remove() { + return _remove = _interopRequireWildcard(__webpack_require__(257)); +} + +var _run; + +function _load_run() { + return _run = _interopRequireWildcard(__webpack_require__(403)); +} + +var _tag; + +function _load_tag() { + return _tag = _interopRequireWildcard(__webpack_require__(258)); } var _team; function _load_team() { - return _team = _interopRequireWildcard(__webpack_require__(350)); + return _team = _interopRequireWildcard(__webpack_require__(404)); } var _unlink; function _load_unlink() { - return _unlink = _interopRequireWildcard(__webpack_require__(351)); + return _unlink = _interopRequireWildcard(__webpack_require__(405)); } var _upgrade; function _load_upgrade() { - return _upgrade = _interopRequireWildcard(__webpack_require__(196)); + return _upgrade = _interopRequireWildcard(__webpack_require__(157)); } var _version; function _load_version() { - return _version = _interopRequireWildcard(__webpack_require__(197)); + return _version = _interopRequireWildcard(__webpack_require__(260)); } var _versions; function _load_versions() { - return _versions = _interopRequireWildcard(__webpack_require__(352)); + return _versions = _interopRequireWildcard(__webpack_require__(406)); } var _why; function _load_why() { - return _why = _interopRequireWildcard(__webpack_require__(353)); + return _why = _interopRequireWildcard(__webpack_require__(407)); } var _workspace; function _load_workspace() { - return _workspace = _interopRequireWildcard(__webpack_require__(354)); + return _workspace = _interopRequireWildcard(__webpack_require__(408)); } var _upgradeInteractive; function _load_upgradeInteractive() { - return _upgradeInteractive = _interopRequireWildcard(__webpack_require__(195)); + return _upgradeInteractive = _interopRequireWildcard(__webpack_require__(259)); } var _useless; function _load_useless() { - return _useless = _interopRequireDefault(__webpack_require__(332)); + return _useless = _interopRequireDefault(__webpack_require__(386)); } var _aliases; function _load_aliases() { - return _aliases = _interopRequireDefault(__webpack_require__(331)); -} - -var _unsupportedAliases; - -function _load_unsupportedAliases() { - return _unsupportedAliases = _interopRequireDefault(__webpack_require__(355)); + return _aliases = _interopRequireDefault(__webpack_require__(252)); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -const chalk = __webpack_require__(15); +const chalk = __webpack_require__(20); + const getDocsLink = name => `${(_constants || _load_constants()).YARN_DOCS}${name || ''}`; const getDocsInfo = name => 'Visit ' + chalk.bold(getDocsLink(name)) + ' for documentation about this command.'; @@ -54035,11 +56654,11 @@ const getDocsInfo = name => 'Visit ' + chalk.bold(getDocsLink(name)) + ' for doc const commands = { access: _access || _load_access(), add: _add || _load_add(), + autoclean: _autoclean || _load_autoclean(), bin: _bin || _load_bin(), cache: _cache || _load_cache(), check: _check || _load_check(), - clean: _clean || _load_clean(), - config: _config2 || _load_config2(), + config: _config || _load_config(), create: _create || _load_create(), dedupe: (0, (_useless || _load_useless()).default)("The dedupe command isn't necessary. `yarn install` will already dedupe."), exec: _exec || _load_exec(), @@ -54083,21 +56702,10 @@ for (const key in (_aliases || _load_aliases()).default) { commands[key].getDocsInfo = getDocsInfo(key); } -for (const key in (_unsupportedAliases || _load_unsupportedAliases()).default) { - commands[key] = { - run(config, reporter) { - throw new (_errors || _load_errors()).MessageError(`Did you mean \`yarn ${(_unsupportedAliases || _load_unsupportedAliases()).default[key]}\`?`); - }, - setFlags: () => {}, - hasWrapper: () => true, - getDocsInfo: getDocsInfo((_unsupportedAliases || _load_unsupportedAliases()).default[key]) - }; -} - exports.default = commands; /***/ }), -/* 191 */ +/* 232 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -54106,739 +56714,800 @@ exports.default = commands; Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = exports.getRegistryFolder = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -let getRegistryFolder = exports.getRegistryFolder = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, name) { - if (config.modulesFolder) { - return config.modulesFolder; - } +var _executeLifecycleScript; - const src = path.join(config.linkFolder, name); +function _load_executeLifecycleScript() { + return _executeLifecycleScript = __webpack_require__(97); +} - var _ref2 = yield config.readManifest(src); +var _path; - const _registry = _ref2._registry; +function _load_path() { + return _path = __webpack_require__(276); +} - invariant(_registry, 'expected registry'); +var _index; - const registryFolder = config.registries[_registry].folder; - return path.join(config.cwd, registryFolder); - }); +function _load_index() { + return _index = _interopRequireDefault(__webpack_require__(167)); +} - return function getRegistryFolder(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); +var _errors; -let run = exports.run = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (args.length) { - for (const name of args) { - const src = path.join(config.linkFolder, name); +function _load_errors() { + return _errors = __webpack_require__(3); +} - if (yield (_fs || _load_fs()).exists(src)) { - const folder = yield getRegistryFolder(config, name); - const dest = path.join(folder, name); +var _fs; - yield (_fs || _load_fs()).unlink(dest); - yield (_fs || _load_fs()).mkdirp(path.dirname(dest)); - yield (_fs || _load_fs()).symlink(src, dest); - reporter.success(reporter.lang('linkUsing', name)); - } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name)); - } - } - } else { - // add cwd module to the global registry - const manifest = yield config.readRootManifest(); - const name = manifest.name; - if (!name) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownPackageName')); - } +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - const linkLoc = path.join(config.linkFolder, name); - if (yield (_fs || _load_fs()).exists(linkLoc)) { - reporter.warn(reporter.lang('linkCollision', name)); - } else { - yield (_fs || _load_fs()).mkdirp(path.dirname(linkLoc)); - yield (_fs || _load_fs()).symlink(config.cwd, linkLoc); +var _constants; - // If there is a `bin` defined in the package.json, - // link each bin to the global bin - if (manifest.bin) { - const globalBinFolder = (0, (_global || _load_global()).getBinFolder)(config, flags); - for (const binName in manifest.bin) { - const binSrc = manifest.bin[binName]; - const binSrcLoc = path.join(linkLoc, binSrc); - const binDestLoc = path.join(globalBinFolder, binName); - if (yield (_fs || _load_fs()).exists(binDestLoc)) { - reporter.warn(reporter.lang('binLinkCollision', binName)); - } else { - yield (_fs || _load_fs()).symlink(binSrcLoc, binDestLoc); - } - } - } - - reporter.success(reporter.lang('linkRegistered', name)); - reporter.info(reporter.lang('linkRegisteredMessage', name)); - } - } - }); - - return function run(_x3, _x4, _x5, _x6) { - return _ref3.apply(this, arguments); - }; -})(); - -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); } -var _fs; +var _packageConstraintResolver; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); +function _load_packageConstraintResolver() { + return _packageConstraintResolver = _interopRequireDefault(__webpack_require__(414)); } -var _global; +var _requestManager; -function _load_global() { - return _global = __webpack_require__(59); +function _load_requestManager() { + return _requestManager = _interopRequireDefault(__webpack_require__(277)); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _index2; -const invariant = __webpack_require__(5); +function _load_index2() { + return _index2 = __webpack_require__(34); +} -const path = __webpack_require__(1); +var _index3; -function hasWrapper(commander, args) { - return true; +function _load_index3() { + return _index3 = __webpack_require__(153); } -function setFlags(commander) {} +var _map; -/***/ }), -/* 192 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); +} -"use strict"; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.buildTree = exports.requireLockfile = undefined; +const detectIndent = __webpack_require__(474); -var _slicedToArray2; +const invariant = __webpack_require__(7); +const path = __webpack_require__(0); +const micromatch = __webpack_require__(219); +const isCi = __webpack_require__(213); -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); +function sortObject(object) { + const sortedObject = {}; + Object.keys(object).sort().forEach(item => { + sortedObject[item] = object[item]; + }); + return sortedObject; } -var _asyncToGenerator2; +class Config { + constructor(reporter) { + this.constraintResolver = new (_packageConstraintResolver || _load_packageConstraintResolver()).default(this, reporter); + this.requestManager = new (_requestManager || _load_requestManager()).default(reporter); + this.reporter = reporter; + this._init({}); + } -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + // -let buildTree = exports.buildTree = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (resolver, linker, patterns, opts, onlyFresh, ignoreHoisted) { - const treesByKey = {}; - const trees = []; - const hoisted = yield linker.getFlatHoistedTree(patterns); - const hoistedByKey = {}; - for (const _ref2 of hoisted) { - var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2); + // - const key = _ref3[0]; - const info = _ref3[1]; - hoistedByKey[key] = info; - } + // - // build initial trees - for (const _ref4 of hoisted) { - var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2); - const info = _ref5[1]; + // - const ref = info.pkg._reference; - const hint = null; - const parent = getParent(info.key, treesByKey); - const children = []; - let depth = 0; - let color = 'bold'; - invariant(ref, 'expected reference'); - if (onlyFresh) { - let isFresh = false; - for (const pattern of ref.patterns) { - if (resolver.isNewPattern(pattern)) { - isFresh = true; - break; - } - } - if (!isFresh) { - continue; - } - } + // - if (info.originalKey !== info.key || opts.reqDepth === 0) { - // was hoisted - color = null; - } - // check parent to obtain next depth - if (parent && parent.depth > 0) { - depth = parent.depth + 1; - } else { - depth = 0; - } - const topLevel = opts.reqDepth === 0 && !parent; - const showAll = opts.reqDepth === -1; - const nextDepthIsValid = depth + 1 <= Number(opts.reqDepth); + // - if (topLevel || nextDepthIsValid || showAll) { - treesByKey[info.key] = { - name: `${info.pkg.name}@${info.pkg.version}`, - children, - hint, - color, - depth - }; - } - // add in dummy children for hoisted dependencies - const nextChildDepthIsValid = depth + 1 < Number(opts.reqDepth); - invariant(ref, 'expected reference'); - if (!ignoreHoisted && nextDepthIsValid || showAll) { - for (const pattern of resolver.dedupePatterns(ref.dependencies)) { - const pkg = resolver.getStrictResolvedPattern(pattern); + // - if (!hoistedByKey[`${info.key}#${pkg.name}`] && (nextChildDepthIsValid || showAll)) { - children.push({ - name: pattern, - color: 'dim', - shadow: true - }); - } - } - } - } - // add children - for (const _ref6 of hoisted) { - var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2); + // - const info = _ref7[1]; - const tree = treesByKey[info.key]; - const parent = getParent(info.key, treesByKey); - if (!tree) { - continue; - } + // - if (info.key.split('#').length === 1) { - trees.push(tree); - continue; - } - if (parent) { - parent.children.push(tree); - } - } + // - return { trees, count: buildCount(trees) }; - }); - return function buildTree(_x, _x2, _x3, _x4, _x5, _x6) { - return _ref.apply(this, arguments); - }; -})(); + // -let run = exports.run = (() => { - var _ref8 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.lockfileFolder, reporter); - const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); - var _ref9 = yield install.fetchRequestFromCwd(); + // - const depRequests = _ref9.requests, - patterns = _ref9.patterns; - yield install.resolver.init(depRequests, { isFlat: install.flags.flat, isFrozen: install.flags.frozenLockfile }); + // - const opts = { - reqDepth: getReqDepth(flags.depth) - }; - var _ref10 = yield buildTree(install.resolver, install.linker, patterns, opts); + // Whether we should ignore executing lifecycle scripts - let trees = _ref10.trees; + // - if (args.length) { - trees = trees.filter(function (tree) { - return filterTree(tree, args); - }); - } - reporter.tree('list', trees); - }); + // - return function run(_x7, _x8, _x9, _x10) { - return _ref8.apply(this, arguments); - }; -})(); -exports.getParent = getParent; -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; -exports.getReqDepth = getReqDepth; -exports.filterTree = filterTree; + // -var _install; -function _load_install() { - return _install = __webpack_require__(23); -} + // -var _wrapper; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} + /** + * Execute a promise produced by factory if it doesn't exist in our cache with + * the associated key. + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + getCache(key, factory) { + const cached = this.cache[key]; + if (cached) { + return cached; + } -const invariant = __webpack_require__(5); + return this.cache[key] = factory().catch(err => { + this.cache[key] = null; + throw err; + }); + } -const requireLockfile = exports.requireLockfile = true; + /** + * Get a config option from our yarn config. + */ -function buildCount(trees) { - if (!trees || !trees.length) { - return 0; - } + getOption(key) { + let expand = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - let count = 0; + const value = this.registries.yarn.getOption(key); - for (const tree of trees) { - if (tree.shadow) { - continue; + if (expand && typeof value === 'string') { + return (0, (_path || _load_path()).expandPath)(value); } - count++; - count += buildCount(tree.children); + return value; } - return count; -} - -function getParent(key, treesByKey) { - const parentKey = key.split('#').slice(0, -1).join('#'); - return treesByKey[parentKey]; -} - -function hasWrapper(commander, args) { - return true; -} - -function setFlags(commander) { - commander.option('--depth [depth]', 'Limit the depth of the shown dependencies'); -} - -function getReqDepth(inputDepth) { - return inputDepth && /^\d+$/.test(inputDepth) ? Number(inputDepth) : -1; -} + /** + * Reduce a list of versions to a single one based on an input range. + */ -function filterTree(tree, filters) { - if (tree.children) { - tree.children = tree.children.filter(child => filterTree(child, filters)); + resolveConstraints(versions, range) { + return this.constraintResolver.reduce(versions, range); } - const notDim = tree.color !== 'dim'; - const found = filters.indexOf(tree.name.slice(0, tree.name.lastIndexOf('@'))) > -1; - const hasChildren = tree.children == null ? false : tree.children.length > 0; + /** + * Initialise config. Fetch registry options, find package roots. + */ - return notDim && (found || hasChildren); -} + init() { + var _this = this; -/***/ }), -/* 193 */ -/***/ (function(module, exports, __webpack_require__) { + let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this._init(opts); -"use strict"; + _this.workspaceRootFolder = yield _this.findWorkspaceRoot(_this.cwd); + _this.lockfileFolder = _this.workspaceRootFolder || _this.cwd; + _this.linkedModules = []; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.requireLockfile = undefined; + let linkedModules; + try { + linkedModules = yield (_fs || _load_fs()).readdir(_this.linkFolder); + } catch (err) { + if (err.code === 'ENOENT') { + linkedModules = []; + } else { + throw err; + } + } -var _extends2; + for (const dir of linkedModules) { + const linkedPath = path.join(_this.linkFolder, dir); -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(36)); -} + if (dir[0] === '@') { + // it's a scope, not a package + const scopedLinked = yield (_fs || _load_fs()).readdir(linkedPath); + _this.linkedModules.push(...scopedLinked.map(function (scopedDir) { + return path.join(dir, scopedDir); + })); + } else { + _this.linkedModules.push(dir); + } + } -var _slicedToArray2; + for (const key of Object.keys((_index2 || _load_index2()).registries)) { + const Registry = (_index2 || _load_index2()).registries[key]; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} + // instantiate registry + const registry = new Registry(_this.cwd, _this.registries, _this.requestManager, _this.reporter); + yield registry.init(); -var _asyncToGenerator2; + _this.registries[key] = registry; + _this.registryFolders.push(registry.folder); + const rootModuleFolder = path.join(_this.cwd, registry.folder); + if (_this.rootModuleFolders.indexOf(rootModuleFolder) < 0) { + _this.rootModuleFolders.push(rootModuleFolder); + } + } -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + _this.networkConcurrency = opts.networkConcurrency || Number(_this.getOption('network-concurrency')) || (_constants || _load_constants()).NETWORK_CONCURRENCY; -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (!args.length) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('tooFewArguments', 1)); - } + _this.childConcurrency = opts.childConcurrency || Number(_this.getOption('child-concurrency')) || Number(process.env.CHILD_CONCURRENCY) || (_constants || _load_constants()).CHILD_CONCURRENCY; - const totalSteps = args.length + 1; - let step = 0; + _this.networkTimeout = opts.networkTimeout || Number(_this.getOption('network-timeout')) || (_constants || _load_constants()).NETWORK_TIMEOUT; - // load manifests - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); - const rootManifests = yield config.getRootManifests(); - const manifests = []; + _this.requestManager.setOptions({ + userAgent: String(_this.getOption('user-agent')), + httpProxy: String(opts.httpProxy || _this.getOption('proxy') || ''), + httpsProxy: String(opts.httpsProxy || _this.getOption('https-proxy') || ''), + strictSSL: Boolean(_this.getOption('strict-ssl')), + ca: Array.prototype.concat(opts.ca || _this.getOption('ca') || []).map(String), + cafile: String(opts.cafile || _this.getOption('cafile', true) || ''), + cert: String(opts.cert || _this.getOption('cert') || ''), + key: String(opts.key || _this.getOption('key') || ''), + networkConcurrency: _this.networkConcurrency, + networkTimeout: _this.networkTimeout + }); - for (const name of args) { - reporter.step(++step, totalSteps, `Removing module ${name}`); + let cacheRootFolder = opts.cacheFolder || _this.getOption('cache-folder', true); - let found = false; + if (!cacheRootFolder) { + let preferredCacheFolders = (_constants || _load_constants()).PREFERRED_MODULE_CACHE_DIRECTORIES; + const preferredCacheFolder = opts.preferredCacheFolder || _this.getOption('preferred-cache-folder', true); - for (const registryName of Object.keys((_index || _load_index()).registries)) { - const registry = config.registries[registryName]; - const object = rootManifests[registryName].object; + if (preferredCacheFolder) { + preferredCacheFolders = [String(preferredCacheFolder)].concat(preferredCacheFolders); + } - for (const type of (_constants || _load_constants()).DEPENDENCY_TYPES) { - const deps = object[type]; - if (deps && deps[name]) { - found = true; - delete deps[name]; - } + const cacheFolderQuery = yield (_fs || _load_fs()).getFirstSuitableFolder(preferredCacheFolders, (_fs || _load_fs()).constants.W_OK | (_fs || _load_fs()).constants.X_OK | (_fs || _load_fs()).constants.R_OK); + for (const skippedEntry of cacheFolderQuery.skipped) { + _this.reporter.warn(_this.reporter.lang('cacheFolderSkipped', skippedEntry.folder)); } - const possibleManifestLoc = path.join(config.cwd, registry.folder, name); - if (yield (_fs || _load_fs()).exists(possibleManifestLoc)) { - manifests.push([possibleManifestLoc, yield config.readManifest(possibleManifestLoc, registryName)]); + cacheRootFolder = cacheFolderQuery.folder; + if (cacheRootFolder && cacheFolderQuery.skipped.length > 0) { + _this.reporter.warn(_this.reporter.lang('cacheFolderSelected', cacheRootFolder)); } } - if (!found) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('moduleNotInManifest')); + if (!cacheRootFolder) { + throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('cacheFolderMissing')); + } else { + _this._cacheRootFolder = String(cacheRootFolder); } - } - - // save manifests - yield config.saveRootManifests(rootManifests); + _this.workspacesEnabled = _this.getOption('workspaces-experimental') !== false; - // run hooks - npm runs these one after another - for (const action of ['preuninstall', 'uninstall', 'postuninstall']) { - for (const _ref2 of manifests) { - var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1); + _this.pruneOfflineMirror = Boolean(_this.getOption('yarn-offline-mirror-pruning')); + _this.enableMetaFolder = Boolean(_this.getOption('enable-meta-folder')); + _this.enableLockfileVersions = Boolean(_this.getOption('yarn-enable-lockfile-versions')); + _this.linkFileDependencies = Boolean(_this.getOption('yarn-link-file-dependencies')); - const loc = _ref3[0]; + //init & create cacheFolder, tempFolder + _this.cacheFolder = path.join(_this._cacheRootFolder, 'v' + String((_constants || _load_constants()).CACHE_VERSION)); + _this.tempFolder = opts.tempFolder || path.join(_this.cacheFolder, '.tmp'); + yield (_fs || _load_fs()).mkdirp(_this.cacheFolder); + yield (_fs || _load_fs()).mkdirp(_this.tempFolder); - yield config.executeLifecycleScript(action, loc); + if (opts.production === 'false') { + _this.production = false; + } else if (_this.getOption('production') || process.env.NODE_ENV === 'production' && process.env.NPM_CONFIG_PRODUCTION !== 'false' && process.env.YARN_PRODUCTION !== 'false') { + _this.production = true; + } else { + _this.production = !!opts.production; } - } - // reinstall so we can get the updated lockfile - reporter.step(++step, totalSteps, reporter.lang('uninstallRegenerate')); - const reinstall = new (_install || _load_install()).Install((0, (_extends2 || _load_extends()).default)({ force: true }, flags), config, new (_index2 || _load_index2()).NoopReporter(), lockfile); - yield reinstall.init(); + if (_this.workspaceRootFolder && !_this.workspacesEnabled) { + throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('workspacesDisabled')); + } + })(); + } - // - reporter.success(reporter.lang('uninstalledPackages')); - }); + _init(opts) { + this.rootModuleFolders = []; + this.registryFolders = []; + this.linkedModules = []; - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); + this.registries = (0, (_map || _load_map()).default)(); + this.cache = (0, (_map || _load_map()).default)(); + this.cwd = opts.cwd || this.cwd || process.cwd(); -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; + this.looseSemver = opts.looseSemver == undefined ? true : opts.looseSemver; -var _wrapper; + this.commandName = opts.commandName || ''; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} + this.preferOffline = !!opts.preferOffline; + this.modulesFolder = opts.modulesFolder; + this.globalFolder = opts.globalFolder || (_constants || _load_constants()).GLOBAL_MODULE_DIRECTORY; + this.linkFolder = opts.linkFolder || (_constants || _load_constants()).LINK_REGISTRY_DIRECTORY; + this.offline = !!opts.offline; + this.binLinks = !!opts.binLinks; -var _index; + this.ignorePlatform = !!opts.ignorePlatform; + this.ignoreScripts = !!opts.ignoreScripts; -function _load_index() { - return _index = __webpack_require__(24); -} + this.disablePrepublish = !!opts.disablePrepublish; -var _install; + // $FlowFixMe$ + this.nonInteractive = !!opts.nonInteractive || isCi || !process.stdout.isTTY; -function _load_install() { - return _install = __webpack_require__(23); -} + this.requestManager.setOptions({ + offline: !!opts.offline && !opts.preferOffline, + captureHar: !!opts.captureHar + }); -var _errors; + if (this.modulesFolder) { + this.rootModuleFolders.push(this.modulesFolder); + } + } -function _load_errors() { - return _errors = __webpack_require__(3); -} + /** + * Generate an absolute module path. + */ -var _index2; + generateHardModulePath(pkg, ignoreLocation) { + invariant(this.cacheFolder, 'No package root'); + invariant(pkg, 'Undefined package'); -function _load_index2() { - return _index2 = __webpack_require__(82); -} + if (pkg.location && !ignoreLocation) { + return pkg.location; + } -var _fs; + let name = pkg.name; + let uid = pkg.uid; + if (pkg.registry) { + name = `${pkg.registry}-${name}`; + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + const hash = pkg.remote.hash; -var _constants; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + if (pkg.version && pkg.version !== pkg.uid) { + uid = `${pkg.version}-${uid}`; + } else if (hash) { + uid += `-${hash}`; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return path.join(this.cacheFolder, `${name}-${uid}`); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + /** + * Execute lifecycle scripts in the specified directory. Ignoring when the --ignore-scripts flag has been + * passed. + */ -const path = __webpack_require__(1); + executeLifecycleScript(commandName, cwd) { + if (this.ignoreScripts) { + return Promise.resolve(); + } else { + return (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execFromManifest)(this, commandName, cwd || this.cwd); + } + } -const requireLockfile = exports.requireLockfile = true; + /** + * Generate an absolute temporary filename location based on the input filename. + */ -function setFlags(commander) {} + getTemp(filename) { + invariant(this.tempFolder, 'No temp folder'); + return path.join(this.tempFolder, filename); + } -function hasWrapper(commander, args) { - return true; -} - -/***/ }), -/* 194 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Remote packages may be cached in a file system to be available for offline installation. + * Second time the same package needs to be installed it will be loaded from there. + * Given a package's filename, return a path in the offline mirror location. + */ -"use strict"; + getOfflineMirrorPath(packageFilename) { + let mirrorPath; + for (const key of ['npm', 'yarn']) { + const registry = this.registries[key]; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.examples = exports.hasWrapper = exports.setFlags = exports.run = exports.getName = undefined; + if (registry == null) { + continue; + } -var _asyncToGenerator2; + const registryMirrorPath = registry.config['yarn-offline-mirror']; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + if (registryMirrorPath === false) { + return null; + } -let getName = exports.getName = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args, config) { - let name = args.shift(); + if (registryMirrorPath == null) { + continue; + } - if (!name) { - const pkg = yield config.readRootManifest(); - name = pkg.name; + mirrorPath = registryMirrorPath; } - if (name) { - if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) { - throw new (_errors || _load_errors()).MessageError(config.reporter.lang('invalidPackageName')); - } + if (mirrorPath == null) { + return null; + } - return (_npmRegistry || _load_npmRegistry()).default.escapeName(name); - } else { - throw new (_errors || _load_errors()).MessageError(config.reporter.lang('unknownPackageName')); + if (packageFilename == null) { + return mirrorPath; } - }); - return function getName(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); + return path.join(mirrorPath, path.basename(packageFilename)); + } -var _packageRequest; + /** + * Checker whether the folder input is a valid module folder. We output a yarn metadata + * file when we've successfully setup a folder so use this as a marker. + */ -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); -} + isValidModuleDest(dest) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (!(yield (_fs || _load_fs()).exists(dest))) { + return false; + } -var _buildSubCommands2; + if (!(yield (_fs || _load_fs()).exists(path.join(dest, (_constants || _load_constants()).METADATA_FILENAME)))) { + return false; + } -function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); -} + return true; + })(); + } -var _login; + /** + * Read package metadata and normalized package info. + */ -function _load_login() { - return _login = __webpack_require__(60); -} + readPackageMetadata(dir) { + var _this2 = this; -var _npmRegistry; + return this.getCache(`metadata-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const metadata = yield _this2.readJson(path.join(dir, (_constants || _load_constants()).METADATA_FILENAME)); + const pkg = yield _this2.readManifest(dir, metadata.registry); -function _load_npmRegistry() { - return _npmRegistry = _interopRequireDefault(__webpack_require__(43)); -} + return { + package: pkg, + artifacts: metadata.artifacts || [], + hash: metadata.hash, + remote: metadata.remote, + registry: metadata.registry + }; + })); + } -var _errors; + /** + * Read normalized package info according yarn-metadata.json + * throw an error if package.json was not found + */ -function _load_errors() { - return _errors = __webpack_require__(3); -} + readManifest(dir, priorityRegistry) { + var _this3 = this; -var _validate; + let isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; -function _load_validate() { - return _validate = __webpack_require__(63); -} + return this.getCache(`manifest-${dir}`, (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const manifest = yield _this3.maybeReadManifest(dir, priorityRegistry, isRoot); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (manifest) { + return manifest; + } else { + throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('couldntFindPackagejson', dir), 'ENOENT'); + } + })); + } -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('tag', { - add(config, reporter, flags, args) { + /** + * try get the manifest file by looking + * 1. manifest file in cache + * 2. manifest file in registry + */ + maybeReadManifest(dir, priorityRegistry) { + var _this4 = this; + + let isRoot = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (args.length !== 2) { - return false; - } + const metadataLoc = path.join(dir, (_constants || _load_constants()).METADATA_FILENAME); - var _PackageRequest$norma = (_packageRequest || _load_packageRequest()).default.normalizePattern(args.shift()); + if (yield (_fs || _load_fs()).exists(metadataLoc)) { + const metadata = yield _this4.readJson(metadataLoc); - const name = _PackageRequest$norma.name, - range = _PackageRequest$norma.range, - hasVersion = _PackageRequest$norma.hasVersion; + if (!priorityRegistry) { + priorityRegistry = metadata.priorityRegistry; + } - if (!hasVersion) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('requiredVersionInRange')); + if (typeof metadata.manifest !== 'undefined') { + return metadata.manifest; + } } - if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName')); + + if (priorityRegistry) { + const file = yield _this4.tryManifest(dir, priorityRegistry, isRoot); + if (file) { + return file; + } } - const tag = args.shift(); + for (const registry of Object.keys((_index2 || _load_index2()).registries)) { + if (priorityRegistry === registry) { + continue; + } - reporter.step(1, 3, reporter.lang('loggingIn')); - const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); + const file = yield _this4.tryManifest(dir, registry, isRoot); + if (file) { + return file; + } + } - reporter.step(2, 3, reporter.lang('creatingTag', tag, range)); - const result = yield config.registries.npm.request(`-/package/${(_npmRegistry || _load_npmRegistry()).default.escapeName(name)}/dist-tags/${encodeURI(tag)}`, { - method: 'PUT', - body: range - }); + return null; + })(); + } - if (result != null && result.ok) { - reporter.success(reporter.lang('createdTag')); - } else { - reporter.error(reporter.lang('createdTagFail')); - } + /** + * Read the root manifest. + */ - reporter.step(3, 3, reporter.lang('revokingToken')); - yield revoke(); + readRootManifest() { + return this.readManifest(this.cwd, 'npm', true); + } - if (result != null && result.ok) { - return true; + /** + * Try and find package info with the input directory and registry. + */ + + tryManifest(dir, registry, isRoot) { + var _this5 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const filename = (_index2 || _load_index2()).registries[registry].filename; + + const loc = path.join(dir, filename); + if (yield (_fs || _load_fs()).exists(loc)) { + const data = yield _this5.readJson(loc); + data._registry = registry; + data._loc = loc; + return (0, (_index || _load_index()).default)(data, dir, _this5, isRoot); } else { - throw new Error(); + return null; } })(); - }, + } + + findManifest(dir, isRoot) { + var _this6 = this; - rm(config, reporter, flags, args) { return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (args.length !== 2) { - return false; + for (const registry of (_index2 || _load_index2()).registryNames) { + const manifest = yield _this6.tryManifest(dir, registry, isRoot); + + if (manifest) { + return manifest; + } } - const name = yield getName(args, config); - const tag = args.shift(); + return null; + })(); + } - reporter.step(1, 3, reporter.lang('loggingIn')); - const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); + findWorkspaceRoot(initial) { + var _this7 = this; - reporter.step(2, 3, reporter.lang('deletingTags')); - const result = yield config.registries.npm.request(`-/package/${name}/dist-tags/${encodeURI(tag)}`, { - method: 'DELETE' - }); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let previous = null; + let current = path.normalize(initial); - if (result === false) { - reporter.error(reporter.lang('deletedTagFail')); - } else { - reporter.success(reporter.lang('deletedTag')); + do { + const manifest = yield _this7.findManifest(current, true); + if (manifest && manifest.workspaces) { + const relativePath = path.relative(current, initial); + if (relativePath === '' || micromatch([relativePath], manifest.workspaces).length > 0) { + return current; + } else { + return null; + } + } + + previous = current; + current = path.dirname(current); + } while (current !== previous); + + return null; + })(); + } + + resolveWorkspaces(root, rootManifest) { + var _this8 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const workspaces = {}; + const patterns = rootManifest.workspaces || []; + if (!_this8.workspacesEnabled) { + return workspaces; + } + if (!rootManifest.private && patterns.length > 0) { + throw new (_errors || _load_errors()).MessageError(_this8.reporter.lang('workspacesRequirePrivateProjects')); } - reporter.step(3, 3, reporter.lang('revokingToken')); - yield revoke(); + const registryFilenames = (_index2 || _load_index2()).registryNames.map(function (registryName) { + return _this8.registries[registryName].constructor.filename; + }).join('|'); + const trailingPattern = `/+(${registryFilenames})`; + const ignorePatterns = _this8.registryFolders.map(function (folder) { + return `/${folder}/*/+(${registryFilenames})`; + }); - if (result === false) { - throw new Error(); - } else { - return true; + const files = yield Promise.all(patterns.map(function (pattern) { + return (_fs || _load_fs()).glob(pattern.replace(/\/?$/, trailingPattern), { + cwd: root, + ignore: ignorePatterns.map(function (ignorePattern) { + return pattern.replace(/\/?$/, ignorePattern); + }) + }); + })); + + for (const file of new Set([].concat(...files))) { + const loc = path.join(root, path.dirname(file)); + const manifest = yield _this8.findManifest(loc, false); + + if (!manifest) { + continue; + } + + if (!manifest.name) { + _this8.reporter.warn(_this8.reporter.lang('workspaceNameMandatory', loc)); + continue; + } + if (!manifest.version) { + _this8.reporter.warn(_this8.reporter.lang('workspaceVersionMandatory', loc)); + continue; + } + + if (Object.prototype.hasOwnProperty.call(workspaces, manifest.name)) { + throw new (_errors || _load_errors()).MessageError(_this8.reporter.lang('workspaceNameDuplicate', manifest.name)); + } + + workspaces[manifest.name] = { loc, manifest }; } + + return workspaces; })(); - }, + } - ls(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const name = yield getName(args, config); + /** + * Description + */ - reporter.step(1, 3, reporter.lang('loggingIn')); - const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); + getFolder(pkg) { + let registryName = pkg._registry; + if (!registryName) { + const ref = pkg._reference; + invariant(ref, 'expected reference'); + registryName = ref.registry; + } + return this.registries[registryName].folder; + } + + /** + * Get root manifests. + */ + + getRootManifests() { + var _this9 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const manifests = {}; + for (const registryName of (_index2 || _load_index2()).registryNames) { + const registry = (_index2 || _load_index2()).registries[registryName]; + const jsonLoc = path.join(_this9.cwd, registry.filename); - reporter.step(2, 3, reporter.lang('gettingTags')); - const tags = yield config.registries.npm.request(`-/package/${name}/dist-tags`); + let object = {}; + let exists = false; + let indent; + if (yield (_fs || _load_fs()).exists(jsonLoc)) { + exists = true; - if (tags) { - reporter.info(`Package ${name}`); - for (const name in tags) { - reporter.info(`${name}: ${tags[name]}`); + const info = yield _this9.readJson(jsonLoc, (_fs || _load_fs()).readJsonAndFile); + object = info.object; + indent = detectIndent(info.content).indent || undefined; } + manifests[registryName] = { loc: jsonLoc, object, exists, indent }; } + return manifests; + })(); + } - reporter.step(3, 3, reporter.lang('revokingToken')); - yield revoke(); + /** + * Save root manifests. + */ - if (!tags) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('packageNotFoundRegistry', name, 'npm')); + saveRootManifests(manifests) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + for (const registryName of (_index2 || _load_index2()).registryNames) { + var _manifests$registryNa = manifests[registryName]; + const loc = _manifests$registryNa.loc, + object = _manifests$registryNa.object, + exists = _manifests$registryNa.exists, + indent = _manifests$registryNa.indent; + + if (!exists && !Object.keys(object).length) { + continue; + } + + for (const field of (_constants || _load_constants()).DEPENDENCY_TYPES) { + if (object[field]) { + object[field] = sortObject(object[field]); + } + } + + yield (_fs || _load_fs()).writeFilePreservingEol(loc, JSON.stringify(object, null, indent || (_constants || _load_constants()).DEFAULT_INDENT) + '\n'); } })(); } -}, ['add <pkg>@<version> [<tag>]', 'rm <pkg> <tag>', 'ls [<pkg>]']); -const run = _buildSubCommands.run, - setFlags = _buildSubCommands.setFlags, - hasWrapper = _buildSubCommands.hasWrapper, - examples = _buildSubCommands.examples; -exports.run = run; -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; -exports.examples = examples; + /** + * Call the passed factory (defaults to fs.readJson) and rethrow a pretty error message if it was the result + * of a syntax error. + */ + + readJson(loc) { + let factory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_fs || _load_fs()).readJson; + + try { + return factory(loc); + } catch (err) { + if (err instanceof SyntaxError) { + throw new (_errors || _load_errors()).MessageError(this.reporter.lang('jsonError', loc, err.message)); + } else { + throw err; + } + } + } + + static create() { + let opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + let reporter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new (_index3 || _load_index3()).NoopReporter(); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const config = new Config(reporter); + yield config.init(opts); + return config; + })(); + } +} +exports.default = Config; /***/ }), -/* 195 */ +/* 233 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -54847,1784 +57516,1988 @@ exports.examples = examples; Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = exports.requireLockfile = undefined; +exports.isOffline = isOffline; +const os = __webpack_require__(47); -var _asyncToGenerator2; +const IGNORE_INTERFACES = ['lo0', 'awdl0', 'bridge0']; +const LOCAL_IPS = ['127.0.0.1', '::1']; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +function isOffline() { + let interfaces; -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.lockfileFolder); - const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); - const deps = yield (_packageRequest || _load_packageRequest()).default.getOutdatedPackages(lockfile, install, config, reporter); + try { + interfaces = os.networkInterfaces(); + } catch (e) { + // As of October 2016, Windows Subsystem for Linux (WSL) does not support + // the os.networkInterfaces() call and throws instead. For this platform, + // assume we are online. + if (e.syscall === 'uv_interface_addresses') { + return false; + } else { + throw e; + } + } - if (!deps.length) { - reporter.success(reporter.lang('allDependenciesUpToDate')); - return; + for (const name in interfaces) { + if (IGNORE_INTERFACES.indexOf(name) >= 0) { + continue; } - const getNameFromHint = function (hint) { - return hint ? `${hint}Dependencies` : 'dependencies'; - }; + const addrs = interfaces[name]; + for (const addr of addrs) { + if (LOCAL_IPS.indexOf(addr.address) < 0) { + // found a possible remote ip + return false; + } + } + } - const maxLengthArr = { name: 0, current: 0, latest: 0 }; - deps.forEach(function (dep) { - return ['name', 'current', 'latest'].forEach(function (key) { - maxLengthArr[key] = Math.max(maxLengthArr[key], dep[key].length); - }); - }); + return true; +} - // Depends on maxLengthArr - const addPadding = function (dep) { - return function (key) { - return `${dep[key]}${' '.repeat(maxLengthArr[key] - dep[key].length)}`; - }; - }; +/***/ }), +/* 234 */ +/***/ (function(module, exports) { - const colorizeName = function (_ref2) { - let current = _ref2.current, - wanted = _ref2.wanted; - return current === wanted ? reporter.format.yellow : reporter.format.red; - }; +function webpackEmptyContext(req) { + throw new Error("Cannot find module '" + req + "'."); +} +webpackEmptyContext.keys = function() { return []; }; +webpackEmptyContext.resolve = webpackEmptyContext; +module.exports = webpackEmptyContext; +webpackEmptyContext.id = 234; - const colorizeDiff = function (from, to) { - const parts = to.split('.'); - const fromParts = from.split('.'); +/***/ }), +/* 235 */ +/***/ (function(module, exports, __webpack_require__) { - const index = parts.findIndex(function (part, i) { - return part !== fromParts[i]; - }); - const splitIndex = index >= 0 ? index : parts.length; +"use strict"; - const colorized = reporter.format.green(parts.slice(splitIndex).join('.')); - return parts.slice(0, splitIndex).concat(colorized).join('.'); - }; - const makeRow = function (dep) { - const padding = addPadding(dep); - const name = colorizeName(dep)(padding('name')); - const current = reporter.format.blue(padding('current')); - const latest = colorizeDiff(dep.current, padding('latest')); - const url = reporter.format.cyan(dep.url); - return `${name} ${current} ⯠${latest} ${url}`; - }; +module.exports = { + setup: setupAsync, + compile: compileAsync +}; - const groupedDeps = deps.reduce(function (acc, dep) { - const hint = dep.hint, - name = dep.name, - latest = dep.latest; - const key = getNameFromHint(hint); - const xs = acc[key] || []; - acc[key] = xs.concat({ - name: makeRow(dep), - value: dep, - short: `${name}@${latest}` - }); - return acc; - }, {}); +var util = __webpack_require__(60); - const flatten = function (xs) { - return xs.reduce(function (ys, y) { - return ys.concat(Array.isArray(y) ? flatten(y) : y); - }, []); - }; +var ASYNC = { + '*': checkGenerators, + 'co*': checkGenerators, + 'es7': checkAsyncFunction +}; - const choices = flatten(Object.keys(groupedDeps).map(function (key) { - return [new (_inquirer || _load_inquirer()).default.Separator(reporter.format.bold.underline.green(key)), groupedDeps[key], new (_inquirer || _load_inquirer()).default.Separator(' ')]; - })); - - try { - const red = reporter.format.red('<red>'); - const yellow = reporter.format.yellow('<yellow>'); - reporter.info(reporter.lang('legendColorsForUpgradeInteractive', red, yellow)); - - const answers = yield reporter.prompt('Choose which packages to update.', choices, { - name: 'packages', - type: 'checkbox', - validate: function (answer) { - return !!answer.length || 'You must choose at least one package.'; - } - }); - - const getName = function (_ref3) { - let name = _ref3.name; - return name; - }; - const isHint = function (x) { - return function (_ref4) { - let hint = _ref4.hint; - return hint === x; - }; - }; +var TRANSPILE = { + 'nodent': getNodent, + 'regenerator': getRegenerator +}; - yield [null, 'dev', 'optional', 'peer'].reduce((() => { - var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (promise, hint) { - // Wait for previous promise to resolve - yield promise; - // Reset dependency flags - flags.dev = hint === 'dev'; - flags.peer = hint === 'peer'; - flags.optional = hint === 'optional'; +var MODES = [ + { async: 'co*' }, + { async: 'es7', transpile: 'nodent' }, + { async: 'co*', transpile: 'regenerator' } +]; - const deps = answers.filter(isHint(hint)).map(getName); - if (deps.length) { - reporter.info(reporter.lang('updateInstalling', getNameFromHint(hint))); - const add = new (_add || _load_add()).Add(deps, flags, config, reporter, lockfile); - return add.init(); - } - return Promise.resolve(); - }); - return function (_x5, _x6) { - return _ref5.apply(this, arguments); - }; - })(), Promise.resolve()); - } catch (e) { - Promise.reject(e); - } - }); +var regenerator, nodent; - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; +function setupAsync(opts, required) { + if (required !== false) required = true; + var async = opts.async + , transpile = opts.transpile + , check; -var _inquirer; + switch (typeof transpile) { + case 'string': + var get = TRANSPILE[transpile]; + if (!get) throw new Error('bad transpiler: ' + transpile); + return (opts._transpileFunc = get(opts, required)); + case 'undefined': + case 'boolean': + if (typeof async == 'string') { + check = ASYNC[async]; + if (!check) throw new Error('bad async mode: ' + async); + return (opts.transpile = check(opts, required)); + } -function _load_inquirer() { - return _inquirer = _interopRequireDefault(__webpack_require__(152)); + for (var i=0; i<MODES.length; i++) { + var _opts = MODES[i]; + if (setupAsync(_opts, false)) { + util.copy(_opts, opts); + return opts.transpile; + } + } + /* istanbul ignore next */ + throw new Error('generators, nodent and regenerator are not available'); + case 'function': + return (opts._transpileFunc = opts.transpile); + default: + throw new Error('bad transpiler: ' + transpile); + } } -var _packageRequest; -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); +function checkGenerators(opts, required) { + /* jshint evil: true */ + try { + (new Function('(function*(){})()'))(); + return true; + } catch(e) { + /* istanbul ignore next */ + if (required) throw new Error('generators not supported'); + } } -var _add; -function _load_add() { - return _add = __webpack_require__(78); +function checkAsyncFunction(opts, required) { + /* jshint evil: true */ + try { + (new Function('(async function(){})()'))(); + /* istanbul ignore next */ + return true; + } catch(e) { + if (required) throw new Error('es7 async functions not supported'); + } } -var _install; -function _load_install() { - return _install = __webpack_require__(23); +function getRegenerator(opts, required) { + try { + if (!regenerator) { + var name = 'regenerator'; + regenerator = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()); + regenerator.runtime(); + } + if (!opts.async || opts.async === true) + opts.async = 'es7'; + return regeneratorTranspile; + } catch(e) { + /* istanbul ignore next */ + if (required) throw new Error('regenerator not available'); + } } -var _wrapper; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); +function regeneratorTranspile(code) { + return regenerator.compile(code).code; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const requireLockfile = exports.requireLockfile = true; - -function setFlags(commander) { - commander.usage('upgrade-interactive'); - commander.option('-E, --exact', 'upgrade to most recent release with exact version'); - commander.option('-T, --tilde', 'upgrade to most recent release with patch version'); -} -function hasWrapper(commander, args) { - return true; +function getNodent(opts, required) { + /* jshint evil: true */ + try { + if (!nodent) { + var name = 'nodent'; + nodent = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())({ log: false, dontInstallRequireHook: true }); + } + if (opts.async != 'es7') { + if (opts.async && opts.async !== true) console.warn('nodent transpiles only es7 async functions'); + opts.async = 'es7'; + } + return nodentTranspile; + } catch(e) { + /* istanbul ignore next */ + if (required) throw new Error('nodent not available'); + } } -/***/ }), -/* 196 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.requireLockfile = undefined; - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function nodentTranspile(code) { + return nodent.compile(code, '', { promises: true, sourcemap: false }).code; } -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const useLockfile = args.length || flags.latest; - const lockfile = useLockfile ? yield (_wrapper || _load_wrapper()).default.fromDirectory(config.lockfileFolder, reporter) : new (_wrapper || _load_wrapper()).default(); - - var _ref2 = (yield config.readRootManifest()) || {}; - const dependencies = _ref2.dependencies, - devDependencies = _ref2.devDependencies, - optionalDependencies = _ref2.optionalDependencies, - peerDependencies = _ref2.peerDependencies; +/** + * Creates validating function for passed schema with asynchronous loading of missing schemas. + * `loadSchema` option should be a function that accepts schema uri and node-style callback. + * @this Ajv + * @param {Object} schema schema object + * @param {Function} callback node-style callback, it is always called with 2 parameters: error (or null) and validating function. + */ +function compileAsync(schema, callback) { + /* eslint no-shadow: 0 */ + /* jshint validthis: true */ + var schemaObj; + var self = this; + try { + schemaObj = this._addSchema(schema); + } catch(e) { + setTimeout(function() { callback(e); }); + return; + } + if (schemaObj.validate) { + setTimeout(function() { callback(null, schemaObj.validate); }); + } else { + if (typeof this._opts.loadSchema != 'function') + throw new Error('options.loadSchema should be a function'); + _compileAsync(schema, callback, true); + } - const allDependencies = Object.assign({}, peerDependencies, optionalDependencies, devDependencies, dependencies); - let addArgs = []; - if (flags.scope) { - if (!flags.scope.startsWith('@')) { - flags.scope = '@' + flags.scope; - } + function _compileAsync(schema, callback, firstCall) { + var validate; + try { validate = self.compile(schema); } + catch(e) { + if (e.missingSchema) loadMissingSchema(e); + else deferCallback(e); + return; + } + deferCallback(null, validate); - if (!flags.scope.endsWith('/')) { - flags.scope += '/'; + function loadMissingSchema(e) { + var ref = e.missingSchema; + if (self._refs[ref] || self._schemas[ref]) + return callback(new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved')); + var _callbacks = self._loadingSchemas[ref]; + if (_callbacks) { + if (typeof _callbacks == 'function') + self._loadingSchemas[ref] = [_callbacks, schemaLoaded]; + else + _callbacks[_callbacks.length] = schemaLoaded; + } else { + self._loadingSchemas[ref] = schemaLoaded; + self._opts.loadSchema(ref, function (err, sch) { + var _callbacks = self._loadingSchemas[ref]; + delete self._loadingSchemas[ref]; + if (typeof _callbacks == 'function') { + _callbacks(err, sch); + } else { + for (var i=0; i<_callbacks.length; i++) + _callbacks[i](err, sch); + } + }); } - if (/^@[a-zA-Z0-9-][a-zA-Z0-9_.-]*\/$/g.test(flags.scope)) { - addArgs = Object.keys(allDependencies).filter(function (dependency) { - return dependency.startsWith(flags.scope); - }).map(function (dependency) { - return getDependency(allDependencies, dependency); - }); - } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('scopeNotValid')); + function schemaLoaded(err, sch) { + if (err) return callback(err); + if (!(self._refs[ref] || self._schemas[ref])) { + try { + self.addSchema(sch, ref); + } catch(e) { + callback(e); + return; + } + } + _compileAsync(schema, callback); } - } else if (flags.latest && args.length === 0) { - addArgs = Object.keys(allDependencies).map(function (dependency) { - return getDependency(allDependencies, dependency); - }); - } else { - addArgs = args.map(function (dependency) { - return getDependency(allDependencies, dependency); - }); } - const addFlags = Object.assign({}, flags, { force: true }); - - const install = new (_add || _load_add()).Add(addArgs, addFlags, config, reporter, lockfile); - yield install.init(); - }); - - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); + function deferCallback(err, validate) { + if (firstCall) setTimeout(function() { callback(err, validate); }); + else return callback(err, validate); + } + } +} -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; -var _add; +/***/ }), +/* 236 */ +/***/ (function(module, exports, __webpack_require__) { -function _load_add() { - return _add = __webpack_require__(78); -} +"use strict"; -var _wrapper; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} +/*eslint complexity: 0*/ -var _packageRequest; +module.exports = function equal(a, b) { + if (a === b) return true; -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); -} + var arrA = Array.isArray(a) + , arrB = Array.isArray(b) + , i; -var _errors; + if (arrA && arrB) { + if (a.length != b.length) return false; + for (i = 0; i < a.length; i++) + if (!equal(a[i], b[i])) return false; + return true; + } -function _load_errors() { - return _errors = __webpack_require__(3); -} + if (arrA != arrB) return false; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (a && b && typeof a === 'object' && typeof b === 'object') { + var keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) return false; -function setFlags(commander) { - // TODO: support some flags that install command has - commander.usage('upgrade [flags]'); - commander.option('-S, --scope <scope>', 'upgrade packages under the specified scope'); - commander.option('--latest', 'upgrade packages to the latest version, ignoring version ranges in package.json'); -} + var dateA = a instanceof Date + , dateB = b instanceof Date; + if (dateA && dateB) return a.getTime() == b.getTime(); + if (dateA != dateB) return false; -function hasWrapper(commander, args) { - return true; -} + var regexpA = a instanceof RegExp + , regexpB = b instanceof RegExp; + if (regexpA && regexpB) return a.toString() == b.toString(); + if (regexpA != regexpB) return false; -const requireLockfile = exports.requireLockfile = true; + for (i = 0; i < keys.length; i++) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; -function getDependency(allDependencies, dependency) { - const remoteSource = allDependencies[dependency]; + for (i = 0; i < keys.length; i++) + if(!equal(a[keys[i]], b[keys[i]])) return false; - if (remoteSource && (_packageRequest || _load_packageRequest()).default.getExoticResolver(remoteSource)) { - return remoteSource; + return true; } - return dependency; -} + return false; +}; + /***/ }), -/* 197 */ +/* 237 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.setVersion = undefined; - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -let setVersion = exports.setVersion = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args, required) { - const pkg = yield config.readRootManifest(); - const pkgLoc = pkg._loc; - const scripts = (0, (_map || _load_map()).default)(); - let newVersion = flags.newVersion; - invariant(pkgLoc, 'expected package location'); +var url = __webpack_require__(14) + , equal = __webpack_require__(236) + , util = __webpack_require__(60) + , SchemaObject = __webpack_require__(238); - if (args.length && !newVersion) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidVersionArgument', NEW_VERSION_FLAG)); - } +module.exports = resolve; - function runLifecycle(lifecycle) { - if (scripts[lifecycle]) { - return (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execCommand)(lifecycle, config, scripts[lifecycle], config.cwd); - } +resolve.normalizeId = normalizeId; +resolve.fullPath = getFullPath; +resolve.url = resolveUrl; +resolve.ids = resolveIds; +resolve.inlineRef = inlineRef; +resolve.schema = resolveSchema; - return Promise.resolve(); - } +/** + * [resolve and compile the references ($ref)] + * @this Ajv + * @param {Function} compile reference to schema compilation funciton (localCompile) + * @param {Object} root object with information about the root schema for the current schema + * @param {String} ref reference to resolve + * @return {Object|Function} schema object (if the schema can be inlined) or validation function + */ +function resolve(compile, root, ref) { + /* jshint validthis: true */ + var refVal = this._refs[ref]; + if (typeof refVal == 'string') { + if (this._refs[refVal]) refVal = this._refs[refVal]; + else return resolve.call(this, compile, root, refVal); + } - if (pkg.scripts) { - // inherit `scripts` from manifest - Object.assign(scripts, pkg.scripts); - } + refVal = refVal || this._schemas[ref]; + if (refVal instanceof SchemaObject) { + return inlineRef(refVal.schema, this._opts.inlineRefs) + ? refVal.schema + : refVal.validate || this._compile(refVal); + } - // get old version - let oldVersion = pkg.version; - if (oldVersion) { - reporter.info(`${reporter.lang('currentVersion')}: ${oldVersion}`); - } else { - oldVersion = '0.0.0'; - } + var res = resolveSchema.call(this, root, ref); + var schema, v, baseId; + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } - // get new version - if (newVersion && !isValidNewVersion(oldVersion, newVersion, config.looseSemver)) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidVersion')); - } + if (schema instanceof SchemaObject) { + v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); + } else if (schema) { + v = inlineRef(schema, this._opts.inlineRefs) + ? schema + : compile.call(this, schema, root, undefined, baseId); + } - // wasn't passed a version arg so ask interactively - while (!newVersion) { - newVersion = yield reporter.question(reporter.lang('newVersion')); + return v; +} - if (!required && !newVersion) { - return function () { - return Promise.resolve(); - }; - } - if (isValidNewVersion(oldVersion, newVersion, config.looseSemver)) { - break; +/** + * Resolve schema, its root and baseId + * @this Ajv + * @param {Object} root root object with properties schema, refVal, refs + * @param {String} ref reference to resolve + * @return {Object} object with properties schema, root, baseId + */ +function resolveSchema(root, ref) { + /* jshint validthis: true */ + var p = url.parse(ref, false, true) + , refPath = _getFullPath(p) + , baseId = getFullPath(root.schema.id); + if (refPath !== baseId) { + var id = normalizeId(refPath); + var refVal = this._refs[id]; + if (typeof refVal == 'string') { + return resolveRecursive.call(this, root, refVal, p); + } else if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + root = refVal; + } else { + refVal = this._schemas[id]; + if (refVal instanceof SchemaObject) { + if (!refVal.validate) this._compile(refVal); + if (id == normalizeId(ref)) + return { schema: refVal, root: root, baseId: baseId }; + root = refVal; } else { - newVersion = null; - reporter.error(reporter.lang('invalidSemver')); + return; } } - if (newVersion) { - newVersion = semver.inc(oldVersion, newVersion, config.looseSemver) || newVersion; - } - invariant(newVersion, 'expected new version'); + if (!root.schema) return; + baseId = getFullPath(root.schema.id); + } + return getJsonPointer.call(this, p, baseId, root.schema, root); +} - if (newVersion === pkg.version) { - return function () { - return Promise.resolve(); - }; - } - yield runLifecycle('preversion'); +/* @this Ajv */ +function resolveRecursive(root, ref, parsedRef) { + /* jshint validthis: true */ + var res = resolveSchema.call(this, root, ref); + if (res) { + var schema = res.schema; + var baseId = res.baseId; + root = res.root; + if (schema.id) baseId = resolveUrl(baseId, schema.id); + return getJsonPointer.call(this, parsedRef, baseId, schema, root); + } +} - // update version - reporter.info(`${reporter.lang('newVersion')}: ${newVersion}`); - pkg.version = newVersion; - // update versions in manifests - const manifests = yield config.getRootManifests(); - for (const registryName of (_index || _load_index()).registryNames) { - const manifest = manifests[registryName]; - if (manifest.exists) { - manifest.object.version = newVersion; +var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); +/* @this Ajv */ +function getJsonPointer(parsedRef, baseId, schema, root) { + /* jshint validthis: true */ + parsedRef.hash = parsedRef.hash || ''; + if (parsedRef.hash.slice(0,2) != '#/') return; + var parts = parsedRef.hash.split('/'); + + for (var i = 1; i < parts.length; i++) { + var part = parts[i]; + if (part) { + part = util.unescapeFragment(part); + schema = schema[part]; + if (!schema) break; + if (schema.id && !PREVENT_SCOPE_CHANGE[part]) baseId = resolveUrl(baseId, schema.id); + if (schema.$ref) { + var $ref = resolveUrl(baseId, schema.$ref); + var res = resolveSchema.call(this, root, $ref); + if (res) { + schema = res.schema; + root = res.root; + baseId = res.baseId; + } } } - yield config.saveRootManifests(manifests); + } + if (schema && schema != root.schema) + return { schema: schema, root: root, baseId: baseId }; +} - // check if committing the new version to git is overriden - if (!flags.gitTagVersion || !config.getOption('version-git-tag')) { - // Don't tag the version in Git - return function () { - return Promise.resolve(); - }; - } - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - invariant(newVersion, 'expected version'); - - // add git commit and tag - let isGit = false; - const parts = config.cwd.split(path.sep); - while (parts.length) { - isGit = yield (_fs || _load_fs()).exists(path.join(parts.join(path.sep), '.git')); - if (isGit) { - break; - } else { - parts.pop(); - } - } - - yield runLifecycle('version'); - - if (isGit) { - const message = (flags.message || String(config.getOption('version-git-message'))).replace(/%s/g, newVersion); - const sign = Boolean(config.getOption('version-sign-git-tag')); - const flag = sign ? '-sm' : '-am'; - const prefix = String(config.getOption('version-tag-prefix')); - - // add manifest - yield (0, (_child || _load_child()).spawn)('git', ['add', pkgLoc]); - - // create git commit - yield (0, (_child || _load_child()).spawn)('git', ['commit', '-m', message]); - - // create git tag - yield (0, (_child || _load_child()).spawn)('git', ['tag', `${prefix}${newVersion}`, flag, message]); - } - - yield runLifecycle('postversion'); - }); - }); - - return function setVersion(_x, _x2, _x3, _x4, _x5) { - return _ref.apply(this, arguments); - }; -})(); - -let run = exports.run = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const commit = yield setVersion(config, reporter, flags, args, true); - yield commit(); - }); - - return function run(_x6, _x7, _x8, _x9) { - return _ref3.apply(this, arguments); - }; -})(); -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; +var SIMPLE_INLINED = util.toHash([ + 'type', 'format', 'pattern', + 'maxLength', 'minLength', + 'maxProperties', 'minProperties', + 'maxItems', 'minItems', + 'maximum', 'minimum', + 'uniqueItems', 'multipleOf', + 'required', 'enum' +]); +function inlineRef(schema, limit) { + if (limit === false) return false; + if (limit === undefined || limit === true) return checkNoRef(schema); + else if (limit) return countKeys(schema) <= limit; +} -var _index; -function _load_index() { - return _index = __webpack_require__(24); +function checkNoRef(schema) { + var item; + if (Array.isArray(schema)) { + for (var i=0; i<schema.length; i++) { + item = schema[i]; + if (typeof item == 'object' && !checkNoRef(item)) return false; + } + } else { + for (var key in schema) { + if (key == '$ref') return false; + item = schema[key]; + if (typeof item == 'object' && !checkNoRef(item)) return false; + } + } + return true; } -var _executeLifecycleScript; -function _load_executeLifecycleScript() { - return _executeLifecycleScript = __webpack_require__(62); +function countKeys(schema) { + var count = 0, item; + if (Array.isArray(schema)) { + for (var i=0; i<schema.length; i++) { + item = schema[i]; + if (typeof item == 'object') count += countKeys(item); + if (count == Infinity) return Infinity; + } + } else { + for (var key in schema) { + if (key == '$ref') return Infinity; + if (SIMPLE_INLINED[key]) { + count++; + } else { + item = schema[key]; + if (typeof item == 'object') count += countKeys(item) + 1; + if (count == Infinity) return Infinity; + } + } + } + return count; } -var _errors; -function _load_errors() { - return _errors = __webpack_require__(3); +function getFullPath(id, normalize) { + if (normalize !== false) id = normalizeId(id); + var p = url.parse(id, false, true); + return _getFullPath(p); } -var _child; -function _load_child() { - return _child = __webpack_require__(45); +function _getFullPath(p) { + var protocolSeparator = p.protocol || p.href.slice(0,2) == '//' ? '//' : ''; + return (p.protocol||'') + protocolSeparator + (p.host||'') + (p.path||'') + '#'; } -var _fs; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); +var TRAILING_SLASH_HASH = /#\/?$/; +function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; } -var _map; -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); +function resolveUrl(baseId, id) { + id = normalizeId(id); + return url.resolve(baseId, id); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const invariant = __webpack_require__(5); -const semver = __webpack_require__(27); -const path = __webpack_require__(1); +/* @this Ajv */ +function resolveIds(schema) { + /* eslint no-shadow: 0 */ + /* jshint validthis: true */ + var id = normalizeId(schema.id); + var localRefs = {}; + _resolveIds.call(this, schema, getFullPath(id, false), id); + return localRefs; -const NEW_VERSION_FLAG = '--new-version [version]'; -function isValidNewVersion(oldVersion, newVersion, looseSemver) { - return !!(semver.valid(newVersion, looseSemver) || semver.inc(oldVersion, newVersion, looseSemver)); -} + /* @this Ajv */ + function _resolveIds(schema, fullPath, baseId) { + /* jshint validthis: true */ + if (Array.isArray(schema)) { + for (var i=0; i<schema.length; i++) + _resolveIds.call(this, schema[i], fullPath+'/'+i, baseId); + } else if (schema && typeof schema == 'object') { + if (typeof schema.id == 'string') { + var id = baseId = baseId + ? url.resolve(baseId, schema.id) + : schema.id; + id = normalizeId(id); -function setFlags(commander) { - commander.option(NEW_VERSION_FLAG, 'new version'); - commander.option('--message [message]', 'message'); - commander.option('--no-git-tag-version', 'no git tag version'); + var refVal = this._refs[id]; + if (typeof refVal == 'string') refVal = this._refs[refVal]; + if (refVal && refVal.schema) { + if (!equal(schema, refVal.schema)) + throw new Error('id "' + id + '" resolves to more than one schema'); + } else if (id != normalizeId(fullPath)) { + if (id[0] == '#') { + if (localRefs[id] && !equal(schema, localRefs[id])) + throw new Error('id "' + id + '" resolves to more than one schema'); + localRefs[id] = schema; + } else { + this._refs[id] = fullPath; + } + } + } + for (var key in schema) + _resolveIds.call(this, schema[key], fullPath+'/'+util.escapeFragment(key), baseId); + } + } } -function hasWrapper(commander, args) { - return true; -} /***/ }), -/* 198 */ +/* 238 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.LocalTarballFetcher = undefined; - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -var _http; - -function _load_http() { - return _http = _interopRequireDefault(__webpack_require__(50)); -} +var util = __webpack_require__(60); -var _errors; +module.exports = SchemaObject; -function _load_errors() { - return _errors = __webpack_require__(3); +function SchemaObject(obj) { + util.copy(obj, this); } -var _constants; - -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} -var _crypto; +/***/ }), +/* 239 */ +/***/ (function(module, exports, __webpack_require__) { -function _load_crypto() { - return _crypto = _interopRequireWildcard(__webpack_require__(85)); -} +"use strict"; -var _baseFetcher; -function _load_baseFetcher() { - return _baseFetcher = _interopRequireDefault(__webpack_require__(79)); -} +module.exports = ValidationError; -var _fs; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); +function ValidationError(errors) { + this.message = 'validation failed'; + this.errors = errors; + this.ajv = this.validation = true; } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const path = __webpack_require__(1); -const tarFs = __webpack_require__(109); -const url = __webpack_require__(11); -const fs = __webpack_require__(6); -const stream = __webpack_require__(20); -const gunzip = __webpack_require__(482); +ValidationError.prototype = Object.create(Error.prototype); +ValidationError.prototype.constructor = ValidationError; -class TarballFetcher extends (_baseFetcher || _load_baseFetcher()).default { - setupMirrorFromCache() { - var _this = this; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const tarballMirrorPath = _this.getTarballMirrorPath(); - const tarballCachePath = _this.getTarballCachePath(); +/***/ }), +/* 240 */ +/***/ (function(module, exports, __webpack_require__) { - if (tarballMirrorPath == null) { - return; - } +"use strict"; - if (!(yield (_fs || _load_fs()).exists(tarballMirrorPath)) && (yield (_fs || _load_fs()).exists(tarballCachePath))) { - // The tarball doesn't exists in the offline cache but does in the cache; we import it to the mirror - yield (_fs || _load_fs()).mkdirp(path.dirname(tarballMirrorPath)); - yield (_fs || _load_fs()).copy(tarballCachePath, tarballMirrorPath, _this.reporter); - } - })(); +module.exports = function generate__limit(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; } - - getLocalAvailabilityStatus() { - var _this2 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const tarballMirrorPath = _this2.getTarballMirrorPath(); - const tarballCachePath = _this2.getTarballCachePath(); - - if (tarballMirrorPath != null && (yield (_fs || _load_fs()).exists(tarballMirrorPath))) { - return true; + var $isMax = $keyword == 'maximum', + $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $notOp = $isMax ? '>' : '<'; + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' var exclusive' + ($lvl) + '; if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && typeof ' + ($schemaValueExcl) + ' != \'undefined\') { '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; } - - if (yield (_fs || _load_fs()).exists(tarballCachePath)) { - return true; + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - - return false; - })(); - } - - getTarballCachePath() { - return path.join(this.dest, (_constants || _load_constants()).TARBALL_FILENAME); - } - - getTarballMirrorPath() { - var _url$parse = url.parse(this.reference); - - const pathname = _url$parse.pathname; - - - if (pathname == null) { - return null; + out += ' } '; + } else { + out += ' {} '; } - - // handle scoped packages - const pathParts = pathname.replace(/^\//, '').split(/\//g); - - const packageFilename = pathParts.length >= 2 && pathParts[0][0] === '@' ? `${pathParts[0]}-${pathParts[pathParts.length - 1]}` // scopped - : `${pathParts[pathParts.length - 1]}`; - - return this.config.getOfflineMirrorPath(packageFilename); - } - - createExtractor(resolve, reject, tarballPath) { - const validateStream = new (_crypto || _load_crypto()).HashStream(); - const extractorStream = gunzip(); - const untarStream = tarFs.extract(this.dest, { - strip: 1, - dmode: 0o555, // all dirs should be readable - fmode: 0o444, // all files should be readable - chown: false }); - - extractorStream.pipe(untarStream).on('error', error => { - error.message = `${error.message}${tarballPath ? ` (${tarballPath})` : ''}`; - reject(error); - }).on('finish', () => { - const expectHash = this.hash; - const actualHash = validateStream.getHash(); - if (!expectHash || expectHash === actualHash) { - resolve({ - hash: actualHash - }); + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; } else { - reject(new (_errors || _load_errors()).SecurityError(this.config.reporter.lang('fetchBadHashWithPath', this.remote.reference, expectHash, actualHash))); - } - }); - - return { validateStream, extractorStream }; - } - - fetchFromLocal(override) { - var _this3 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const tarballMirrorPath = _this3.getTarballMirrorPath(); - const tarballCachePath = _this3.getTarballCachePath(); - - const tarballPath = path.resolve(_this3.config.cwd, override || tarballMirrorPath || tarballCachePath); - - if (!tarballPath || !(yield (_fs || _load_fs()).exists(tarballPath))) { - throw new (_errors || _load_errors()).MessageError(_this3.config.reporter.lang('tarballNotInNetworkOrCache', _this3.reference, tarballPath)); - } - - return new Promise(function (resolve, reject) { - var _createExtractor = _this3.createExtractor(resolve, reject, tarballPath); - - const validateStream = _createExtractor.validateStream, - extractorStream = _createExtractor.extractorStream; - - const cachedStream = fs.createReadStream(tarballPath); - - cachedStream.pipe(validateStream).pipe(extractorStream).on('error', function (err) { - reject(new (_errors || _load_errors()).MessageError(_this3.config.reporter.lang('fetchErrorCorrupt', err.message, tarballPath))); - }); - }); - })(); - } - - fetchFromExternal() { - const registry = this.config.registries[this.registry]; - - return registry.request(this.reference, { - headers: { - 'Accept-Encoding': 'gzip', - Accept: 'application/octet-stream' - }, - buffer: true, - process: (req, resolve, reject) => { - const reporter = this.config.reporter; - // should we save this to the offline cache? - - const tarballMirrorPath = this.getTarballMirrorPath(); - const tarballCachePath = this.getTarballCachePath(); - - var _createExtractor2 = this.createExtractor(resolve, reject); - - const validateStream = _createExtractor2.validateStream, - extractorStream = _createExtractor2.extractorStream; - - - const handleRequestError = res => { - if (res.statusCode >= 400) { - const statusDescription = (_http || _load_http()).default.STATUS_CODES[res.statusCode]; - reject(new Error(reporter.lang('requestFailed', `${res.statusCode} ${statusDescription}`))); - } - }; - - req.on('response', handleRequestError); - req.pipe(validateStream); - - if (tarballMirrorPath) { - validateStream.pipe(fs.createWriteStream(tarballMirrorPath)).on('error', reject); - } - - if (tarballCachePath) { - validateStream.pipe(fs.createWriteStream(tarballCachePath)).on('error', reject); - } - - validateStream.pipe(extractorStream).on('error', reject); + out += ' validate.errors = [' + (__err) + ']; return false; '; } - }, this.packageName); + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else if( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ((exclusive' + ($lvl) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ') || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = exclusive' + ($lvl) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + out += ' if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + ' ' + ($notOp); + if ($exclusive) { + out += '='; + } + out += ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') {'; } - - _fetch() { - var _this4 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const urlParse = url.parse(_this4.reference); - - const isFilePath = urlParse.protocol ? urlParse.protocol.match(/^[a-z]:$/i) : urlParse.pathname ? urlParse.pathname.match(/^(?:\.{1,2})?[\\\/]/) : false; - - if (isFilePath) { - return _this4.fetchFromLocal(_this4.reference); + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schema) + '\''; } - - if (yield _this4.getLocalAvailabilityStatus()) { - return _this4.fetchFromLocal(); + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); } else { - return _this4.fetchFromExternal(); + out += '' + ($schema); } - })(); + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; } -} - -exports.default = TarballFetcher; -class LocalTarballFetcher extends TarballFetcher { - _fetch() { - return this.fetchFromLocal(this.reference); + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; } + return out; } -exports.LocalTarballFetcher = LocalTarballFetcher; + /***/ }), -/* 199 */ +/* 241 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.testEngine = testEngine; -exports.checkOne = checkOne; -exports.check = check; - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); -} - -var _map; - -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); -} - -var _misc; - -function _load_misc() { - return _misc = __webpack_require__(10); -} - -var _yarnVersion; - -function _load_yarnVersion() { - return _yarnVersion = __webpack_require__(65); -} - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const invariant = __webpack_require__(5); -const semver = __webpack_require__(27); - -const VERSIONS = Object.assign({}, process.versions, { - yarn: (_yarnVersion || _load_yarnVersion()).version -}); - -function isValid(items, actual) { - let isNotWhitelist = true; - let isBlacklist = false; - - for (const item of items) { - // blacklist - if (item[0] === '!') { - isBlacklist = true; - - if (actual === item.slice(1)) { - return false; +module.exports = function generate__limitItems(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxItems' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxItems') { + out += 'more'; + } else { + out += 'less'; } - // whitelist - } else { - isNotWhitelist = false; - - if (item === actual) { - return true; + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); + } + out += ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } + out += ' } '; + } else { + out += ' {} '; } - - // npm allows blacklists and whitelists to be mixed. Blacklists with - // whitelisted items should be treated as whitelists. - return isBlacklist && isNotWhitelist; + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; } -const aliases = (0, (_map || _load_map()).default)({ - iojs: 'node' }); -const ignore = ['npm', // we'll never satisfy this for obvious reasons -'teleport', // a module bundler used by some modules -'rhino']; +/***/ }), +/* 242 */ +/***/ (function(module, exports, __webpack_require__) { -function testEngine(name, range, versions, looseSemver) { - const actual = versions[name]; - if (!actual) { - return false; - } +"use strict"; - if (!semver.valid(actual, looseSemver)) { - return false; +module.exports = function generate__limitLength(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; } - - if (semver.satisfies(actual, range, looseSemver)) { - return true; + var $op = $keyword == 'maxLength' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } - - if (name === 'node' && semver.gt(actual, '1.0.0', looseSemver)) { - // WARNING: this is a massive hack and is super gross but necessary for compatibility - // some modules have the `engines.node` field set to a caret version below semver major v1 - // eg. ^0.12.0. this is problematic as we enforce engines checks and node is now on version >=1 - // to allow this pattern we transform the node version to fake ones in the minor range 10-13 - const major = semver.major(actual, looseSemver); - const fakes = [`0.10.${major}`, `0.11.${major}`, `0.12.${major}`, `0.13.${major}`]; - for (const actualFake of fakes) { - if (semver.satisfies(actualFake, range, looseSemver)) { - return true; + if (it.opts.unicode === false) { + out += ' ' + ($data) + '.length '; + } else { + out += ' ucs2length(' + ($data) + ') '; + } + out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be '; + if ($keyword == 'maxLength') { + out += 'longer'; + } else { + out += 'shorter'; + } + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + ($schema); } + out += ' characters\' '; } - } - - // incompatible version - return false; -} - -function isValidArch(archs) { - return isValid(archs, process.arch); -} - -function isValidPlatform(platforms) { - return isValid(platforms, process.platform); -} - -function checkOne(info, config, ignoreEngines) { - let didIgnore = false; - let didError = false; - const reporter = config.reporter; - const human = `${info.name}@${info.version}`; - - const pushError = msg => { - const ref = info._reference; - invariant(ref, 'expected package reference'); - - if (ref.optional) { - ref.ignore = true; - ref.incompatible = true; - - reporter.warn(`${human}: ${msg}`); - if (!didIgnore) { - reporter.info(reporter.lang('optionalCompatibilityExcluded', human)); - didIgnore = true; + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); } - } else { - reporter.error(`${human}: ${msg}`); - didError = true; + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - }; - - const invalidPlatform = !config.ignorePlatform && Array.isArray(info.os) && info.os.length > 0 && !isValidPlatform(info.os); - - if (invalidPlatform) { - pushError(reporter.lang('incompatibleOS', process.platform)); - } - - const invalidCpu = !config.ignorePlatform && Array.isArray(info.cpu) && info.cpu.length > 0 && !isValidArch(info.cpu); - - if (invalidCpu) { - pushError(reporter.lang('incompatibleCPU', process.arch)); + out += ' } '; + } else { + out += ' {} '; } - - if (!ignoreEngines && typeof info.engines === 'object') { - for (const entry of (0, (_misc || _load_misc()).entries)(info.engines)) { - let name = entry[0]; - const range = entry[1]; - - if (aliases[name]) { - name = aliases[name]; - } - - if (VERSIONS[name]) { - if (!testEngine(name, range, VERSIONS, config.looseSemver)) { - pushError(reporter.lang('incompatibleEngine', name, range)); - } - } else if (ignore.indexOf(name) < 0) { - reporter.warn(`${human}: ${reporter.lang('invalidEngine', name)}`); - } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } - - if (didError) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('foundIncompatible')); + out += '} '; + if ($breakOnError) { + out += ' else { '; } + return out; } -function check(infos, config, ignoreEngines) { - for (const info of infos) { - checkOne(info, config, ignoreEngines); - } -} /***/ }), -/* 200 */ +/* 243 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -let fetchCache = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dest, fetcher, config) { - var _ref2 = yield config.readPackageMetadata(dest); - - const hash = _ref2.hash, - pkg = _ref2.package; - - yield fetcher.setupMirrorFromCache(); - return { - package: pkg, - hash, - dest, - cached: true - }; - }); - - return function fetchCache(_x, _x2, _x3) { - return _ref.apply(this, arguments); - }; -})(); - -let fetchOne = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (ref, config) { - const dest = config.generateHardModulePath(ref); - - const remote = ref.remote; - - // Mock metedata for symlinked dependencies - if (remote.type === 'link' || remote.type === 'workspace') { - const mockPkg = { _uid: '', name: '', version: '0.0.0' }; - return Promise.resolve({ resolved: null, hash: '', dest, package: mockPkg, cached: false }); - } - - const Fetcher = (_index || _load_index())[remote.type]; - if (!Fetcher) { - throw new (_errors || _load_errors()).MessageError(config.reporter.lang('unknownFetcherFor', remote.type)); - } - - const fetcher = new Fetcher(dest, remote, config); - if (yield config.isValidModuleDest(dest)) { - return fetchCache(dest, fetcher, config); - } - - // remove as the module may be invalid - yield (_fs || _load_fs()).unlink(dest); - - try { - return yield fetcher.fetch({ - name: ref.name, - version: ref.version - }); - } catch (err) { - try { - yield (_fs || _load_fs()).unlink(dest); - } catch (err2) { - // what do? +module.exports = function generate__limitProperties(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $op = $keyword == 'maxProperties' ? '>' : '<'; + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; + } + out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have '; + if ($keyword == 'maxProperties') { + out += 'more'; + } else { + out += 'less'; } - throw err; - } - }); - - return function fetchOne(_x4, _x5) { - return _ref3.apply(this, arguments); - }; -})(); - -let maybeFetchOne = (() => { - var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (ref, config) { - try { - return yield fetchOne(ref, config); - } catch (err) { - if (ref.optional) { - config.reporter.error(err.message); - return null; + out += ' than '; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; } else { - throw err; + out += '' + ($schema); } + out += ' properties\' '; } - }); - - return function maybeFetchOne(_x6, _x7) { - return _ref4.apply(this, arguments); - }; -})(); - -exports.fetch = fetch; - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); -} - -var _index; - -function _load_index() { - return _index = _interopRequireWildcard(__webpack_require__(358)); -} - -var _fs; - -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} - -var _promise; - -function _load_promise() { - return _promise = _interopRequireWildcard(__webpack_require__(64)); -} - -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function fetch(pkgs, config) { - const pkgsPerDest = new Map(); - pkgs = pkgs.filter(pkg => { - const ref = pkg._reference; - if (!ref) { - return false; + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } - const dest = config.generateHardModulePath(ref); - const otherPkg = pkgsPerDest.get(dest); - if (otherPkg) { - config.reporter.warn(config.reporter.lang('multiplePackagesCantUnpackInSameDestination', ref.patterns, dest, otherPkg.patterns)); - return false; + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; } - pkgsPerDest.set(dest, ref); - return true; - }); - const tick = config.reporter.progress(pkgs.length); - - return (_promise || _load_promise()).queue(pkgs, (() => { - var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (pkg) { - const ref = pkg._reference; - if (!ref) { - return pkg; - } - - const res = yield maybeFetchOne(ref, config); - let newPkg; - - if (res) { - newPkg = res.package; - - // update with new remote - // but only if there was a hash previously as the tarball fetcher does not provide a hash. - if (ref.remote.hash) { - ref.remote.hash = res.hash; - } - } - - if (tick) { - tick(); - } - - if (newPkg) { - newPkg._reference = ref; - newPkg._remote = ref.remote; - newPkg.name = pkg.name; - newPkg.fresh = pkg.fresh; - return newPkg; - } - - return pkg; - }); - - return function (_x8) { - return _ref5.apply(this, arguments); - }; - })(), config.networkConcurrency); + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; } + /***/ }), -/* 201 */ +/* 244 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +module.exports = function generate_validate(it, $keyword) { + var out = ''; + var $async = it.schema.$async === true; + if (it.isTop) { + var $top = it.isTop, + $lvl = it.level = 0, + $dataLvl = it.dataLevel = 0, + $data = 'data'; + it.rootId = it.resolve.fullPath(it.root.schema.id); + it.baseId = it.baseId || it.rootId; + if ($async) { + it.async = true; + var $es7 = it.opts.async == 'es7'; + it.yieldAwait = $es7 ? 'await' : 'yield'; + } + delete it.isTop; + it.dataPathArr = [undefined]; + out += ' var validate = '; + if ($async) { + if ($es7) { + out += ' (async function '; + } else { + if (it.opts.async == 'co*') { + out += 'co.wrap'; + } + out += '(function* '; + } + } else { + out += ' (function '; + } + out += ' (data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; var vErrors = null; '; + out += ' var errors = 0; '; + out += ' if (rootData === undefined) rootData = data;'; + } else { + var $lvl = it.level, + $dataLvl = it.dataLevel, + $data = 'data' + ($dataLvl || ''); + if (it.schema.id) it.baseId = it.resolve.url(it.baseId, it.schema.id); + if ($async && !it.async) throw new Error('async schema in sync schema'); + out += ' var errs_' + ($lvl) + ' = errors;'; + } + var $valid = 'valid' + $lvl, + $breakOnError = !it.opts.allErrors, + $closingBraces1 = '', + $closingBraces2 = ''; + var $typeSchema = it.schema.type, + $typeIsArray = Array.isArray($typeSchema); + if ($typeSchema && it.opts.coerceTypes) { + var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); + if ($coerceToTypes) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; + var $dataType = 'dataType' + $lvl, + $coerced = 'coerced' + $lvl; + out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; '; + if (it.opts.coerceTypes == 'array') { + out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; '; + } + out += ' var ' + ($coerced) + ' = undefined; '; + var $bracesCoercion = ''; + var arr1 = $coerceToTypes; + if (arr1) { + var $type, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $type = arr1[$i += 1]; + if ($i) { + out += ' if (' + ($coerced) + ' === undefined) { '; + $bracesCoercion += '}'; + } + if (it.opts.coerceTypes == 'array' && $type != 'array') { + out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } '; + } + if ($type == 'string') { + out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; + } else if ($type == 'number' || $type == 'integer') { + out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; + if ($type == 'integer') { + out += ' && !(' + ($data) + ' % 1)'; + } + out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; + } else if ($type == 'boolean') { + out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; + } else if ($type == 'null') { + out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; + } else if (it.opts.coerceTypes == 'array' && $type == 'array') { + out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; + } + } + } + out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' ' + ($data) + ' = ' + ($coerced) + '; '; + if (!$dataLvl) { + out += 'if (' + ($parentData) + ' !== undefined)'; + } + out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } } '; + } + } + var $refKeywords; + if (it.schema.$ref && ($refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'))) { + if (it.opts.extendRefs == 'fail') { + throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '"'); + } else if (it.opts.extendRefs == 'ignore') { + $refKeywords = false; + console.log('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); + } else if (it.opts.extendRefs !== true) { + console.log('$ref: all keywords used in schema at path "' + it.errSchemaPath + '". It will change in the next major version, see issue #260. Use option { extendRefs: true } to keep current behaviour'); + } + } + if (it.schema.$ref && !$refKeywords) { + out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; + if ($breakOnError) { + out += ' } if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } else { + var arr2 = it.RULES; + if (arr2) { + var $rulesGroup, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $rulesGroup = arr2[i2 += 1]; + if ($shouldUseGroup($rulesGroup)) { + if ($rulesGroup.type) { + out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { '; + } + if (it.opts.useDefaults && !it.compositeRule) { + if ($rulesGroup.type == 'object' && it.schema.properties) { + var $schema = it.schema.properties, + $schemaKeys = Object.keys($schema); + var arr3 = $schemaKeys; + if (arr3) { + var $propertyKey, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $propertyKey = arr3[i3 += 1]; + var $sch = $schema[$propertyKey]; + if ($sch.default !== undefined) { + var $passData = $data + it.util.getProperty($propertyKey); + out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { + var arr4 = it.schema.items; + if (arr4) { + var $sch, $i = -1, + l4 = arr4.length - 1; + while ($i < l4) { + $sch = arr4[$i += 1]; + if ($sch.default !== undefined) { + var $passData = $data + '[' + $i + ']'; + out += ' if (' + ($passData) + ' === undefined) ' + ($passData) + ' = '; + if (it.opts.useDefaults == 'shared') { + out += ' ' + (it.useDefault($sch.default)) + ' '; + } else { + out += ' ' + (JSON.stringify($sch.default)) + ' '; + } + out += '; '; + } + } + } + } + } + var arr5 = $rulesGroup.rules; + if (arr5) { + var $rule, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $rule = arr5[i5 += 1]; + if ($shouldUseRule($rule)) { + out += ' ' + ($rule.code(it, $rule.keyword)) + ' '; + if ($breakOnError) { + $closingBraces1 += '}'; + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces1) + ' '; + $closingBraces1 = ''; + } + if ($rulesGroup.type) { + out += ' } '; + if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { + var $typeChecked = true; + out += ' else { '; + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + } + if ($breakOnError) { + out += ' if (errors === '; + if ($top) { + out += '0'; + } else { + out += 'errs_' + ($lvl); + } + out += ') { '; + $closingBraces2 += '}'; + } + } + } + } + } + if ($typeSchema && !$typeChecked && !$coerceToTypes) { + var $schemaPath = it.schemaPath + '.type', + $errSchemaPath = it.errSchemaPath + '/type', + $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; + out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be '; + if ($typeIsArray) { + out += '' + ($typeSchema.join(",")); + } else { + out += '' + ($typeSchema); + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + } + if ($breakOnError) { + out += ' ' + ($closingBraces2) + ' '; + } + if ($top) { + if ($async) { + out += ' if (errors === 0) return true; '; + out += ' else throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; '; + out += ' return errors === 0; '; + } + out += ' }); return validate;'; + } else { + out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; + } + out = it.util.cleanUpCode(out); + if ($top && $breakOnError) { + out = it.util.cleanUpVarErrors(out, $async); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -var _packageRequest; + function $shouldUseGroup($rulesGroup) { + for (var i = 0; i < $rulesGroup.rules.length; i++) + if ($shouldUseRule($rulesGroup.rules[i])) return true; + } -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); + function $shouldUseRule($rule) { + return it.schema[$rule.keyword] !== undefined || ($rule.keyword == 'properties' && (it.schema.additionalProperties === false || typeof it.schema.additionalProperties == 'object' || (it.schema.patternProperties && Object.keys(it.schema.patternProperties).length) || (it.opts.v5 && it.schema.patternGroups && Object.keys(it.schema.patternGroups).length))); + } + return out; } -var _requestManager; - -function _load_requestManager() { - return _requestManager = _interopRequireDefault(__webpack_require__(209)); -} -var _blockingQueue; +/***/ }), +/* 245 */ +/***/ (function(module, exports, __webpack_require__) { -function _load_blockingQueue() { - return _blockingQueue = _interopRequireDefault(__webpack_require__(84)); -} +"use strict"; -var _wrapper; +module.exports = function () { + return /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PRZcf-nqry=><]/g; +}; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} -var _map; +/***/ }), +/* 246 */ +/***/ (function(module, exports) { -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); -} +// API +module.exports = abort; -var _workspaceLayout; +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); -function _load_workspaceLayout() { - return _workspaceLayout = _interopRequireDefault(__webpack_require__(66)); + // reset leftover jobs + state.jobs = {}; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const invariant = __webpack_require__(5); - -const semver = __webpack_require__(27); - -class PackageResolver { - constructor(config, lockfile) { - this.patternsByPackage = (0, (_map || _load_map()).default)(); - this.fetchingPatterns = (0, (_map || _load_map()).default)(); - this.fetchingQueue = new (_blockingQueue || _load_blockingQueue()).default('resolver fetching'); - this.patterns = (0, (_map || _load_map()).default)(); - this.usedRegistries = new Set(); - this.flat = false; - - this.reporter = config.reporter; - this.lockfile = lockfile; - this.config = config; - this.delayedResolveQueue = []; +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); } +} - // whether the dependency graph will be flattened +/***/ }), +/* 247 */ +/***/ (function(module, exports, __webpack_require__) { - // list of registries that have been used in this resolution +var defer = __webpack_require__(380); +// API +module.exports = async; - // activity monitor +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; + // check if async happened + defer(function() { isAsync = true; }); - // patterns we've already resolved or are in the process of resolving + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} - // TODO +/***/ }), +/* 248 */ +/***/ (function(module, exports, __webpack_require__) { +var async = __webpack_require__(247) + , abort = __webpack_require__(246) + ; - // manages and throttles json api http requests +// API +module.exports = iterate; +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - // list of patterns associated with a package + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } + // clean up jobs + delete state.jobs[key]; - // lockfile instance which we can use to retrieve version info - - - // a map of dependency patterns to packages + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } + // return salvaged results + callback(error, state.results); + }); +} - // reporter instance, abstracts out display logic +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } - // environment specific config methods and options + return aborter; +} - // list of packages need to be resolved later (they found a matching version in the - // resolver, but better matches can still arrive later in the resolve process) +/***/ }), +/* 249 */ +/***/ (function(module, exports) { +// API +module.exports = state; - /** - * TODO description - */ +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; - isNewPattern(pattern) { - return !!this.patterns[pattern].fresh; + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); } - updateManifest(ref, newPkg) { - // inherit fields - const oldPkg = this.patterns[ref.patterns[0]]; - newPkg._reference = ref; - newPkg._remote = ref.remote; - newPkg.name = oldPkg.name; - newPkg.fresh = oldPkg.fresh; + return initState; +} - // update patterns - for (const pattern of ref.patterns) { - this.patterns[pattern] = newPkg; - } - return Promise.resolve(); - } +/***/ }), +/* 250 */ +/***/ (function(module, exports, __webpack_require__) { - updateManifests(newPkgs) { - for (const newPkg of newPkgs) { - if (newPkg._reference) { - for (const pattern of newPkg._reference.patterns) { - this.patterns[pattern] = newPkg; - } - } - } +var abort = __webpack_require__(246) + , async = __webpack_require__(247) + ; - return Promise.resolve(); +// API +module.exports = terminator; + +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; } - /** - * Given a list of patterns, dedupe them to a list of unique patterns. - */ + // fast forward iteration index + this.index = this.size; - dedupePatterns(patterns) { - const deduped = []; - const seen = new Set(); + // abort jobs + abort(this); - for (const pattern of patterns) { - const info = this.getResolvedPattern(pattern); - if (seen.has(info)) { - continue; - } + // send back results we have so far + async(callback)(null, this.results); +} - seen.add(info); - deduped.push(pattern); - } - return deduped; - } +/***/ }), +/* 251 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Get a list of all manifests by topological order. - */ +var iterate = __webpack_require__(248) + , initState = __webpack_require__(249) + , terminator = __webpack_require__(250) + ; - getTopologicalManifests(seedPatterns) { - const pkgs = new Set(); - const skip = new Set(); +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; - const add = seedPatterns => { - for (const pattern of seedPatterns) { - const pkg = this.getStrictResolvedPattern(pattern); - if (skip.has(pkg)) { - continue; - } +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); - const ref = pkg._reference; - invariant(ref, 'expected reference'); - skip.add(pkg); - add(ref.dependencies); - pkgs.add(pkg); - } - }; + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } - add(seedPatterns); + state.index++; - return pkgs; - } + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; + } - /** - * Get a list of all manifests by level sort order. - */ + // done here + callback(null, state.results); + }); - getLevelOrderManifests(seedPatterns) { - const pkgs = new Set(); - const skip = new Set(); + return terminator.bind(state, callback); +} - const add = seedPatterns => { - const refs = []; +/* + * -- Sort methods + */ - for (const pattern of seedPatterns) { - const pkg = this.getStrictResolvedPattern(pattern); - if (skip.has(pkg)) { - continue; - } +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} - const ref = pkg._reference; - invariant(ref, 'expected reference'); +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} - refs.push(ref); - skip.add(pkg); - pkgs.add(pkg); - } - for (const ref of refs) { - add(ref.dependencies); - } - }; +/***/ }), +/* 252 */ +/***/ (function(module, exports, __webpack_require__) { - add(seedPatterns); +"use strict"; - return pkgs; - } - /** - * Get a list of all package names in the depenency graph. - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = { + 'upgrade-interactive': 'upgradeInteractive', + 'generate-lock-entry': 'generateLockEntry' +}; - getAllDependencyNamesByLevelOrder(seedPatterns) { - const names = new Set(); - for (const _ref of this.getLevelOrderManifests(seedPatterns)) { - const name = _ref.name; +/***/ }), +/* 253 */ +/***/ (function(module, exports, __webpack_require__) { - names.add(name); - } - return names; - } +"use strict"; - /** - * Retrieve all the package info stored for this package name. - */ - getAllInfoForPackageName(name) { - const infos = []; - const seen = new Set(); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.clean = exports.noArguments = exports.requireLockfile = undefined; - for (const pattern of this.patternsByPackage[name]) { - const info = this.patterns[pattern]; - if (seen.has(info)) { - continue; - } +var _asyncToGenerator2; - seen.add(info); - infos.push(info); - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - return infos; - } +let clean = exports.clean = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) { + const loc = path.join(config.cwd, (_constants || _load_constants()).CLEAN_FILENAME); + const file = yield (_fs || _load_fs()).readFile(loc); + const lines = file.split('\n'); + const filters = (0, (_filter || _load_filter()).ignoreLinesToRegex)(lines); - /** - * Get a flat list of all package info. - */ + let removedFiles = 0; + let removedSize = 0; - getManifests() { - const infos = []; - const seen = new Set(); + // build list of possible module folders + const locs = new Set(); + if (config.modulesFolder) { + locs.add(config.modulesFolder); + } + for (const name of (_index || _load_index()).registryNames) { + const registry = config.registries[name]; + locs.add(path.join(config.cwd, registry.folder)); + } - for (const pattern in this.patterns) { - const info = this.patterns[pattern]; - if (seen.has(info)) { + for (const folder of locs) { + if (!(yield (_fs || _load_fs()).exists(folder))) { continue; } - infos.push(info); - seen.add(info); - } + const spinner = reporter.activity(); + const files = yield (_fs || _load_fs()).walk(folder); - return infos; - } + var _sortFilter = (0, (_filter || _load_filter()).sortFilter)(files, filters); - /** - * replace pattern in resolver, e.g. `name` is replaced with `name@^1.0.1` - */ - replacePattern(pattern, newPattern) { - const pkg = this.getResolvedPattern(pattern); - invariant(pkg, `missing package ${pattern}`); - const ref = pkg._reference; - invariant(ref, 'expected package reference'); - ref.patterns = [newPattern]; - this.addPattern(newPattern, pkg); - this.removePattern(pattern); - } + const ignoreFiles = _sortFilter.ignoreFiles; - /** - * Make all versions of this package resolve to it. - */ + spinner.end(); - collapseAllVersionsOfPackage(name, version) { - const patterns = this.dedupePatterns(this.patternsByPackage[name]); - const human = `${name}@${version}`; + const tick = reporter.progress(ignoreFiles.size); + // TODO make sure `main` field of all modules isn't ignored - // get manifest that matches the version we're collapsing too - let collapseToReference; - let collapseToManifest; - let collapseToPattern; - for (const pattern of patterns) { - const _manifest = this.patterns[pattern]; - if (_manifest.version === version) { - collapseToReference = _manifest._reference; - collapseToManifest = _manifest; - collapseToPattern = pattern; - break; + for (const file of ignoreFiles) { + const loc = path.join(folder, file); + const stat = yield (_fs || _load_fs()).lstat(loc); + removedSize += stat.size; + removedFiles++; + } + + for (const file of ignoreFiles) { + const loc = path.join(folder, file); + yield (_fs || _load_fs()).unlink(loc); + tick(); } } - invariant(collapseToReference && collapseToManifest && collapseToPattern, `Couldn't find package manifest for ${human}`); + return { removedFiles, removedSize }; + }); - for (const pattern of patterns) { - // don't touch the pattern we're collapsing to - if (pattern === collapseToPattern) { - continue; - } + return function clean(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); - // remove this pattern - const ref = this.getStrictResolvedPattern(pattern)._reference; - invariant(ref, 'expected package reference'); - const refPatterns = ref.patterns.slice(); - ref.prune(); +let runInit = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (cwd, reporter) { + reporter.step(1, 1, reporter.lang('cleanCreatingFile', (_constants || _load_constants()).CLEAN_FILENAME)); + const cleanLoc = path.join(cwd, (_constants || _load_constants()).CLEAN_FILENAME); + yield (_fs || _load_fs()).writeFile(cleanLoc, `${DEFAULT_FILTER}\n`, { flag: 'wx' }); + reporter.info(reporter.lang('cleanCreatedFile', (_constants || _load_constants()).CLEAN_FILENAME)); + }); - // add pattern to the manifest we're collapsing to - for (const pattern of refPatterns) { - collapseToReference.addPattern(pattern, collapseToManifest); - } - } + return function runInit(_x3, _x4) { + return _ref2.apply(this, arguments); + }; +})(); - return collapseToPattern; - } +let runAutoClean = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter) { + reporter.step(1, 1, reporter.lang('cleaning')); - /** - * TODO description - */ + var _ref4 = yield clean(config, reporter); - addPattern(pattern, info) { - this.patterns[pattern] = info; + const removedFiles = _ref4.removedFiles, + removedSize = _ref4.removedSize; - const byName = this.patternsByPackage[info.name] = this.patternsByPackage[info.name] || []; - byName.push(pattern); - } + reporter.info(reporter.lang('cleanRemovedFiles', removedFiles)); + reporter.info(reporter.lang('cleanSavedSize', Number((removedSize / 1024 / 1024).toFixed(2)))); + }); - /** - * TODO description - */ + return function runAutoClean(_x5, _x6) { + return _ref3.apply(this, arguments); + }; +})(); - removePattern(pattern) { - const pkg = this.patterns[pattern]; - if (!pkg) { - return; - } +let checkForCleanFile = (() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (cwd) { + const cleanLoc = path.join(cwd, (_constants || _load_constants()).CLEAN_FILENAME); + const exists = yield (_fs || _load_fs()).exists(cleanLoc); + return exists; + }); - const byName = this.patternsByPackage[pkg.name]; - if (!byName) { - return; + return function checkForCleanFile(_x7) { + return _ref5.apply(this, arguments); + }; +})(); + +let run = exports.run = (() => { + var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const cleanFileExists = yield checkForCleanFile(config.cwd); + + if (flags.init && cleanFileExists) { + reporter.info(reporter.lang('cleanAlreadyExists', (_constants || _load_constants()).CLEAN_FILENAME)); + } else if (flags.init) { + yield runInit(config.cwd, reporter); + } else if (flags.force && cleanFileExists) { + yield runAutoClean(config, reporter); + } else if (cleanFileExists) { + reporter.info(reporter.lang('cleanRequiresForce', (_constants || _load_constants()).CLEAN_FILENAME)); + } else { + reporter.info(reporter.lang('cleanDoesNotExist', (_constants || _load_constants()).CLEAN_FILENAME)); } + }); - byName.splice(byName.indexOf(pattern), 1); - delete this.patterns[pattern]; - } + return function run(_x8, _x9, _x10, _x11) { + return _ref6.apply(this, arguments); + }; +})(); - /** - * TODO description - */ +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; - getResolvedPattern(pattern) { - return this.patterns[pattern]; - } +var _index; - /** - * TODO description - */ +function _load_index() { + return _index = __webpack_require__(34); +} - getStrictResolvedPattern(pattern) { - const manifest = this.getResolvedPattern(pattern); - invariant(manifest, 'expected manifest'); - return manifest; - } +var _filter; - /** - * TODO description - */ +function _load_filter() { + return _filter = __webpack_require__(273); +} - getExactVersionMatch(name, version) { - const patterns = this.patternsByPackage[name]; - if (!patterns) { - return null; - } +var _constants; - for (const pattern of patterns) { - const info = this.getStrictResolvedPattern(pattern); - if (info.version === version) { - return info; - } - } +function _load_constants() { + return _constants = __webpack_require__(6); +} - return null; - } +var _fs; - /** - * Get the manifest of the highest known version that satisfies a package range - */ +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - getHighestRangeVersionMatch(name, range) { - const patterns = this.patternsByPackage[name]; - if (!patterns) { - return null; - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - const versionNumbers = []; - const resolvedPatterns = patterns.map(pattern => { - const info = this.getStrictResolvedPattern(pattern); - versionNumbers.push(info.version); - - return info; - }); - - const maxValidRange = semver.maxSatisfying(versionNumbers, range); - if (!maxValidRange) { - return null; - } - - const indexOfmaxValidRange = versionNumbers.indexOf(maxValidRange); - const maxValidRangeManifest = resolvedPatterns[indexOfmaxValidRange]; - - return maxValidRangeManifest; - } - - /** - * TODO description - */ - - find(req) { - var _this = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const fetchKey = `${req.registry}:${req.pattern}`; - if (_this.fetchingPatterns[fetchKey]) { - return; - } else { - _this.fetchingPatterns[fetchKey] = true; - } - - if (_this.activity) { - _this.activity.tick(req.pattern); - } - - const lockfileEntry = _this.lockfile.getLocked(req.pattern); - let fresh = false; - if (lockfileEntry) { - var _PackageRequest$norma = (_packageRequest || _load_packageRequest()).default.normalizePattern(req.pattern); - - const range = _PackageRequest$norma.range, - hasVersion = _PackageRequest$norma.hasVersion; - // lockfileEntry is incorrect, remove it from lockfile cache and consider the pattern as new - - if (semver.validRange(range) && semver.valid(lockfileEntry.version) && !semver.satisfies(lockfileEntry.version, range) && !(_packageRequest || _load_packageRequest()).default.getExoticResolver(range) && hasVersion) { - _this.reporter.warn(_this.reporter.lang('incorrectLockfileEntry', req.pattern)); - _this.removePattern(req.pattern); - _this.lockfile.removePattern(req.pattern); - fresh = true; - } - } else { - fresh = true; - } - - const request = new (_packageRequest || _load_packageRequest()).default(req, _this); - yield request.find({ fresh, frozen: _this.frozen }); - })(); - } - - /** - * TODO description - */ - - init(deps) { - var _this2 = this; - - var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { isFlat: false, isFrozen: false, workspaceLayout: undefined }; - - let isFlat = _ref2.isFlat, - isFrozen = _ref2.isFrozen, - workspaceLayout = _ref2.workspaceLayout; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this2.flat = Boolean(isFlat); - _this2.frozen = Boolean(isFrozen); - _this2.workspaceLayout = workspaceLayout; - const activity = _this2.activity = _this2.reporter.activity(); - yield Promise.all(deps.map(function (req) { - return _this2.find(req); - })); - - // all required package versions have been discovered, so now packages that - // resolved to existing versions can be resolved to their best available version - _this2.resolvePackagesWithExistingVersions(); - - activity.end(); - _this2.activity = null; - })(); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - /** - * Called by the package requester for packages that this resolver already had - * a matching version for. Delay the resolve, because better matches can still be - * discovered. - */ +const path = __webpack_require__(0); - reportPackageWithExistingVersion(req, info) { - this.delayedResolveQueue.push({ req, info }); - } +const requireLockfile = exports.requireLockfile = true; +const noArguments = exports.noArguments = true; - /** - * Executes the resolve to existing versions for packages after the find process, - * when all versions that are going to be used have been discovered. - */ +const DEFAULT_FILTER = ` +# test directories +__tests__ +test +tests +powered-test - resolvePackagesWithExistingVersions() { - for (const _ref3 of this.delayedResolveQueue) { - const req = _ref3.req, - info = _ref3.info; +# asset directories +docs +doc +website +images +assets - req.resolveToExistingVersion(info); - } - } -} -exports.default = PackageResolver; +# examples +example +examples -/***/ }), -/* 202 */ -/***/ (function(module, exports, __webpack_require__) { +# code coverage directories +coverage +.nyc_output -"use strict"; +# build scripts +Makefile +Gulpfile.js +Gruntfile.js +# configs +.tern-project +.gitattributes +.editorconfig +.*ignore +.eslintrc +.jshintrc +.flowconfig +.documentup.json +.yarn-metadata.json +.*.yml +*.yml -Object.defineProperty(exports, "__esModule", { - value: true -}); -function formatFunction() { - for (var _len = arguments.length, strs = Array(_len), _key = 0; _key < _len; _key++) { - strs[_key] = arguments[_key]; - } +# misc +*.gz +*.md +`.trim(); - return strs.join(' '); +function setFlags(commander) { + commander.usage('autoclean [flags]'); + commander.option('-I, --init', `Create "${(_constants || _load_constants()).CLEAN_FILENAME}" file with the default entries.`); + commander.option('-F, --force', `Run autoclean using the existing "${(_constants || _load_constants()).CLEAN_FILENAME}" file.`); } -const defaultFormatter = exports.defaultFormatter = { - bold: formatFunction, - dim: formatFunction, - italic: formatFunction, - underline: formatFunction, - inverse: formatFunction, - strikethrough: formatFunction, - black: formatFunction, - red: formatFunction, - green: formatFunction, - yellow: formatFunction, - blue: formatFunction, - magenta: formatFunction, - cyan: formatFunction, - white: formatFunction, - gray: formatFunction, - grey: formatFunction, - stripColor: formatFunction -}; - -/***/ }), -/* 203 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.en = undefined; - -var _en; - -function _load_en() { - return _en = _interopRequireDefault(__webpack_require__(373)); +function hasWrapper(commander) { + return true; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -exports.en = (_en || _load_en()).default; - /***/ }), -/* 204 */ +/* 254 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -56633,347 +59506,459 @@ exports.en = (_en || _load_en()).default; Object.defineProperty(exports, "__esModule", { value: true }); +exports.run = exports.verifyTreeCheck = exports.noArguments = exports.requireLockfile = undefined; var _slicedToArray2; function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _exoticResolver; - -function _load_exoticResolver() { - return _exoticResolver = _interopRequireDefault(__webpack_require__(44)); -} +let verifyTreeCheck = exports.verifyTreeCheck = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + let errCount = 0; + function reportError(msg) { + for (var _len = arguments.length, vars = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + vars[_key - 1] = arguments[_key]; + } -var _misc; + reporter.error(reporter.lang(msg, ...vars)); + errCount++; + } + // check all dependencies recursively without relying on internal resolver + const registryName = 'yarn'; + const registry = config.registries[registryName]; + const rootManifest = yield config.readManifest(registry.cwd, registryName); -function _load_misc() { - return _misc = _interopRequireWildcard(__webpack_require__(10)); -} + const dependenciesToCheckVersion = []; + if (rootManifest.dependencies) { + for (const name in rootManifest.dependencies) { + const version = rootManifest.dependencies[name]; + // skip linked dependencies + const isLinkedDepencency = /^link:/i.test(version) || /^file:/i.test(version) && config.linkFileDependencies; + if (isLinkedDepencency) { + continue; + } + dependenciesToCheckVersion.push({ + name, + originalKey: name, + parentCwd: registry.cwd, + version + }); + } + } + if (rootManifest.devDependencies && !config.production) { + for (const name in rootManifest.devDependencies) { + const version = rootManifest.devDependencies[name]; + // skip linked dependencies + const isLinkedDepencency = /^link:/i.test(version) || /^file:/i.test(version) && config.linkFileDependencies; + if (isLinkedDepencency) { + continue; + } + dependenciesToCheckVersion.push({ + name, + originalKey: name, + parentCwd: registry.cwd, + version + }); + } + } -var _fs; + const locationsVisited = new Set(); + while (dependenciesToCheckVersion.length) { + const dep = dependenciesToCheckVersion.shift(); + const manifestLoc = path.join(dep.parentCwd, registry.folder, dep.name); + if (locationsVisited.has(manifestLoc + `@${dep.version}`)) { + continue; + } + locationsVisited.add(manifestLoc + `@${dep.version}`); + if (!(yield (_fs || _load_fs()).exists(manifestLoc))) { + reportError('packageNotInstalled', `${dep.originalKey}`); + continue; + } + if (!(yield (_fs || _load_fs()).exists(path.join(manifestLoc, 'package.json')))) { + continue; + } + const pkg = yield config.readManifest(manifestLoc, registryName); + if (semver.validRange(dep.version, config.looseSemver) && !semver.satisfies(pkg.version, dep.version, config.looseSemver)) { + reportError('packageWrongVersion', dep.originalKey, dep.version, pkg.version); + continue; + } + const dependencies = pkg.dependencies; + if (dependencies) { + for (const subdep in dependencies) { + const subDepPath = path.join(manifestLoc, registry.folder, subdep); + let found = false; + const relative = path.relative(registry.cwd, subDepPath); + const locations = path.normalize(relative).split(registry.folder + path.sep).filter(function (dir) { + return !!dir; + }); + locations.pop(); + while (locations.length >= 0) { + let possiblePath; + if (locations.length > 0) { + possiblePath = path.join(registry.cwd, registry.folder, locations.join(path.sep + registry.folder + path.sep)); + } else { + possiblePath = registry.cwd; + } + if (yield (_fs || _load_fs()).exists(path.join(possiblePath, registry.folder, subdep))) { + dependenciesToCheckVersion.push({ + name: subdep, + originalKey: `${dep.originalKey}#${subdep}`, + parentCwd: possiblePath, + version: dependencies[subdep] + }); + found = true; + break; + } + if (!locations.length) { + break; + } + locations.pop(); + } + if (!found) { + reportError('packageNotInstalled', `${dep.originalKey}#${subdep}`); + } + } + } + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + if (errCount > 0) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount)); + } else { + reporter.success(reporter.lang('folderInSync')); + } + }); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return function verifyTreeCheck(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +let integrityHashCheck = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + let errCount = 0; + function reportError(msg) { + for (var _len2 = arguments.length, vars = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + vars[_key2 - 1] = arguments[_key2]; + } -const invariant = __webpack_require__(5); + reporter.error(reporter.lang(msg, ...vars)); + errCount++; + } + const integrityChecker = new (_integrityChecker || _load_integrityChecker()).default(config); -const path = __webpack_require__(1); -const uuid = __webpack_require__(58); + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.cwd); + const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); -class FileResolver extends (_exoticResolver || _load_exoticResolver()).default { - constructor(request, fragment) { - super(request, fragment); - this.loc = (_misc || _load_misc()).removePrefix(fragment, 'file:'); - } + // get patterns that are installed when running `yarn install` - resolve() { - var _this = this; + var _ref3 = yield install.fetchRequestFromCwd(); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let loc = _this.loc; - if (!path.isAbsolute(loc)) { - loc = path.join(_this.config.cwd, loc); - } + const patterns = _ref3.patterns, + workspaceLayout = _ref3.workspaceLayout; - if (_this.config.linkFileDependencies) { - const registry = 'npm'; - const manifest = { _uid: '', name: '', version: '0.0.0', _registry: registry }; - manifest._remote = { - type: 'link', - registry, - hash: null, - reference: loc - }; - manifest._uid = manifest.version; - return manifest; - } - if (!(yield (_fs || _load_fs()).exists(loc))) { - throw new (_errors || _load_errors()).MessageError(_this.reporter.lang('doesntExist', loc)); - } - const manifest = yield (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - try { - return yield _this.config.readManifest(loc, _this.registry); - } catch (e) { - if (e.code === 'ENOENT') { - return { - // This is just the default, it can be overridden with key of dependencies - name: path.dirname(loc), - version: '0.0.0', - _uid: '0.0.0', - _registry: 'npm' - }; - } + const match = yield integrityChecker.check(patterns, lockfile.cache, flags, workspaceLayout); + for (const pattern of match.missingPatterns) { + reportError('lockfileNotContainPattern', pattern); + } + if (match.integrityFileMissing) { + reportError('noIntegrityFile'); + } + if (match.integrityMatches === false) { + reporter.warn(reporter.lang((_integrityChecker2 || _load_integrityChecker2()).integrityErrors[match.integrityError])); + reportError('integrityCheckFailed'); + } - throw e; - } - })(); - const registry = manifest._registry; - invariant(registry, 'expected registry'); + if (errCount > 0) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount)); + } else { + reporter.success(reporter.lang('folderInSync')); + } + }); - manifest._remote = { - type: 'copy', - registry, - hash: `${uuid.v4()}-${new Date().getTime()}`, - reference: loc - }; + return function integrityHashCheck(_x5, _x6, _x7, _x8) { + return _ref2.apply(this, arguments); + }; +})(); - manifest._uid = manifest.version; +let run = exports.run = (() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (flags.verifyTree) { + yield verifyTreeCheck(config, reporter, flags, args); + return; + } else if (flags.integrity) { + yield integrityHashCheck(config, reporter, flags, args); + return; + } - // Normalize relative paths; if anything changes, make a copy of the manifest - const dependencies = _this.normalizeDependencyPaths(manifest.dependencies, loc); - const optionalDependencies = _this.normalizeDependencyPaths(manifest.optionalDependencies, loc); + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.cwd); + const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); - if (dependencies !== manifest.dependencies || optionalDependencies !== manifest.optionalDependencies) { - const _manifest = Object.assign({}, manifest); - if (dependencies != null) { - _manifest.dependencies = dependencies; - } - if (optionalDependencies != null) { - _manifest.optionalDependencies = optionalDependencies; + function humaniseLocation(loc) { + const relative = path.relative(path.join(config.cwd, 'node_modules'), loc); + const normalized = path.normalize(relative).split(path.sep); + return normalized.filter(p => p !== 'node_modules').reduce((result, part) => { + const length = result.length; + if (length && result[length - 1].startsWith('@') && result[length - 1].indexOf(path.sep) === -1) { + result[length - 1] += path.sep + part; + } else { + result.push(part); } - return _manifest; - } else { - return manifest; + return result; + }, []); + } + + let warningCount = 0; + let errCount = 0; + function reportError(msg) { + for (var _len3 = arguments.length, vars = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + vars[_key3 - 1] = arguments[_key3]; } - })(); - } - normalizeDependencyPaths(section, loc) { - if (section == null) { - return section; + reporter.error(reporter.lang(msg, ...vars)); + errCount++; } - let temp = section; + // get patterns that are installed when running `yarn install` + + var _ref5 = yield install.hydrate(); - for (const _ref2 of (_misc || _load_misc()).entries(section)) { - var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2); + const rawPatterns = _ref5.patterns, + workspaceLayout = _ref5.workspaceLayout; - const k = _ref3[0]; - const v = _ref3[1]; + const patterns = yield install.flatten(rawPatterns); - if (typeof v === 'string' && v.startsWith('file:') && !path.isAbsolute(v)) { - if (temp === section) { - temp = Object.assign({}, section); - } - temp[k] = `file:${path.relative(this.config.cwd, path.join(loc, (_misc || _load_misc()).removePrefix(v, 'file:')))}`; + // check if patterns exist in lockfile + for (const pattern of patterns) { + if (!lockfile.getLocked(pattern) && (!workspaceLayout || !workspaceLayout.getManifestByPattern(pattern))) { + reportError('lockfileNotContainPattern', pattern); } } - return temp; - } -} -exports.default = FileResolver; -FileResolver.protocol = 'file'; + const bundledDeps = {}; + // check if any of the node_modules are out of sync + const res = yield install.linker.getFlatHoistedTree(patterns); + for (const _ref6 of res) { + var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2); -/***/ }), -/* 205 */ -/***/ (function(module, exports, __webpack_require__) { + const loc = _ref7[0]; + var _ref7$ = _ref7[1]; + const originalKey = _ref7$.originalKey; + const pkg = _ref7$.pkg; + const ignore = _ref7$.ignore; -"use strict"; + if (ignore) { + continue; + } + const parts = humaniseLocation(loc); -Object.defineProperty(exports, "__esModule", { - value: true -}); + // grey out hoisted portions of key + let human = originalKey; + const hoistedParts = parts.slice(); + const hoistedKey = parts.join('#'); + if (human !== hoistedKey) { + const humanParts = human.split('#'); -var _npmResolver; + for (let i = 0; i < humanParts.length; i++) { + const humanPart = humanParts[i]; -function _load_npmResolver() { - return _npmResolver = _interopRequireDefault(__webpack_require__(126)); -} + if (hoistedParts[0] === humanPart) { + hoistedParts.shift(); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (i < humanParts.length - 1) { + humanParts[i] += '#'; + } + } else { + humanParts[i] = reporter.format.dim(`${humanPart}#`); + } + } -class YarnResolver extends (_npmResolver || _load_npmResolver()).default {} -exports.default = YarnResolver; + human = humanParts.join(''); + } -/***/ }), -/* 206 */ -/***/ (function(module, exports, __webpack_require__) { + // skip unnecessary checks for linked dependencies + const remoteType = pkg._reference.remote.type; + const isLinkedDepencency = remoteType === 'link' || remoteType === 'workspace' || remoteType === 'file' && config.linkFileDependencies; + if (isLinkedDepencency) { + continue; + } -"use strict"; + if (!(yield (_fs || _load_fs()).exists(loc))) { + if (pkg._reference.optional) { + reporter.warn(reporter.lang('optionalDepNotInstalled', human)); + } else { + reportError('packageNotInstalled', human); + } + continue; + } + const pkgLoc = path.join(loc, 'package.json'); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.sortFilter = sortFilter; -exports.matchesFilter = matchesFilter; -exports.ignoreLinesToRegex = ignoreLinesToRegex; -exports.filterOverridenGitignores = filterOverridenGitignores; + if (yield (_fs || _load_fs()).exists(pkgLoc)) { + const packageJson = yield config.readJson(pkgLoc); + packageJson.version = semver.clean(packageJson.version); -var _misc; + if (pkg.version !== packageJson.version) { + // node_modules contains wrong version + reportError('packageWrongVersion', human, pkg.version, packageJson.version); + } -function _load_misc() { - return _misc = __webpack_require__(10); -} + const deps = Object.assign({}, packageJson.dependencies, packageJson.peerDependencies); + bundledDeps[packageJson.name] = packageJson.bundledDependencies || []; -const mm = __webpack_require__(243); -const path = __webpack_require__(1); + for (const name in deps) { + const range = deps[name]; + if (!semver.validRange(range, config.looseSemver)) { + continue; // exotic + } -const WHITESPACE_RE = /^\s+$/; + const subHuman = `${human}#${name}@${range}`; -function sortFilter(files, filters) { - let keepFiles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set(); - let possibleKeepFiles = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Set(); - let ignoreFiles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : new Set(); + // find the package that this will resolve to, factoring in hoisting + const possibles = []; + let depLoc; + for (let i = parts.length; i >= 0; i--) { + const myParts = parts.slice(0, i).concat(name); - for (const file of files) { - let keep = false; + // build package.json location for this position + const myDepPkgLoc = path.join(config.cwd, 'node_modules', myParts.join(`${path.sep}node_modules${path.sep}`)); - // always keep a file if a ! pattern matches it - for (const filter of filters) { - if (filter.isNegation && matchesFilter(filter, file.basename, file.relative)) { - keep = true; - break; - } - } + possibles.push(myDepPkgLoc); + } + while (possibles.length) { + const myDepPkgLoc = possibles.shift(); + if (yield (_fs || _load_fs()).exists(myDepPkgLoc)) { + depLoc = myDepPkgLoc; + break; + } + } + if (!depLoc) { + // we'll hit the module not install error above when this module is hit + continue; + } - // - if (keep) { - keepFiles.add(file.relative); - continue; - } + const depPkgLoc = path.join(depLoc, 'package.json'); - // otherwise don't keep it if a pattern matches it - keep = true; - for (const filter of filters) { - if (!filter.isNegation && matchesFilter(filter, file.basename, file.relative)) { - keep = false; - break; + if (yield (_fs || _load_fs()).exists(depPkgLoc)) { + const depPkg = yield config.readJson(depPkgLoc); + const foundHuman = `${humaniseLocation(path.dirname(depPkgLoc)).join('#')}@${depPkg.version}`; + if (!semver.satisfies(depPkg.version, range, config.looseSemver)) { + // module isn't correct semver + reportError('packageDontSatisfy', subHuman, foundHuman); + continue; + } + + // check for modules above us that this could be deduped to + for (const loc of possibles) { + const locPkg = path.join(loc, 'package.json'); + + if (!(yield (_fs || _load_fs()).exists(locPkg))) { + continue; + } + + const packageJson = yield config.readJson(locPkg); + const packagePath = originalKey.split('#'); + const rootDep = packagePath[0]; + const packageName = packagePath[1] || packageJson.name; + + const bundledDep = bundledDeps[rootDep] && bundledDeps[rootDep].indexOf(packageName) !== -1; + if (!bundledDep && (packageJson.version === depPkg.version || semver.satisfies(packageJson.version, range, config.looseSemver) && semver.gt(packageJson.version, depPkg.version, config.looseSemver))) { + reporter.warn(reporter.lang('couldBeDeduped', subHuman, packageJson.version, `${humaniseLocation(path.dirname(locPkg)).join('#')}@${packageJson.version}`)); + warningCount++; + } + break; + } + } + } } } - if (keep) { - possibleKeepFiles.add(file.relative); + if (warningCount > 1) { + reporter.info(reporter.lang('foundWarnings', warningCount)); + } + + if (errCount > 0) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('foundErrors', errCount)); } else { - ignoreFiles.add(file.relative); + reporter.success(reporter.lang('folderInSync')); } - } + }); - // exclude file - for (const file of possibleKeepFiles) { - const parts = path.dirname(file).split(path.sep); + return function run(_x9, _x10, _x11, _x12) { + return _ref4.apply(this, arguments); + }; +})(); - while (parts.length) { - const folder = parts.join(path.sep); - if (ignoreFiles.has(folder)) { - ignoreFiles.add(file); - break; - } - parts.pop(); - } - } +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; - // - for (const file of possibleKeepFiles) { - if (!ignoreFiles.has(file)) { - keepFiles.add(file); - } - } +var _errors; - // - for (const file of keepFiles) { - const parts = path.dirname(file).split(path.sep); +function _load_errors() { + return _errors = __webpack_require__(3); +} - while (parts.length) { - // deregister this folder from being ignored, any files inside - // will still be marked as ignored - ignoreFiles.delete(parts.join(path.sep)); - parts.pop(); - } - } +var _integrityChecker; - return { ignoreFiles, keepFiles }; +function _load_integrityChecker() { + return _integrityChecker = _interopRequireDefault(__webpack_require__(158)); } -function matchesFilter(filter, basename, loc) { - if (filter.base && filter.base !== '.') { - loc = path.relative(filter.base, loc); - } - return filter.regex.test(loc) || filter.regex.test(`/${loc}`) || filter.regex.test(basename) || mm.isMatch(loc, filter.pattern); +var _integrityChecker2; + +function _load_integrityChecker2() { + return _integrityChecker2 = __webpack_require__(158); } -function ignoreLinesToRegex(lines) { - let base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.'; +var _lockfile; - return lines - // create regex - .map(line => { - // remove empty lines, comments, etc - if (line === '' || line === '!' || line[0] === '#' || WHITESPACE_RE.test(line)) { - return null; - } +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} - let pattern = line; - let isNegation = false; +var _fs; - // hide the fact that it's a negation from minimatch since we'll handle this specifically - // ourselves - if (pattern[0] === '!') { - isNegation = true; - pattern = pattern.slice(1); - } +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - // remove trailing slash - pattern = (0, (_misc || _load_misc()).removeSuffix)(pattern, '/'); +var _install; - const regex = mm.makeRe(pattern.trim(), { nocase: true }); +function _load_install() { + return _install = __webpack_require__(31); +} - if (regex) { - return { - base, - isNegation, - pattern, - regex - }; - } else { - return null; - } - }).filter(Boolean); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const semver = __webpack_require__(22); + +const path = __webpack_require__(0); + +const requireLockfile = exports.requireLockfile = false; +const noArguments = exports.noArguments = true; + +function hasWrapper(commander) { + return true; } -function filterOverridenGitignores(files) { - const IGNORE_FILENAMES = ['.yarnignore', '.npmignore', '.gitignore']; - const GITIGNORE_NAME = IGNORE_FILENAMES[2]; - return files.filter(file => IGNORE_FILENAMES.includes(file.basename)).reduce((acc, file) => { - if (file.basename !== GITIGNORE_NAME) { - return [...acc, file]; - } else { - //don't include .gitignore if .npmignore or .yarnignore are present - const dir = path.dirname(file.absolute); - const higherPriorityIgnoreFilePaths = [`${dir}/${IGNORE_FILENAMES[0]}`, `${dir}/${IGNORE_FILENAMES[1]}`]; - const hasHigherPriorityFiles = files.find(file => higherPriorityIgnoreFilePaths.includes(file.absolute)); - if (!hasHigherPriorityFiles) { - return [...acc, file]; - } - } - return acc; - }, []); +function setFlags(commander) { + commander.option('--integrity'); + commander.option('--verify-tree'); } /***/ }), -/* 207 */ +/* 255 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -56982,81 +59967,99 @@ function filterOverridenGitignores(files) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.isOffline = isOffline; -const os = __webpack_require__(113); +exports.run = exports.getRegistryFolder = undefined; -const IGNORE_INTERFACES = ['lo0', 'awdl0', 'bridge0']; -const LOCAL_IPS = ['127.0.0.1', '::1']; +var _asyncToGenerator2; -function isOffline() { - let interfaces; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - try { - interfaces = os.networkInterfaces(); - } catch (e) { - // As of October 2016, Windows Subsystem for Linux (WSL) does not support - // the os.networkInterfaces() call and throws instead. For this platform, - // assume we are online. - if (e.syscall === 'uv_interface_addresses') { - return false; - } else { - throw e; +let getRegistryFolder = exports.getRegistryFolder = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, name) { + if (config.modulesFolder) { + return config.modulesFolder; } - } - for (const name in interfaces) { - if (IGNORE_INTERFACES.indexOf(name) >= 0) { - continue; - } + const src = path.join(config.linkFolder, name); - const addrs = interfaces[name]; - for (const addr of addrs) { - if (LOCAL_IPS.indexOf(addr.address) < 0) { - // found a possible remote ip - return false; - } - } - } + var _ref2 = yield config.readManifest(src); - return true; -} + const _registry = _ref2._registry; -/***/ }), -/* 208 */ -/***/ (function(module, exports, __webpack_require__) { + invariant(_registry, 'expected registry'); -"use strict"; + const registryFolder = config.registries[_registry].folder; + return path.join(config.cwd, registryFolder); + }); + return function getRegistryFolder(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getPosixPath = getPosixPath; -exports.expandPath = expandPath; -const userHome = __webpack_require__(86).default; +let run = exports.run = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (args.length) { + for (const name of args) { + const src = path.join(config.linkFolder, name); -function getPosixPath(path) { - return path.replace(/\\/g, '/'); -} + if (yield (_fs || _load_fs()).exists(src)) { + const folder = yield getRegistryFolder(config, name); + const dest = path.join(folder, name); -function expandPath(path) { - if (process.platform !== 'win32') { - path = path.replace(/^\s*~(?=$|\/|\\)/, userHome); - } + yield (_fs || _load_fs()).unlink(dest); + yield (_fs || _load_fs()).mkdirp(path.dirname(dest)); + yield (_fs || _load_fs()).symlink(src, dest); + reporter.success(reporter.lang('linkUsing', name)); + } else { + throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name)); + } + } + } else { + // add cwd module to the global registry + const manifest = yield config.readRootManifest(); + const name = manifest.name; + if (!name) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownPackageName')); + } - return path; -} + const linkLoc = path.join(config.linkFolder, name); + if (yield (_fs || _load_fs()).exists(linkLoc)) { + reporter.warn(reporter.lang('linkCollision', name)); + } else { + yield (_fs || _load_fs()).mkdirp(path.dirname(linkLoc)); + yield (_fs || _load_fs()).symlink(config.cwd, linkLoc); -/***/ }), -/* 209 */ -/***/ (function(module, exports, __webpack_require__) { + // If there is a `bin` defined in the package.json, + // link each bin to the global bin + if (manifest.bin) { + const globalBinFolder = yield (0, (_global || _load_global()).getBinFolder)(config, flags); + for (const binName in manifest.bin) { + const binSrc = manifest.bin[binName]; + const binSrcLoc = path.join(linkLoc, binSrc); + const binDestLoc = path.join(globalBinFolder, binName); + if (yield (_fs || _load_fs()).exists(binDestLoc)) { + reporter.warn(reporter.lang('binLinkCollision', binName)); + } else { + yield (_fs || _load_fs()).symlink(binSrcLoc, binDestLoc); + } + } + } -"use strict"; + reporter.success(reporter.lang('linkRegistered', name)); + reporter.info(reporter.lang('linkRegisteredMessage', name)); + } + } + }); + return function run(_x3, _x4, _x5, _x6) { + return _ref3.apply(this, arguments); + }; +})(); -Object.defineProperty(exports, "__esModule", { - value: true -}); +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; var _errors; @@ -57064,19268 +60067,20413 @@ function _load_errors() { return _errors = __webpack_require__(3); } -var _blockingQueue; +var _fs; -function _load_blockingQueue() { - return _blockingQueue = _interopRequireDefault(__webpack_require__(84)); +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } -var _constants; +var _global; -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); +function _load_global() { + return _global = __webpack_require__(92); } -var _network; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -function _load_network() { - return _network = _interopRequireWildcard(__webpack_require__(207)); -} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var _map; +const invariant = __webpack_require__(7); -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); +const path = __webpack_require__(0); + +function hasWrapper(commander, args) { + return true; } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function setFlags(commander) {} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), +/* 256 */ +/***/ (function(module, exports, __webpack_require__) { -const RequestCaptureHar = __webpack_require__(587); -const invariant = __webpack_require__(5); -const url = __webpack_require__(11); -const fs = __webpack_require__(6); +"use strict"; -const successHosts = (0, (_map || _load_map()).default)(); -const controlOffline = (_network || _load_network()).isOffline(); -class RequestManager { - constructor(reporter) { - this.offlineNoRequests = false; - this._requestCaptureHar = null; - this._requestModule = null; - this.offlineQueue = []; - this.captureHar = false; - this.httpsProxy = null; - this.ca = null; - this.httpProxy = null; - this.strictSSL = true; - this.userAgent = ''; - this.reporter = reporter; - this.running = 0; - this.queue = []; - this.cache = {}; - this.max = (_constants || _load_constants()).NETWORK_CONCURRENCY; - this.maxRetryAttempts = 5; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.buildTree = exports.requireLockfile = undefined; - setOptions(opts) { - if (opts.userAgent != null) { - this.userAgent = opts.userAgent; - } +var _slicedToArray2; - if (opts.offline != null) { - this.offlineNoRequests = opts.offline; - } +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} - if (opts.captureHar != null) { - this.captureHar = opts.captureHar; - } +var _asyncToGenerator2; - if (opts.httpProxy != null) { - this.httpProxy = opts.httpProxy; - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - if (opts.httpsProxy != null) { - this.httpsProxy = opts.httpsProxy; - } +let buildTree = exports.buildTree = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (resolver, linker, patterns, opts, onlyFresh, ignoreHoisted) { + const treesByKey = {}; + const trees = []; + const flatTree = yield linker.getFlatHoistedTree(patterns); - if (opts.strictSSL !== null && typeof opts.strictSSL !== 'undefined') { - this.strictSSL = opts.strictSSL; - } + // If using workspaces, filter out the virtual manifest + const workspaceLayout = resolver.workspaceLayout; - if (opts.ca != null && opts.ca.length > 0) { - this.ca = opts.ca; - } + const hoisted = workspaceLayout && workspaceLayout.virtualManifestName ? flatTree.filter(function (_ref2) { + var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1); - if (opts.networkConcurrency != null) { - this.max = opts.networkConcurrency; - } + let key = _ref3[0]; + return key.indexOf(workspaceLayout.virtualManifestName) === -1; + }) : flatTree; - if (opts.networkTimeout != null) { - this.timeout = opts.networkTimeout; - } + const hoistedByKey = {}; + for (const _ref4 of hoisted) { + var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2); - if (opts.maxRetryAttempts != null) { - this.maxRetryAttempts = opts.maxRetryAttempts; - } + const key = _ref5[0]; + const info = _ref5[1]; - if (opts.cafile != null && opts.cafile != '') { - // The CA bundle file can contain one or more certificates with comments/text between each PEM block. - // tls.connect wants an array of certificates without any comments/text, so we need to split the string - // and strip out any text in between the certificates - try { - const bundle = fs.readFileSync(opts.cafile).toString(); - const hasPemPrefix = block => block.startsWith('-----BEGIN '); - // opts.cafile overrides opts.ca, this matches with npm behavior - this.ca = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix); - } catch (err) { - this.reporter.error(`Could not open cafile: ${err.message}`); - } + hoistedByKey[key] = info; } - if (opts.cert != null) { - this.cert = opts.cert; - } + // build initial trees + for (const _ref6 of hoisted) { + var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2); - if (opts.key != null) { - this.key = opts.key; - } - } + const info = _ref7[1]; - /** - * Lazy load `request` since it is exceptionally expensive to load and is - * often not needed at all. - */ + const ref = info.pkg._reference; + const hint = null; + const parent = getParent(info.key, treesByKey); + const children = []; + let depth = 0; + let color = 'bold'; + invariant(ref, 'expected reference'); - _getRequestModule() { - if (!this._requestModule) { - const request = __webpack_require__(588); - if (this.captureHar) { - this._requestCaptureHar = new RequestCaptureHar(request); - this._requestModule = this._requestCaptureHar.request.bind(this._requestCaptureHar); + if (onlyFresh) { + let isFresh = false; + for (const pattern of ref.patterns) { + if (resolver.isNewPattern(pattern)) { + isFresh = true; + break; + } + } + if (!isFresh) { + continue; + } + } + + if (info.originalKey !== info.key || opts.reqDepth === 0) { + // was hoisted + color = null; + } + // check parent to obtain next depth + if (parent && parent.depth > 0) { + depth = parent.depth + 1; } else { - this._requestModule = request; + depth = 0; } - } - return this._requestModule; - } - /** - * Queue up a request. - */ + const topLevel = opts.reqDepth === 0 && !parent; + const showAll = opts.reqDepth === -1; + const nextDepthIsValid = depth + 1 <= Number(opts.reqDepth); - request(params) { - if (this.offlineNoRequests) { - return Promise.reject(new (_errors || _load_errors()).MessageError(this.reporter.lang('cantRequestOffline', params.url))); + if (topLevel || nextDepthIsValid || showAll) { + treesByKey[info.key] = { + name: `${info.pkg.name}@${info.pkg.version}`, + children, + hint, + color, + depth + }; + } + + // add in dummy children for hoisted dependencies + const nextChildDepthIsValid = depth + 1 < Number(opts.reqDepth); + invariant(ref, 'expected reference'); + if (!ignoreHoisted && nextDepthIsValid || showAll) { + for (const pattern of resolver.dedupePatterns(ref.dependencies)) { + const pkg = resolver.getStrictResolvedPattern(pattern); + + if (!hoistedByKey[`${info.key}#${pkg.name}`] && (nextChildDepthIsValid || showAll)) { + children.push({ + name: pattern, + color: 'dim', + shadow: true + }); + } + } + } } - const cached = this.cache[params.url]; - if (cached) { - return cached; + // add children + for (const _ref8 of hoisted) { + var _ref9 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref8, 2); + + const info = _ref9[1]; + + const tree = treesByKey[info.key]; + const parent = getParent(info.key, treesByKey); + if (!tree) { + continue; + } + + if (info.key.split('#').length === 1) { + trees.push(tree); + continue; + } + + if (parent) { + parent.children.push(tree); + } } - params.method = params.method || 'GET'; - params.forever = true; - params.retryAttempts = 0; - params.strictSSL = this.strictSSL; - params.headers = Object.assign({ - 'User-Agent': this.userAgent - }, params.headers); + return { trees, count: buildCount(trees) }; + }); - const promise = new Promise((resolve, reject) => { - this.queue.push({ params, reject, resolve }); - this.shiftQueue(); + return function buildTree(_x, _x2, _x3, _x4, _x5, _x6) { + return _ref.apply(this, arguments); + }; +})(); + +let run = exports.run = (() => { + var _ref10 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder, reporter); + const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); + + var _ref11 = yield install.fetchRequestFromCwd(); + + const depRequests = _ref11.requests, + patterns = _ref11.patterns, + manifest = _ref11.manifest, + workspaceLayout = _ref11.workspaceLayout; + + yield install.resolver.init(depRequests, { + isFlat: install.flags.flat, + isFrozen: install.flags.frozenLockfile, + workspaceLayout }); - // we can't cache a request with a processor - if (!params.process) { - this.cache[params.url] = promise; + let activePatterns = []; + if ((0, (_constants || _load_constants()).isProduction)()) { + const devDeps = getDevDeps(manifest); + activePatterns = patterns.filter(function (pattern) { + return !devDeps.has(pattern); + }); + } else { + activePatterns = patterns; } - return promise; - } + const opts = { + reqDepth: getReqDepth(flags.depth) + }; - /** - * Clear the request cache. This is important as we cache all HTTP requests so you'll - * want to do this as soon as you can. - */ + var _ref12 = yield buildTree(install.resolver, install.linker, activePatterns, opts); - clearCache() { - this.cache = {}; - if (this._requestCaptureHar != null) { - this._requestCaptureHar.clear(); + let trees = _ref12.trees; + + + if (args.length) { + trees = trees.filter(function (tree) { + return filterTree(tree, args); + }); } - } - /** - * Check if an error is possibly due to lost or poor network connectivity. - */ + reporter.tree('list', trees); + }); - isPossibleOfflineError(err) { - const code = err.code, - hostname = err.hostname; + return function run(_x7, _x8, _x9, _x10) { + return _ref10.apply(this, arguments); + }; +})(); - if (!code) { - return false; - } +exports.getParent = getParent; +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; +exports.getReqDepth = getReqDepth; +exports.filterTree = filterTree; +exports.getDevDeps = getDevDeps; - // network was previously online but now we're offline - const possibleOfflineChange = !controlOffline && !(_network || _load_network()).isOffline(); - if (code === 'ENOTFOUND' && possibleOfflineChange) { - // can't resolve a domain - return true; - } +var _install; - // used to be able to resolve this domain! something is wrong - if (code === 'ENOTFOUND' && hostname && successHosts[hostname]) { - // can't resolve this domain but we've successfully resolved it before - return true; - } +function _load_install() { + return _install = __webpack_require__(31); +} - // network was previously offline and we can't resolve the domain - if (code === 'ENOTFOUND' && controlOffline) { - return true; - } +var _lockfile; - // connection was reset or dropped - if (code === 'ECONNRESET') { - return true; - } +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} - // TCP timeout - if (code === 'ESOCKETTIMEDOUT') { - return true; - } +var _constants; - return false; +function _load_constants() { + return _constants = __webpack_require__(6); +} + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const invariant = __webpack_require__(7); +const micromatch = __webpack_require__(219); + +const requireLockfile = exports.requireLockfile = true; + +function buildCount(trees) { + if (!trees || !trees.length) { + return 0; } - /** - * Queue up request arguments to be retried. Start a network connectivity timer if there - * isn't already one. - */ + let count = 0; - queueForOffline(opts) { - if (!this.offlineQueue.length) { - this.reporter.warn(this.reporter.lang('offlineRetrying')); - this.initOfflineRetry(); + for (const tree of trees) { + if (tree.shadow) { + continue; } - this.offlineQueue.push(opts); + count++; + count += buildCount(tree.children); } - /** - * Begin timers to retry failed requests when we possibly establish network connectivity - * again. - */ + return count; +} - initOfflineRetry() { - setTimeout(() => { - const queue = this.offlineQueue; - this.offlineQueue = []; - for (const opts of queue) { - this.execute(opts); - } - }, 3000); +function getParent(key, treesByKey) { + const parentKey = key.split('#').slice(0, -1).join('#'); + return treesByKey[parentKey]; +} + +function hasWrapper(commander, args) { + return true; +} + +function setFlags(commander) { + commander.option('--depth [depth]', 'Limit the depth of the shown dependencies'); +} + +function getReqDepth(inputDepth) { + return inputDepth && /^\d+$/.test(inputDepth) ? Number(inputDepth) : -1; +} + +function filterTree(tree, filters) { + if (tree.children) { + tree.children = tree.children.filter(child => filterTree(child, filters)); } - /** - * Execute a request. - */ + const notDim = tree.color !== 'dim'; + const hasChildren = tree.children == null ? false : tree.children.length > 0; + const name = tree.name.slice(0, tree.name.lastIndexOf('@')); + const found = micromatch.any(name, filters); - execute(opts) { - const params = opts.params; - const reporter = this.reporter; + return notDim && (found || hasChildren); +} +function getDevDeps(manifest) { + return new Set(Object.keys(manifest.devDependencies).map(key => `${key}@${manifest.devDependencies[key]}`)); +} - const buildNext = fn => data => { - fn(data); - this.running--; - this.shiftQueue(); - }; +/***/ }), +/* 257 */ +/***/ (function(module, exports, __webpack_require__) { - const resolve = buildNext(opts.resolve); +"use strict"; - const rejectNext = buildNext(opts.reject); - const reject = function (err) { - err.message = `${params.url}: ${err.message}`; - rejectNext(err); - }; - let calledOnError = false; - const onError = err => { - if (calledOnError) { - return; - } - calledOnError = true; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.requireLockfile = undefined; - const attempts = params.retryAttempts || 0; - if (attempts < this.maxRetryAttempts - 1 && this.isPossibleOfflineError(err)) { - params.retryAttempts = attempts + 1; - if (typeof params.cleanup === 'function') { - params.cleanup(); - } - this.queueForOffline(opts); - } else { - reject(err); - } - }; +var _extends2; - if (!params.process) { - const parts = url.parse(params.url); +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); +} - params.callback = (err, res, body) => { - if (err) { - onError(err); - return; - } +var _slicedToArray2; - successHosts[parts.hostname] = true; +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} - this.reporter.verbose(this.reporter.lang('verboseRequestFinish', params.url, res.statusCode)); +var _asyncToGenerator2; - if (body && typeof body.error === 'string') { - reject(new Error(body.error)); - return; - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - if (res.statusCode === 403) { - const errMsg = body && body.message || reporter.lang('requestError', params.url, res.statusCode); - reject(new Error(errMsg)); - } else { - if (res.statusCode === 400 || res.statusCode === 404 || res.statusCode === 401) { - body = false; +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (!args.length) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('tooFewArguments', 1)); + } + + const totalSteps = args.length + 1; + let step = 0; + + // load manifests + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.cwd); + const rootManifests = yield config.getRootManifests(); + const manifests = []; + + for (const name of args) { + reporter.step(++step, totalSteps, `Removing module ${name}`); + + let found = false; + + for (const registryName of Object.keys((_index || _load_index()).registries)) { + const registry = config.registries[registryName]; + const object = rootManifests[registryName].object; + + for (const type of (_constants || _load_constants()).DEPENDENCY_TYPES) { + const deps = object[type]; + if (deps && deps[name]) { + found = true; + delete deps[name]; } - resolve(body); } - }; - } - if (params.buffer) { - params.encoding = null; - } + const possibleManifestLoc = path.join(config.cwd, registry.folder, name); + if (yield (_fs || _load_fs()).exists(possibleManifestLoc)) { + manifests.push([possibleManifestLoc, yield config.readManifest(possibleManifestLoc, registryName)]); + } + } - let proxy = this.httpProxy; - if (params.url.startsWith('https:')) { - proxy = this.httpsProxy || proxy; - } - if (proxy) { - params.proxy = proxy; + if (!found) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('moduleNotInManifest')); + } } - if (this.ca != null) { - params.ca = this.ca; - } + // save manifests + yield config.saveRootManifests(rootManifests); - if (this.cert != null) { - params.cert = this.cert; - } + // run hooks - npm runs these one after another + for (const action of ['preuninstall', 'uninstall', 'postuninstall']) { + for (const _ref2 of manifests) { + var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1); - if (this.key != null) { - params.key = this.key; - } + const loc = _ref3[0]; - if (this.timeout != null) { - params.timeout = this.timeout; + yield config.executeLifecycleScript(action, loc); + } } - const request = this._getRequestModule(); - const req = request(params); - this.reporter.verbose(this.reporter.lang('verboseRequestStart', params.method, params.url)); + // reinstall so we can get the updated lockfile + reporter.step(++step, totalSteps, reporter.lang('uninstallRegenerate')); + const reinstall = new (_install || _load_install()).Install((0, (_extends2 || _load_extends()).default)({ force: true }, flags), config, new (_index2 || _load_index2()).NoopReporter(), lockfile); + yield reinstall.init(); - req.on('error', onError); + // + reporter.success(reporter.lang('uninstalledPackages')); + }); - const queue = params.queue; - if (queue) { - req.on('data', queue.stillActive.bind(queue)); - } + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); - if (params.process) { - params.process(req, resolve, reject); - } - } +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; - /** - * Remove an item from the queue. Create it's request options and execute it. - */ +var _lockfile; - shiftQueue() { - if (this.running >= this.max || !this.queue.length) { - return; - } +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} - const opts = this.queue.shift(); +var _index; - this.running++; - this.execute(opts); - } +function _load_index() { + return _index = __webpack_require__(34); +} - saveHar(filename) { - if (!this.captureHar) { - throw new Error(this.reporter.lang('requestManagerNotSetupHAR')); - } - // No request may have occurred at all. - this._getRequestModule(); - invariant(this._requestCaptureHar != null, 'request-capture-har not setup'); - this._requestCaptureHar.saveHar(filename); - } +var _install; + +function _load_install() { + return _install = __webpack_require__(31); +} + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); +} + +var _index2; + +function _load_index2() { + return _index2 = __webpack_require__(153); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} + +var _constants; + +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const path = __webpack_require__(0); + +const requireLockfile = exports.requireLockfile = true; + +function setFlags(commander) {} + +function hasWrapper(commander, args) { + return true; } -exports.default = RequestManager; /***/ }), -/* 210 */ +/* 258 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var crypto_hash_sha512 = __webpack_require__(110).lowlevel.crypto_hash; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.examples = exports.hasWrapper = exports.setFlags = exports.run = exports.getName = undefined; -/* - * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a - * result, it retains the original copyright and license. The two files are - * under slightly different (but compatible) licenses, and are here combined in - * one file. - * - * Credit for the actual porting work goes to: - * Devi Mandiri <me@devi.web.id> - */ +var _asyncToGenerator2; -/* - * The Blowfish portions are under the following license: - * - * Blowfish block cipher for OpenBSD - * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de> - * All rights reserved. - * - * Implementation advice by David Mazieres <dm@lcs.mit.edu>. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} -/* - * The bcrypt_pbkdf portions are under the following license: - * - * Copyright (c) 2013 Ted Unangst <tedu@openbsd.org> - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ +let getName = exports.getName = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args, config) { + let name = args.shift(); -/* - * Performance improvements (Javascript-specific): - * - * Copyright 2016, Joyent Inc - * Author: Alex Wilson <alex.wilson@joyent.com> - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ + if (!name) { + const pkg = yield config.readRootManifest(); + name = pkg.name; + } -// Ported from OpenBSD bcrypt_pbkdf.c v1.9 + if (name) { + if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) { + throw new (_errors || _load_errors()).MessageError(config.reporter.lang('invalidPackageName')); + } -var BLF_J = 0; + return (_npmRegistry || _load_npmRegistry()).default.escapeName(name); + } else { + throw new (_errors || _load_errors()).MessageError(config.reporter.lang('unknownPackageName')); + } + }); -var Blowfish = function() { - this.S = [ - new Uint32Array([ - 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, - 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, - 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, - 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, - 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, - 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, - 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, - 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, - 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, - 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, - 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, - 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, - 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, - 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, - 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, - 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, - 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, - 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, - 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, - 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, - 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, - 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, - 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, - 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, - 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, - 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, - 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, - 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, - 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, - 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, - 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, - 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, - 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, - 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, - 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, - 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, - 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, - 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, - 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, - 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, - 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, - 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, - 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, - 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, - 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, - 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, - 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, - 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, - 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, - 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, - 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, - 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, - 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, - 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, - 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, - 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, - 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, - 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, - 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, - 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, - 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, - 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, - 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, - 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), - new Uint32Array([ - 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, - 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, - 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, - 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, - 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, - 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, - 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, - 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, - 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, - 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, - 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, - 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, - 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, - 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, - 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, - 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, - 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, - 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, - 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, - 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, - 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, - 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, - 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, - 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, - 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, - 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, - 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, - 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, - 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, - 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, - 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, - 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, - 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, - 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, - 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, - 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, - 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, - 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, - 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, - 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, - 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, - 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, - 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, - 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, - 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, - 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, - 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, - 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, - 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, - 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, - 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, - 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, - 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, - 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, - 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, - 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, - 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, - 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, - 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, - 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, - 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, - 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, - 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, - 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), - new Uint32Array([ - 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, - 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, - 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, - 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, - 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, - 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, - 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, - 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, - 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, - 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, - 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, - 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, - 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, - 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, - 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, - 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, - 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, - 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, - 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, - 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, - 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, - 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, - 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, - 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, - 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, - 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, - 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, - 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, - 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, - 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, - 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, - 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, - 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, - 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, - 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, - 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, - 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, - 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, - 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, - 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, - 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, - 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, - 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, - 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, - 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, - 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, - 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, - 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, - 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, - 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, - 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, - 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, - 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, - 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, - 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, - 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, - 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, - 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, - 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, - 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, - 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, - 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, - 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, - 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), - new Uint32Array([ - 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, - 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, - 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, - 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, - 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, - 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, - 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, - 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, - 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, - 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, - 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, - 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, - 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, - 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, - 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, - 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, - 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, - 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, - 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, - 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, - 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, - 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, - 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, - 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, - 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, - 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, - 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, - 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, - 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, - 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, - 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, - 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, - 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, - 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, - 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, - 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, - 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, - 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, - 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, - 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, - 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, - 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, - 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, - 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, - 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, - 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, - 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, - 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, - 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, - 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, - 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, - 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, - 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, - 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, - 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, - 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, - 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, - 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, - 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, - 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, - 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, - 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, - 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, - 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) - ]; - this.P = new Uint32Array([ - 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, - 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, - 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, - 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, - 0x9216d5d9, 0x8979fb1b]); -}; + return function getName(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); -function F(S, x8, i) { - return (((S[0][x8[i+3]] + - S[1][x8[i+2]]) ^ - S[2][x8[i+1]]) + - S[3][x8[i]]); -}; +let list = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const name = yield getName(args, config); -Blowfish.prototype.encipher = function(x, x8) { - if (x8 === undefined) { - x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - } - x[0] ^= this.P[0]; - for (var i = 1; i < 16; i += 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[17]; - x[1] = t; -}; + reporter.step(1, 3, reporter.lang('loggingIn')); + const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); -Blowfish.prototype.decipher = function(x) { - var x8 = new Uint8Array(x.buffer); - if (x.byteOffset !== 0) - x8 = x8.subarray(x.byteOffset); - x[0] ^= this.P[17]; - for (var i = 16; i > 0; i -= 2) { - x[1] ^= F(this.S, x8, 0) ^ this.P[i]; - x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; - } - var t = x[0]; - x[0] = x[1] ^ this.P[0]; - x[1] = t; -}; + reporter.step(2, 3, reporter.lang('gettingTags')); + const tags = yield config.registries.npm.request(`-/package/${name}/dist-tags`); -function stream2word(data, databytes){ - var i, temp = 0; - for (i = 0; i < 4; i++, BLF_J++) { - if (BLF_J >= databytes) BLF_J = 0; - temp = (temp << 8) | data[BLF_J]; - } - return temp; -}; + if (tags) { + reporter.info(`Package ${name}`); + for (const name in tags) { + reporter.info(`${name}: ${tags[name]}`); + } + } -Blowfish.prototype.expand0state = function(key, keybytes) { - var d = new Uint32Array(2), i, k; - var d8 = new Uint8Array(d.buffer); + reporter.step(3, 3, reporter.lang('revokingToken')); + yield revoke(); - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } - BLF_J = 0; + if (!tags) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('packageNotFoundRegistry', name, 'npm')); + } + }); - for (i = 0; i < 18; i += 2) { - this.encipher(d, d8); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } + return function list(_x3, _x4, _x5, _x6) { + return _ref2.apply(this, arguments); + }; +})(); - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - this.encipher(d, d8); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; +let remove = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (args.length !== 2) { + return false; } - } -}; -Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { - var d = new Uint32Array(2), i, k; + const name = yield getName(args, config); + const tag = args.shift(); - for (i = 0, BLF_J = 0; i < 18; i++) { - this.P[i] ^= stream2word(key, keybytes); - } + reporter.step(1, 3, reporter.lang('loggingIn')); + const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); - for (i = 0, BLF_J = 0; i < 18; i += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.P[i] = d[0]; - this.P[i+1] = d[1]; - } + reporter.step(2, 3, reporter.lang('deletingTags')); + const result = yield config.registries.npm.request(`-/package/${name}/dist-tags/${encodeURI(tag)}`, { + method: 'DELETE' + }); - for (i = 0; i < 4; i++) { - for (k = 0; k < 256; k += 2) { - d[0] ^= stream2word(data, databytes); - d[1] ^= stream2word(data, databytes); - this.encipher(d); - this.S[i][k] = d[0]; - this.S[i][k+1] = d[1]; + if (result === false) { + reporter.error(reporter.lang('deletedTagFail')); + } else { + reporter.success(reporter.lang('deletedTag')); } - } - BLF_J = 0; -}; -Blowfish.prototype.enc = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.encipher(data.subarray(i*2)); - } -}; + reporter.step(3, 3, reporter.lang('revokingToken')); + yield revoke(); -Blowfish.prototype.dec = function(data, blocks) { - for (var i = 0; i < blocks; i++) { - this.decipher(data.subarray(i*2)); - } -}; + if (result === false) { + throw new Error(); + } else { + return true; + } + }); -var BCRYPT_BLOCKS = 8, - BCRYPT_HASHSIZE = 32; + return function remove(_x7, _x8, _x9, _x10) { + return _ref3.apply(this, arguments); + }; +})(); -function bcrypt_hash(sha2pass, sha2salt, out) { - var state = new Blowfish(), - cdata = new Uint32Array(BCRYPT_BLOCKS), i, - ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, - 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, - 105,116,101]); //"OxychromaticBlowfishSwatDynamite" +var _buildSubCommands2; - state.expandstate(sha2salt, 64, sha2pass, 64); - for (i = 0; i < 64; i++) { - state.expand0state(sha2salt, 64); - state.expand0state(sha2pass, 64); - } +function _load_buildSubCommands() { + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); +} - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = stream2word(ciphertext, ciphertext.byteLength); - for (i = 0; i < 64; i++) - state.enc(cdata, cdata.byteLength / 8); +var _login; - for (i = 0; i < BCRYPT_BLOCKS; i++) { - out[4*i+3] = cdata[i] >>> 24; - out[4*i+2] = cdata[i] >>> 16; - out[4*i+1] = cdata[i] >>> 8; - out[4*i+0] = cdata[i]; - } -}; +function _load_login() { + return _login = __webpack_require__(93); +} -function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { - var sha2pass = new Uint8Array(64), - sha2salt = new Uint8Array(64), - out = new Uint8Array(BCRYPT_HASHSIZE), - tmpout = new Uint8Array(BCRYPT_HASHSIZE), - countsalt = new Uint8Array(saltlen+4), - i, j, amt, stride, dest, count, - origkeylen = keylen; +var _npmRegistry; - if (rounds < 1) - return -1; - if (passlen === 0 || saltlen === 0 || keylen === 0 || - keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) - return -1; +function _load_npmRegistry() { + return _npmRegistry = _interopRequireDefault(__webpack_require__(52)); +} - stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); - amt = Math.floor((keylen + stride - 1) / stride); +var _errors; - for (i = 0; i < saltlen; i++) - countsalt[i] = salt[i]; +function _load_errors() { + return _errors = __webpack_require__(3); +} - crypto_hash_sha512(sha2pass, pass, passlen); +var _normalizePattern2; - for (count = 1; keylen > 0; count++) { - countsalt[saltlen+0] = count >>> 24; - countsalt[saltlen+1] = count >>> 16; - countsalt[saltlen+2] = count >>> 8; - countsalt[saltlen+3] = count; +function _load_normalizePattern() { + return _normalizePattern2 = __webpack_require__(30); +} - crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (i = out.byteLength; i--;) - out[i] = tmpout[i]; +var _validate; - for (i = 1; i < rounds; i++) { - crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); - bcrypt_hash(sha2pass, sha2salt, tmpout); - for (j = 0; j < out.byteLength; j++) - out[j] ^= tmpout[j]; - } +function _load_validate() { + return _validate = __webpack_require__(98); +} - amt = Math.min(amt, keylen); - for (i = 0; i < amt; i++) { - dest = i * stride + (count - 1); - if (dest >= origkeylen) - break; - key[dest] = out[i]; - } - keylen -= i; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return 0; -}; +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('tag', { + add(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (args.length !== 2) { + return false; + } -module.exports = { - BLOCKS: BCRYPT_BLOCKS, - HASHSIZE: BCRYPT_HASHSIZE, - hash: bcrypt_hash, - pbkdf: bcrypt_pbkdf -}; + var _normalizePattern = (0, (_normalizePattern2 || _load_normalizePattern()).normalizePattern)(args.shift()); + + const name = _normalizePattern.name, + range = _normalizePattern.range, + hasVersion = _normalizePattern.hasVersion; + + if (!hasVersion) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('requiredVersionInRange')); + } + if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName')); + } + + const tag = args.shift(); + + reporter.step(1, 3, reporter.lang('loggingIn')); + const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); + + reporter.step(2, 3, reporter.lang('creatingTag', tag, range)); + const result = yield config.registries.npm.request(`-/package/${(_npmRegistry || _load_npmRegistry()).default.escapeName(name)}/dist-tags/${encodeURI(tag)}`, { + method: 'PUT', + body: range + }); + + if (result != null && result.ok) { + reporter.success(reporter.lang('createdTag')); + } else { + reporter.error(reporter.lang('createdTagFail')); + } + + reporter.step(3, 3, reporter.lang('revokingToken')); + yield revoke(); + + if (result != null && result.ok) { + return true; + } else { + throw new Error(); + } + })(); + }, + + rm(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + reporter.warn(`\`yarn tag rm\` is deprecated. Please use \`yarn tag remove\`.`); + yield remove(config, reporter, flags, args); + })(); + }, + + remove(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield remove(config, reporter, flags, args); + })(); + }, + + ls(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + reporter.warn(`\`yarn tag ls\` is deprecated. Please use \`yarn tag list\`.`); + yield list(config, reporter, flags, args); + })(); + }, + + list(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield list(config, reporter, flags, args); + })(); + } +}, ['add <pkg>@<version> [<tag>]', 'remove <pkg> <tag>', 'list [<pkg>]']); +const run = _buildSubCommands.run, + setFlags = _buildSubCommands.setFlags, + hasWrapper = _buildSubCommands.hasWrapper, + examples = _buildSubCommands.examples; +exports.run = run; +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; +exports.examples = examples; /***/ }), -/* 211 */ +/* 259 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const restoreCursor = __webpack_require__(598); -let hidden = false; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.requireLockfile = undefined; -exports.show = stream => { - const s = stream || process.stderr; +var _asyncToGenerator2; - if (!s.isTTY) { - return; - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - hidden = false; - s.write('\u001b[?25h'); -}; +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const outdatedFieldName = flags.latest ? 'latest' : 'wanted'; + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder); -exports.hide = stream => { - const s = stream || process.stderr; + const deps = yield (0, (_upgrade || _load_upgrade()).getOutdated)(config, reporter, flags, lockfile, args); - if (!s.isTTY) { - return; - } + if (deps.length === 0) { + reporter.success(reporter.lang('allDependenciesUpToDate')); + return; + } - restoreCursor(); - hidden = true; - s.write('\u001b[?25l'); -}; + const maxLengthArr = { + name: 'name'.length, + current: 'from'.length, + range: 'latest'.length, + [outdatedFieldName]: 'to'.length + }; -exports.toggle = (force, stream) => { - if (force !== undefined) { - hidden = force; - } + const keysWithDynamicLength = ['name', 'current', outdatedFieldName]; - if (hidden) { - exports.show(stream); - } else { - exports.hide(stream); - } -}; + if (!flags.latest) { + maxLengthArr.range = 'range'.length; + keysWithDynamicLength.push('range'); + } + deps.forEach(function (dep) { + return keysWithDynamicLength.forEach(function (key) { + maxLengthArr[key] = Math.max(maxLengthArr[key], dep[key].length); + }); + }); -/***/ }), -/* 212 */ -/***/ (function(module, exports) { + // Depends on maxLengthArr + const addPadding = function (dep) { + return function (key) { + return `${dep[key]}${' '.repeat(maxLengthArr[key] - dep[key].length)}`; + }; + }; + const headerPadding = function (header, key) { + return `${reporter.format.bold.underline(header)}${' '.repeat(maxLengthArr[key] - header.length)}`; + }; + const colorizeName = function (from, to) { + return reporter.format[(0, (_colorForVersions || _load_colorForVersions()).default)(from, to)]; + }; -/** - * slice() reference. - */ + const getNameFromHint = function (hint) { + return hint ? `${hint}Dependencies` : 'dependencies'; + }; -var slice = Array.prototype.slice; + const makeRow = function (dep) { + const padding = addPadding(dep); + const name = colorizeName(dep.current, dep[outdatedFieldName])(padding('name')); + const current = reporter.format.blue(padding('current')); + const latest = (0, (_colorizeDiff || _load_colorizeDiff()).default)(dep.current, padding(outdatedFieldName), reporter); + const url = reporter.format.cyan(dep.url); + const range = reporter.format.blue(flags.latest ? 'latest' : padding('range')); + return `${name} ${range} ${current} ⯠${latest} ${url}`; + }; -/** - * Expose `co`. - */ + const makeHeaderRow = function () { + const name = headerPadding('name', 'name'); + const range = headerPadding('range', 'range'); + const from = headerPadding('from', 'current'); + const to = headerPadding('to', outdatedFieldName); + const url = reporter.format.bold.underline('url'); + return ` ${name} ${range} ${from} ${to} ${url}`; + }; -module.exports = co['default'] = co.co = co; + const groupedDeps = deps.reduce(function (acc, dep) { + const hint = dep.hint, + name = dep.name, + upgradeTo = dep.upgradeTo; -/** - * Wrap the given generator `fn` into a - * function that returns a promise. - * This is a separate function so that - * every `co()` call doesn't create a new, - * unnecessary closure. - * - * @param {GeneratorFunction} fn - * @return {Function} - * @api public - */ + const version = dep[outdatedFieldName]; + const key = getNameFromHint(hint); + const xs = acc[key] || []; + acc[key] = xs.concat({ + name: makeRow(dep), + value: dep, + short: `${name}@${version}`, + upgradeTo + }); + return acc; + }, {}); -co.wrap = function (fn) { - createPromise.__generatorFunction__ = fn; - return createPromise; - function createPromise() { - return co.call(this, fn.apply(this, arguments)); - } -}; + const flatten = function (xs) { + return xs.reduce(function (ys, y) { + return ys.concat(Array.isArray(y) ? flatten(y) : y); + }, []); + }; -/** - * Execute the generator function or a generator - * and return a promise. - * - * @param {Function} fn - * @return {Promise} - * @api public - */ + const choices = flatten(Object.keys(groupedDeps).map(function (key) { + return [new (_inquirer || _load_inquirer()).default.Separator(reporter.format.bold.underline.green(key)), new (_inquirer || _load_inquirer()).default.Separator(makeHeaderRow()), groupedDeps[key], new (_inquirer || _load_inquirer()).default.Separator(' ')]; + })); -function co(gen) { - var ctx = this; - var args = slice.call(arguments, 1) + try { + const red = reporter.format.red('<red>'); + const yellow = reporter.format.yellow('<yellow>'); + const green = reporter.format.green('<green>'); + reporter.info(reporter.lang('legendColorsForUpgradeInteractive', red, yellow, green)); - // we wrap everything in a promise to avoid promise chaining, - // which leads to memory leak errors. - // see https://github.com/tj/co/issues/180 - return new Promise(function(resolve, reject) { - if (typeof gen === 'function') gen = gen.apply(ctx, args); - if (!gen || typeof gen.next !== 'function') return resolve(gen); + const answers = yield reporter.prompt('Choose which packages to update.', choices, { + name: 'packages', + type: 'checkbox', + validate: function (answer) { + return !!answer.length || 'You must choose at least one package.'; + } + }); - onFulfilled(); + const getPattern = function (_ref2) { + let upgradeTo = _ref2.upgradeTo; + return upgradeTo; + }; + const isHint = function (x) { + return function (_ref3) { + let hint = _ref3.hint; + return hint === x; + }; + }; - /** - * @param {Mixed} res - * @return {Promise} - * @api private - */ + yield [null, 'dev', 'optional', 'peer'].reduce((() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (promise, hint) { + // Wait for previous promise to resolve + yield promise; + // Reset dependency flags + flags.dev = hint === 'dev'; + flags.peer = hint === 'peer'; + flags.optional = hint === 'optional'; + const deps = answers.filter(isHint(hint)).map(getPattern); + if (deps.length) { + for (const pattern of deps) { + lockfile.removePattern(pattern); + } + reporter.info(reporter.lang('updateInstalling', getNameFromHint(hint))); + const add = new (_add || _load_add()).Add(deps, flags, config, reporter, lockfile); + return add.init(); + } + return Promise.resolve(); + }); - function onFulfilled(res) { - var ret; - try { - ret = gen.next(res); - } catch (e) { - return reject(e); - } - next(ret); + return function (_x5, _x6) { + return _ref4.apply(this, arguments); + }; + })(), Promise.resolve()); + } catch (e) { + Promise.reject(e); } + }); - /** - * @param {Error} err - * @return {Promise} - * @api private - */ + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); - function onRejected(err) { - var ret; - try { - ret = gen.throw(err); - } catch (e) { - return reject(e); - } - next(ret); - } +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; - /** - * Get the next value in the generator, - * return a promise. - * - * @param {Object} ret - * @return {Promise} - * @api private - */ +var _inquirer; - function next(ret) { - if (ret.done) return resolve(ret.value); - var value = toPromise.call(ctx, ret.value); - if (value && isPromise(value)) return value.then(onFulfilled, onRejected); - return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, ' - + 'but the following object was passed: "' + String(ret.value) + '"')); - } - }); +function _load_inquirer() { + return _inquirer = _interopRequireDefault(__webpack_require__(212)); } -/** - * Convert a `yield`ed value into a promise. - * - * @param {Mixed} obj - * @return {Promise} - * @api private - */ +var _lockfile; -function toPromise(obj) { - if (!obj) return obj; - if (isPromise(obj)) return obj; - if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj); - if ('function' == typeof obj) return thunkToPromise.call(this, obj); - if (Array.isArray(obj)) return arrayToPromise.call(this, obj); - if (isObject(obj)) return objectToPromise.call(this, obj); - return obj; +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); } -/** - * Convert a thunk to a promise. - * - * @param {Function} - * @return {Promise} - * @api private - */ +var _add; -function thunkToPromise(fn) { - var ctx = this; - return new Promise(function (resolve, reject) { - fn.call(ctx, function (err, res) { - if (err) return reject(err); - if (arguments.length > 2) res = slice.call(arguments, 1); - resolve(res); - }); - }); +function _load_add() { + return _add = __webpack_require__(121); } -/** - * Convert an array of "yieldables" to a promise. - * Uses `Promise.all()` internally. - * - * @param {Array} obj - * @return {Promise} - * @api private - */ +var _upgrade; -function arrayToPromise(obj) { - return Promise.all(obj.map(toPromise, this)); +function _load_upgrade() { + return _upgrade = __webpack_require__(157); } -/** - * Convert an object of "yieldables" to a promise. - * Uses `Promise.all()` internally. - * - * @param {Object} obj - * @return {Promise} - * @api private - */ - -function objectToPromise(obj){ - var results = new obj.constructor(); - var keys = Object.keys(obj); - var promises = []; - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var promise = toPromise.call(this, obj[key]); - if (promise && isPromise(promise)) defer(promise, key); - else results[key] = obj[key]; - } - return Promise.all(promises).then(function () { - return results; - }); +var _colorForVersions; - function defer(promise, key) { - // predefine the key in the result - results[key] = undefined; - promises.push(promise.then(function (res) { - results[key] = res; - })); - } +function _load_colorForVersions() { + return _colorForVersions = _interopRequireDefault(__webpack_require__(271)); } -/** - * Check if `obj` is a promise. - * - * @param {Object} obj - * @return {Boolean} - * @api private - */ +var _colorizeDiff; -function isPromise(obj) { - return 'function' == typeof obj.then; +function _load_colorizeDiff() { + return _colorizeDiff = _interopRequireDefault(__webpack_require__(272)); } -/** - * Check if `obj` is a generator. - * - * @param {Mixed} obj - * @return {Boolean} - * @api private - */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function isGenerator(obj) { - return 'function' == typeof obj.next && 'function' == typeof obj.throw; -} +const requireLockfile = exports.requireLockfile = true; -/** - * Check if `obj` is a generator function. - * - * @param {Mixed} obj - * @return {Boolean} - * @api private - */ -function isGeneratorFunction(obj) { - var constructor = obj.constructor; - if (!constructor) return false; - if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true; - return isGenerator(constructor.prototype); +function setFlags(commander) { + commander.usage('upgrade-interactive [flags]'); + commander.option('-S, --scope <scope>', 'upgrade packages under the specified scope'); + commander.option('--latest', 'list the latest version of packages, ignoring version ranges in package.json'); + commander.option('-E, --exact', 'install exact version. Only used when --latest is specified.'); + commander.option('-T, --tilde', 'install most recent release with the same minor version. Only used when --latest is specified.'); + commander.option('-C, --caret', 'install most recent release with the same major version. Only used when --latest is specified.'); } -/** - * Check for plain object. - * - * @param {Mixed} val - * @return {Boolean} - * @api private - */ - -function isObject(val) { - return Object == val.constructor; +function hasWrapper(commander, args) { + return true; } - /***/ }), -/* 213 */ +/* 260 */ /***/ (function(module, exports, __webpack_require__) { -var util = __webpack_require__(2); -var Stream = __webpack_require__(20).Stream; -var DelayedStream = __webpack_require__(455); +"use strict"; -module.exports = CombinedStream; -function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; - this._released = false; - this._streams = []; - this._currentStream = null; -} -util.inherits(CombinedStream, Stream); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.setVersion = undefined; -CombinedStream.create = function(options) { - var combinedStream = new this(); +var _asyncToGenerator2; - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - return combinedStream; -}; +let setVersion = exports.setVersion = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args, required) { + const pkg = yield config.readRootManifest(); + const pkgLoc = pkg._loc; + const scripts = (0, (_map || _load_map()).default)(); + let newVersion = flags.newVersion; + invariant(pkgLoc, 'expected package location'); -CombinedStream.isStreamLike = function(stream) { - return (typeof stream !== 'function') - && (typeof stream !== 'string') - && (typeof stream !== 'boolean') - && (typeof stream !== 'number') - && (!Buffer.isBuffer(stream)); -}; + if (args.length && !newVersion) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidVersionArgument', NEW_VERSION_FLAG)); + } -CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); + function runLifecycle(lifecycle) { + if (scripts[lifecycle]) { + return (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execCommand)(lifecycle, config, scripts[lifecycle], config.cwd); + } - if (isStreamLike) { - if (!(stream instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams, - }); - stream.on('data', this._checkDataSize.bind(this)); - stream = newStream; + return Promise.resolve(); } - this._handleErrors(stream); + if (pkg.scripts) { + // inherit `scripts` from manifest + Object.assign(scripts, pkg.scripts); + } - if (this.pauseStreams) { - stream.pause(); + // get old version + let oldVersion = pkg.version; + if (oldVersion) { + reporter.info(`${reporter.lang('currentVersion')}: ${oldVersion}`); + } else { + oldVersion = '0.0.0'; } - } - this._streams.push(stream); - return this; -}; + // get new version + if (newVersion && !isValidNewVersion(oldVersion, newVersion, config.looseSemver)) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidVersion')); + } -CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; -}; + // wasn't passed a version arg so ask interactively + while (!newVersion) { + newVersion = yield reporter.question(reporter.lang('newVersion')); -CombinedStream.prototype._getNext = function() { - this._currentStream = null; - var stream = this._streams.shift(); + if (!required && !newVersion) { + return function () { + return Promise.resolve(); + }; + } + if (isValidNewVersion(oldVersion, newVersion, config.looseSemver)) { + break; + } else { + newVersion = null; + reporter.error(reporter.lang('invalidSemver')); + } + } + if (newVersion) { + newVersion = semver.inc(oldVersion, newVersion, config.looseSemver) || newVersion; + } + invariant(newVersion, 'expected new version'); - if (typeof stream == 'undefined') { - this.end(); - return; - } + if (newVersion === pkg.version) { + return function () { + return Promise.resolve(); + }; + } - if (typeof stream !== 'function') { - this._pipeNext(stream); - return; - } + yield runLifecycle('preversion'); - var getStream = stream; - getStream(function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('data', this._checkDataSize.bind(this)); - this._handleErrors(stream); + // update version + reporter.info(`${reporter.lang('newVersion')}: ${newVersion}`); + pkg.version = newVersion; + + // update versions in manifests + const manifests = yield config.getRootManifests(); + for (const registryName of (_index || _load_index()).registryNames) { + const manifest = manifests[registryName]; + if (manifest.exists) { + manifest.object.version = newVersion; + } } + yield config.saveRootManifests(manifests); - this._pipeNext(stream); - }.bind(this)); -}; + // check if committing the new version to git is overriden + if (!flags.gitTagVersion || !config.getOption('version-git-tag')) { + // Don't tag the version in Git + return function () { + return Promise.resolve(); + }; + } -CombinedStream.prototype._pipeNext = function(stream) { - this._currentStream = stream; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + invariant(newVersion, 'expected version'); - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('end', this._getNext.bind(this)); - stream.pipe(this, {end: false}); - return; - } + // add git commit and tag + let isGit = false; + const parts = config.cwd.split(path.sep); + while (parts.length) { + isGit = yield (_fs || _load_fs()).exists(path.join(parts.join(path.sep), '.git')); + if (isGit) { + break; + } else { + parts.pop(); + } + } - var value = stream; - this.write(value); - this._getNext(); -}; + yield runLifecycle('version'); -CombinedStream.prototype._handleErrors = function(stream) { - var self = this; - stream.on('error', function(err) { - self._emitError(err); - }); -}; + if (isGit) { + const message = (flags.message || String(config.getOption('version-git-message'))).replace(/%s/g, newVersion); + const sign = Boolean(config.getOption('version-sign-git-tag')); + const flag = sign ? '-sm' : '-am'; + const prefix = String(config.getOption('version-tag-prefix')); -CombinedStream.prototype.write = function(data) { - this.emit('data', data); -}; + const gitRoot = (yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['rev-parse', '--show-toplevel'], { cwd: config.cwd })).trim(); -CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; - } + // add manifest + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['add', path.relative(gitRoot, pkgLoc)], { cwd: gitRoot }); - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); - this.emit('pause'); -}; + // create git commit + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['commit', '-m', message], { cwd: gitRoot }); -CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); - } + // create git tag + yield (0, (_gitSpawn || _load_gitSpawn()).spawn)(['tag', `${prefix}${newVersion}`, flag, message], { cwd: gitRoot }); + } - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); - this.emit('resume'); -}; + yield runLifecycle('postversion'); + }); + }); -CombinedStream.prototype.end = function() { - this._reset(); - this.emit('end'); -}; + return function setVersion(_x, _x2, _x3, _x4, _x5) { + return _ref.apply(this, arguments); + }; +})(); -CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit('close'); -}; +let run = exports.run = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const commit = yield setVersion(config, reporter, flags, args, true); + yield commit(); + }); -CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; -}; + return function run(_x6, _x7, _x8, _x9) { + return _ref3.apply(this, arguments); + }; +})(); -CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; - } +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; - this._emitError(new Error(message)); -}; +var _index; -CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; +function _load_index() { + return _index = __webpack_require__(34); +} - var self = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; - } +var _executeLifecycleScript; - self.dataSize += stream.dataSize; - }); +function _load_executeLifecycleScript() { + return _executeLifecycleScript = __webpack_require__(97); +} - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } -}; +var _errors; -CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit('error', err); -}; +function _load_errors() { + return _errors = __webpack_require__(3); +} +var _gitSpawn; -/***/ }), -/* 214 */ -/***/ (function(module, exports) { +function _load_gitSpawn() { + return _gitSpawn = __webpack_require__(274); +} -// IE 8- don't enum bug keys -module.exports = ( - 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' -).split(','); +var _fs; -/***/ }), -/* 215 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} -module.exports = __webpack_require__(29).document && document.documentElement; +var _map; -/***/ }), -/* 216 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); +} -// fallback for non-array-like ES3 and non-enumerable old V8 strings -var cof = __webpack_require__(88); -module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ - return cof(it) == 'String' ? it.split('') : Object(it); -}; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -/***/ }), -/* 217 */ -/***/ (function(module, exports, __webpack_require__) { +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// check on default Array iterator -var Iterators = __webpack_require__(55) - , ITERATOR = __webpack_require__(26)('iterator') - , ArrayProto = Array.prototype; +const invariant = __webpack_require__(7); +const semver = __webpack_require__(22); +const path = __webpack_require__(0); -module.exports = function(it){ - return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); -}; +const NEW_VERSION_FLAG = '--new-version [version]'; +function isValidNewVersion(oldVersion, newVersion, looseSemver) { + return !!(semver.valid(newVersion, looseSemver) || semver.inc(oldVersion, newVersion, looseSemver)); +} -/***/ }), -/* 218 */ -/***/ (function(module, exports, __webpack_require__) { +function setFlags(commander) { + commander.option(NEW_VERSION_FLAG, 'new version'); + commander.option('--message [message]', 'message'); + commander.option('--no-git-tag-version', 'no git tag version'); +} -// call something on iterator step with safe closing on error -var anObject = __webpack_require__(46); -module.exports = function(iterator, fn, value, entries){ - try { - return entries ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch(e){ - var ret = iterator['return']; - if(ret !== undefined)anObject(ret.call(iterator)); - throw e; - } -}; +function hasWrapper(commander, args) { + return true; +} /***/ }), -/* 219 */ +/* 261 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var LIBRARY = __webpack_require__(221) - , $export = __webpack_require__(89) - , redefine = __webpack_require__(436) - , hide = __webpack_require__(54) - , has = __webpack_require__(90) - , Iterators = __webpack_require__(55) - , $iterCreate = __webpack_require__(425) - , setToStringTag = __webpack_require__(140) - , getPrototypeOf = __webpack_require__(432) - , ITERATOR = __webpack_require__(26)('iterator') - , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` - , FF_ITERATOR = '@@iterator' - , KEYS = 'keys' - , VALUES = 'values'; -var returnThis = function(){ return this; }; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LocalTarballFetcher = undefined; -module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ - $iterCreate(Constructor, NAME, next); - var getMethod = function(kind){ - if(!BUGGY && kind in proto)return proto[kind]; - switch(kind){ - case KEYS: return function keys(){ return new Constructor(this, kind); }; - case VALUES: return function values(){ return new Constructor(this, kind); }; - } return function entries(){ return new Constructor(this, kind); }; - }; - var TAG = NAME + ' Iterator' - , DEF_VALUES = DEFAULT == VALUES - , VALUES_BUG = false - , proto = Base.prototype - , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] - , $default = $native || getMethod(DEFAULT) - , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined - , $anyNative = NAME == 'Array' ? proto.entries || $native : $native - , methods, key, IteratorPrototype; - // Fix native - if($anyNative){ - IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); - if(IteratorPrototype !== Object.prototype){ - // Set @@toStringTag to native iterators - setToStringTag(IteratorPrototype, TAG, true); - // fix for some old engines - if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); - } - } - // fix Array#{values, @@iterator}.name in V8 / FF - if(DEF_VALUES && $native && $native.name !== VALUES){ - VALUES_BUG = true; - $default = function values(){ return $native.call(this); }; - } - // Define iterator - if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ - hide(proto, ITERATOR, $default); - } - // Plug for library - Iterators[NAME] = $default; - Iterators[TAG] = returnThis; - if(DEFAULT){ - methods = { - values: DEF_VALUES ? $default : getMethod(VALUES), - keys: IS_SET ? $default : getMethod(KEYS), - entries: $entries - }; - if(FORCED)for(key in methods){ - if(!(key in proto))redefine(proto, key, methods[key]); - } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); - } - return methods; -}; +var _asyncToGenerator2; -/***/ }), -/* 220 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} -var ITERATOR = __webpack_require__(26)('iterator') - , SAFE_CLOSING = false; +var _http; -try { - var riter = [7][ITERATOR](); - riter['return'] = function(){ SAFE_CLOSING = true; }; - Array.from(riter, function(){ throw 2; }); -} catch(e){ /* empty */ } +function _load_http() { + return _http = _interopRequireDefault(__webpack_require__(49)); +} -module.exports = function(exec, skipClosing){ - if(!skipClosing && !SAFE_CLOSING)return false; - var safe = false; - try { - var arr = [7] - , iter = arr[ITERATOR](); - iter.next = function(){ return {done: safe = true}; }; - arr[ITERATOR] = function(){ return iter; }; - exec(arr); - } catch(e){ /* empty */ } - return safe; -}; +var _errors; -/***/ }), -/* 221 */ -/***/ (function(module, exports) { +function _load_errors() { + return _errors = __webpack_require__(3); +} -module.exports = true; +var _constants; -/***/ }), -/* 222 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} -// 19.1.2.14 / 15.2.3.14 Object.keys(O) -var $keys = __webpack_require__(433) - , enumBugKeys = __webpack_require__(214); +var _crypto; -module.exports = Object.keys || function keys(O){ - return $keys(O, enumBugKeys); -}; +function _load_crypto() { + return _crypto = _interopRequireWildcard(__webpack_require__(123)); +} -/***/ }), -/* 223 */ -/***/ (function(module, exports, __webpack_require__) { +var _baseFetcher; -var global = __webpack_require__(29) - , SHARED = '__core-js_shared__' - , store = global[SHARED] || (global[SHARED] = {}); -module.exports = function(key){ - return store[key] || (store[key] = {}); -}; +function _load_baseFetcher() { + return _baseFetcher = _interopRequireDefault(__webpack_require__(122)); +} -/***/ }), -/* 224 */ -/***/ (function(module, exports, __webpack_require__) { +var _fs; -var ctx = __webpack_require__(68) - , invoke = __webpack_require__(424) - , html = __webpack_require__(215) - , cel = __webpack_require__(137) - , global = __webpack_require__(29) - , process = global.process - , setTask = global.setImmediate - , clearTask = global.clearImmediate - , MessageChannel = global.MessageChannel - , counter = 0 - , queue = {} - , ONREADYSTATECHANGE = 'onreadystatechange' - , defer, channel, port; -var run = function(){ - var id = +this; - if(queue.hasOwnProperty(id)){ - var fn = queue[id]; - delete queue[id]; - fn(); - } -}; -var listener = function(event){ - run.call(event.data); -}; -// Node.js 0.9+ & IE10+ has setImmediate, otherwise: -if(!setTask || !clearTask){ - setTask = function setImmediate(fn){ - var args = [], i = 1; - while(arguments.length > i)args.push(arguments[i++]); - queue[++counter] = function(){ - invoke(typeof fn == 'function' ? fn : Function(fn), args); - }; - defer(counter); - return counter; - }; - clearTask = function clearImmediate(id){ - delete queue[id]; - }; - // Node.js 0.8- - if(__webpack_require__(88)(process) == 'process'){ - defer = function(id){ - process.nextTick(ctx(run, id, 1)); - }; - // Browsers with MessageChannel, includes WebWorkers - } else if(MessageChannel){ - channel = new MessageChannel; - port = channel.port2; - channel.port1.onmessage = listener; - defer = ctx(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ - defer = function(id){ - global.postMessage(id + '', '*'); - }; - global.addEventListener('message', listener, false); - // IE8- - } else if(ONREADYSTATECHANGE in cel('script')){ - defer = function(id){ - html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ - html.removeChild(this); - run.call(id); - }; - }; - // Rest old browsers - } else { - defer = function(id){ - setTimeout(ctx(run, id, 1), 0); - }; - } +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } -module.exports = { - set: setTask, - clear: clearTask -}; -/***/ }), -/* 225 */ -/***/ (function(module, exports) { +var _misc; -var id = 0 - , px = Math.random(); -module.exports = function(key){ - return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); -}; +function _load_misc() { + return _misc = __webpack_require__(10); +} -/***/ }), -/* 226 */ -/***/ (function(module, exports, __webpack_require__) { +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -// Load modules +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -var Crypto = __webpack_require__(7); -var Boom = __webpack_require__(87); +const path = __webpack_require__(0); +const tarFs = __webpack_require__(145); +const url = __webpack_require__(14); +const fs = __webpack_require__(5); +const stream = __webpack_require__(26); +const gunzip = __webpack_require__(498); +const invariant = __webpack_require__(7); -// Declare internals +class TarballFetcher extends (_baseFetcher || _load_baseFetcher()).default { + setupMirrorFromCache() { + var _this = this; -var internals = {}; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const tarballMirrorPath = _this.getTarballMirrorPath(); + const tarballCachePath = _this.getTarballCachePath(); + if (tarballMirrorPath == null) { + return; + } -// Generate a cryptographically strong pseudo-random data + if (!(yield (_fs || _load_fs()).exists(tarballMirrorPath)) && (yield (_fs || _load_fs()).exists(tarballCachePath))) { + // The tarball doesn't exists in the offline cache but does in the cache; we import it to the mirror + yield (_fs || _load_fs()).mkdirp(path.dirname(tarballMirrorPath)); + yield (_fs || _load_fs()).copy(tarballCachePath, tarballMirrorPath, _this.reporter); + } + })(); + } -exports.randomString = function (size) { - - var buffer = exports.randomBits((size + 1) * 6); - if (buffer instanceof Error) { - return buffer; - } - - var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, ''); - return string.slice(0, size); -}; + getTarballCachePath() { + return path.join(this.dest, (_constants || _load_constants()).TARBALL_FILENAME); + } + getTarballMirrorPath() { + var _url$parse = url.parse(this.reference); -exports.randomBits = function (bits) { + const pathname = _url$parse.pathname; - if (!bits || - bits < 0) { - return Boom.internal('Invalid random bits count'); + if (pathname == null) { + return null; } - var bytes = Math.ceil(bits / 8); - try { - return Crypto.randomBytes(bytes); - } - catch (err) { - return Boom.internal('Failed generating random bits: ' + err.message); - } -}; + // handle scoped packages + const pathParts = pathname.replace(/^\//, '').split(/\//g); + const packageFilename = pathParts.length >= 2 && pathParts[0][0] === '@' ? `${pathParts[0]}-${pathParts[pathParts.length - 1]}` // scopped + : `${pathParts[pathParts.length - 1]}`; -// Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match) + return this.config.getOfflineMirrorPath(packageFilename); + } -exports.fixedTimeComparison = function (a, b) { + createExtractor(resolve, reject, tarballPath) { + const validateStream = new (_crypto || _load_crypto()).HashStream(); + const extractorStream = gunzip(); + const untarStream = tarFs.extract(this.dest, { + strip: 1, + dmode: 0o755, // all dirs should be readable + fmode: 0o644, // all files should be readable + chown: false }); - if (typeof a !== 'string' || - typeof b !== 'string') { + extractorStream.pipe(untarStream).on('error', error => { + error.message = `${error.message}${tarballPath ? ` (${tarballPath})` : ''}`; + reject(error); + }).on('finish', () => { + const expectHash = this.hash; + const actualHash = validateStream.getHash(); - return false; - } + if (!expectHash || expectHash === actualHash) { + resolve({ + hash: actualHash + }); + } else { + reject(new (_errors || _load_errors()).SecurityError(this.config.reporter.lang('fetchBadHashWithPath', this.packageName, this.remote.reference, expectHash, actualHash))); + } + }); - var mismatch = (a.length === b.length ? 0 : 1); - if (mismatch) { - b = a; - } + return { validateStream, extractorStream }; + } - for (var i = 0, il = a.length; i < il; ++i) { - var ac = a.charCodeAt(i); - var bc = b.charCodeAt(i); - mismatch |= (ac ^ bc); + *getLocalPaths(override) { + if (override) { + yield path.resolve(this.config.cwd, override); } + yield this.getTarballMirrorPath(); + yield this.getTarballCachePath(); + } - return (mismatch === 0); -}; + fetchFromLocal(override) { + var _this2 = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref = yield (_fs || _load_fs()).readFirstAvailableStream(_this2.getLocalPaths(override)); + const stream = _ref.stream, + triedPaths = _ref.triedPaths; -/***/ }), -/* 227 */ -/***/ (function(module, exports, __webpack_require__) { + return new Promise(function (resolve, reject) { + if (!stream) { + reject(new (_errors || _load_errors()).MessageError(_this2.reporter.lang('tarballNotInNetworkOrCache', _this2.reference, triedPaths))); + return; + } + invariant(stream, 'stream should be available at this point'); + // $FlowFixMe - This is available https://nodejs.org/api/fs.html#fs_readstream_path + const tarballPath = stream.path; + var _createExtractor = _this2.createExtractor(resolve, reject, tarballPath); -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ + const validateStream = _createExtractor.validateStream, + extractorStream = _createExtractor.extractorStream; -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __webpack_require__(560); -/** - * The currently active debug mode names, and names to skip. - */ + stream.pipe(validateStream).pipe(extractorStream).on('error', function (err) { + reject(new (_errors || _load_errors()).MessageError(_this2.config.reporter.lang('fetchErrorCorrupt', err.message, tarballPath))); + }); + }); + })(); + } -exports.names = []; -exports.skips = []; + fetchFromExternal() { + var _this3 = this; -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const registry = _this3.config.registries[_this3.registry]; -exports.formatters = {}; + let retriesRemaining = 2; + do { + try { + return yield registry.request(_this3.reference, { + headers: { + 'Accept-Encoding': 'gzip', + Accept: 'application/octet-stream' + }, + buffer: true, + process: function (req, resolve, reject) { + // should we save this to the offline cache? + const reporter = _this3.config.reporter; -/** - * Previous log timestamp. - */ + const tarballMirrorPath = _this3.getTarballMirrorPath(); + const tarballCachePath = _this3.getTarballCachePath(); -var prevTime; + var _createExtractor2 = _this3.createExtractor(resolve, reject); -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ + const validateStream = _createExtractor2.validateStream, + extractorStream = _createExtractor2.extractorStream; -function selectColor(namespace) { - var hash = 0, i; - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + req.on('response', function (res) { + if (res.statusCode >= 400) { + const statusDescription = (_http || _load_http()).default.STATUS_CODES[res.statusCode]; + reject(new (_errors || _load_errors()).ResponseError(reporter.lang('requestFailed', `${res.statusCode} ${statusDescription}`), res.statusCode)); + } + }); + req.pipe(validateStream); - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + if (tarballMirrorPath) { + validateStream.pipe(fs.createWriteStream(tarballMirrorPath)).on('error', reject); + } -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ + if (tarballCachePath) { + validateStream.pipe(fs.createWriteStream(tarballCachePath)).on('error', reject); + } -function createDebug(namespace) { + validateStream.pipe(extractorStream).on('error', reject); + } + }, _this3.packageName); + } catch (err) { + if (err instanceof (_errors || _load_errors()).ResponseError && err.responseCode >= 500 && retriesRemaining > 1) { + retriesRemaining--; + _this3.reporter.warn(_this3.reporter.lang('retryOnInternalServerError')); + yield (0, (_misc || _load_misc()).sleep)(3000); + } else { + const tarballMirrorPath = _this3.getTarballMirrorPath(); + const tarballCachePath = _this3.getTarballCachePath(); - function debug() { - // disabled? - if (!debug.enabled) return; + if (tarballMirrorPath && (yield (_fs || _load_fs()).exists(tarballMirrorPath))) { + yield (_fs || _load_fs()).unlink(tarballMirrorPath); + } - var self = debug; + if (tarballCachePath && (yield (_fs || _load_fs()).exists(tarballCachePath))) { + yield (_fs || _load_fs()).unlink(tarballCachePath); + } - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + throw err; + } + } + } while (retriesRemaining > 0); + // Unreachable code, this is just to make Flow happy + throw new Error('Ran out of retries!'); + })(); + } - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } + _fetch() { + const isFilePath = this.reference.startsWith('file:'); + this.reference = (0, (_misc || _load_misc()).removePrefix)(this.reference, 'file:'); + const urlParse = url.parse(this.reference); - args[0] = exports.coerce(args[0]); + // legacy support for local paths in yarn.lock entries + const isRelativePath = urlParse.protocol ? urlParse.protocol.match(/^[a-z]:$/i) : urlParse.pathname ? urlParse.pathname.match(/^(?:\.{1,2})?[\\\/]/) : false; - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + if (isFilePath || isRelativePath) { + return this.fetchFromLocal(this.reference); } - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); + return this.fetchFromLocal().catch(err => this.fetchFromExternal()); } +} - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); +exports.default = TarballFetcher; +class LocalTarballFetcher extends TarballFetcher { + _fetch() { + return this.fetchFromLocal(this.reference); } - - return debug; } +exports.LocalTarballFetcher = LocalTarballFetcher; -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ +/***/ }), +/* 262 */ +/***/ (function(module, exports, __webpack_require__) { -function enable(namespaces) { - exports.save(namespaces); +"use strict"; - exports.names = []; - exports.skips = []; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.testEngine = testEngine; +exports.checkOne = checkOne; +exports.check = check; - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); } -/** - * Disable debug output. - * - * @api public - */ +var _map; -function disable() { - exports.enable(''); +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); } -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ +var _misc; -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; +function _load_misc() { + return _misc = __webpack_require__(10); } -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ +var _yarnVersion; -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +function _load_yarnVersion() { + return _yarnVersion = __webpack_require__(91); } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 228 */ -/***/ (function(module, exports, __webpack_require__) { +const invariant = __webpack_require__(7); +const semver = __webpack_require__(22); -var stream = __webpack_require__(47) -var eos = __webpack_require__(457) -var inherits = __webpack_require__(37) -var shift = __webpack_require__(620) +const VERSIONS = Object.assign({}, process.versions, { + yarn: (_yarnVersion || _load_yarnVersion()).version +}); -var SIGNAL_FLUSH = new Buffer([0]) +function isValid(items, actual) { + let isNotWhitelist = true; + let isBlacklist = false; -var onuncork = function(self, fn) { - if (self._corked) self.once('uncork', fn) - else fn() -} + for (const item of items) { + // blacklist + if (item[0] === '!') { + isBlacklist = true; -var destroyer = function(self, end) { - return function(err) { - if (err) self.destroy(err.message === 'premature close' ? null : err) - else if (end && !self._ended) self.end() - } -} + if (actual === item.slice(1)) { + return false; + } + // whitelist + } else { + isNotWhitelist = false; -var end = function(ws, fn) { - if (!ws) return fn() - if (ws._writableState && ws._writableState.finished) return fn() - if (ws._writableState) return ws.end(fn) - ws.end() - fn() -} + if (item === actual) { + return true; + } + } + } -var toStreams2 = function(rs) { - return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) + // npm allows blacklists and whitelists to be mixed. Blacklists with + // whitelisted items should be treated as whitelists. + return isBlacklist && isNotWhitelist; } -var Duplexify = function(writable, readable, opts) { - if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) - stream.Duplex.call(this, opts) +const aliases = (0, (_map || _load_map()).default)({ + iojs: 'node' }); - this._writable = null - this._readable = null - this._readable2 = null +const ignore = ['npm', // we'll never satisfy this for obvious reasons +'teleport', // a module bundler used by some modules +'rhino', // once a target for older modules +'cordovaDependencies']; - this._forwardDestroy = !opts || opts.destroy !== false - this._forwardEnd = !opts || opts.end !== false - this._corked = 1 // start corked - this._ondrain = null - this._drained = false - this._forwarding = false - this._unwrite = null - this._unread = null - this._ended = false +function testEngine(name, range, versions, looseSemver) { + const actual = versions[name]; + if (!actual) { + return false; + } - this.destroyed = false + if (!semver.valid(actual, looseSemver)) { + return false; + } - if (writable) this.setWritable(writable) - if (readable) this.setReadable(readable) -} + if (semver.satisfies(actual, range, looseSemver)) { + return true; + } -inherits(Duplexify, stream.Duplex) + if (name === 'node' && semver.gt(actual, '1.0.0', looseSemver)) { + // WARNING: this is a massive hack and is super gross but necessary for compatibility + // some modules have the `engines.node` field set to a caret version below semver major v1 + // eg. ^0.12.0. this is problematic as we enforce engines checks and node is now on version >=1 + // to allow this pattern we transform the node version to fake ones in the minor range 10-13 + const major = semver.major(actual, looseSemver); + const fakes = [`0.10.${major}`, `0.11.${major}`, `0.12.${major}`, `0.13.${major}`]; + for (const actualFake of fakes) { + if (semver.satisfies(actualFake, range, looseSemver)) { + return true; + } + } + } -Duplexify.obj = function(writable, readable, opts) { - if (!opts) opts = {} - opts.objectMode = true - opts.highWaterMark = 16 - return new Duplexify(writable, readable, opts) + // incompatible version + return false; } -Duplexify.prototype.cork = function() { - if (++this._corked === 1) this.emit('cork') +function isValidArch(archs) { + return isValid(archs, process.arch); } -Duplexify.prototype.uncork = function() { - if (this._corked && --this._corked === 0) this.emit('uncork') +function isValidPlatform(platforms) { + return isValid(platforms, process.platform); } -Duplexify.prototype.setWritable = function(writable) { - if (this._unwrite) this._unwrite() +function checkOne(info, config, ignoreEngines) { + let didIgnore = false; + let didError = false; + const reporter = config.reporter; + const human = `${info.name}@${info.version}`; - if (this.destroyed) { - if (writable && writable.destroy) writable.destroy() - return - } + const pushError = msg => { + const ref = info._reference; + invariant(ref, 'expected package reference'); - if (writable === null || writable === false) { - this.end() - return - } + if (ref.optional) { + ref.ignore = true; + ref.incompatible = true; - var self = this - var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) + reporter.info(`${human}: ${msg}`); + if (!didIgnore) { + reporter.info(reporter.lang('optionalCompatibilityExcluded', human)); + didIgnore = true; + } + } else { + reporter.error(`${human}: ${msg}`); + didError = true; + } + }; - var ondrain = function() { - var ondrain = self._ondrain - self._ondrain = null - if (ondrain) ondrain() - } + const invalidPlatform = !config.ignorePlatform && Array.isArray(info.os) && info.os.length > 0 && !isValidPlatform(info.os); - var clear = function() { - self._writable.removeListener('drain', ondrain) - unend() + if (invalidPlatform) { + pushError(reporter.lang('incompatibleOS', process.platform)); } - if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks - - this._writable = writable - this._writable.on('drain', ondrain) - this._unwrite = clear - - this.uncork() // always uncork setWritable -} - -Duplexify.prototype.setReadable = function(readable) { - if (this._unread) this._unread() + const invalidCpu = !config.ignorePlatform && Array.isArray(info.cpu) && info.cpu.length > 0 && !isValidArch(info.cpu); - if (this.destroyed) { - if (readable && readable.destroy) readable.destroy() - return + if (invalidCpu) { + pushError(reporter.lang('incompatibleCPU', process.arch)); } - if (readable === null || readable === false) { - this.push(null) - this.resume() - return - } + if (!ignoreEngines && typeof info.engines === 'object') { + for (const entry of (0, (_misc || _load_misc()).entries)(info.engines)) { + let name = entry[0]; + const range = entry[1]; - var self = this - var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) + if (aliases[name]) { + name = aliases[name]; + } - var onreadable = function() { - self._forward() + if (VERSIONS[name]) { + if (!testEngine(name, range, VERSIONS, config.looseSemver)) { + pushError(reporter.lang('incompatibleEngine', name, range)); + } + } else if (ignore.indexOf(name) < 0) { + reporter.warn(`${human}: ${reporter.lang('invalidEngine', name)}`); + } + } } - var onend = function() { - self.push(null) + if (didError) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('foundIncompatible')); } +} - var clear = function() { - self._readable2.removeListener('readable', onreadable) - self._readable2.removeListener('end', onend) - unend() +function check(infos, config, ignoreEngines) { + for (const info of infos) { + checkOne(info, config, ignoreEngines); } - - this._drained = true - this._readable = readable - this._readable2 = readable._readableState ? readable : toStreams2(readable) - this._readable2.on('readable', onreadable) - this._readable2.on('end', onend) - this._unread = clear - - this._forward() } -Duplexify.prototype._read = function() { - this._drained = true - this._forward() -} +/***/ }), +/* 263 */ +/***/ (function(module, exports, __webpack_require__) { -Duplexify.prototype._forward = function() { - if (this._forwarding || !this._readable2 || !this._drained) return - this._forwarding = true +"use strict"; - var data - while (this._drained && (data = shift(this._readable2)) !== null) { - if (this.destroyed) continue - this._drained = this.push(data) - } +Object.defineProperty(exports, "__esModule", { + value: true +}); - this._forwarding = false +var _asyncToGenerator2; + +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -Duplexify.prototype.destroy = function(err) { - if (this.destroyed) return - this.destroyed = true +let fetchCache = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (dest, fetcher, config) { + var _ref2 = yield config.readPackageMetadata(dest); - var self = this - process.nextTick(function() { - self._destroy(err) - }) -} + const hash = _ref2.hash, + pkg = _ref2.package; -Duplexify.prototype._destroy = function(err) { - if (err) { - var ondrain = this._ondrain - this._ondrain = null - if (ondrain) ondrain(err) - else this.emit('error', err) - } + yield fetcher.setupMirrorFromCache(); + return { + package: pkg, + hash, + dest, + cached: true + }; + }); - if (this._forwardDestroy) { - if (this._readable && this._readable.destroy) this._readable.destroy() - if (this._writable && this._writable.destroy) this._writable.destroy() - } + return function fetchCache(_x, _x2, _x3) { + return _ref.apply(this, arguments); + }; +})(); - this.emit('close') +let fetchOne = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (ref, config) { + const dest = config.generateHardModulePath(ref); + + const remote = ref.remote; + // Mock metedata for symlinked dependencies + if (remote.type === 'link') { + const mockPkg = { _uid: '', name: '', version: '0.0.0' }; + return Promise.resolve({ resolved: null, hash: '', dest, package: mockPkg, cached: false }); + } + + const Fetcher = (_index || _load_index())[remote.type]; + if (!Fetcher) { + throw new (_errors || _load_errors()).MessageError(config.reporter.lang('unknownFetcherFor', remote.type)); + } + + const fetcher = new Fetcher(dest, remote, config); + if (yield config.isValidModuleDest(dest)) { + return fetchCache(dest, fetcher, config); + } + + // remove as the module may be invalid + yield (_fs || _load_fs()).unlink(dest); + + try { + return yield fetcher.fetch({ + name: ref.name, + version: ref.version + }); + } catch (err) { + try { + yield (_fs || _load_fs()).unlink(dest); + } catch (err2) { + // what do? + } + throw err; + } + }); + + return function fetchOne(_x4, _x5) { + return _ref3.apply(this, arguments); + }; +})(); + +let maybeFetchOne = (() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (ref, config) { + try { + return yield fetchOne(ref, config); + } catch (err) { + if (ref.optional) { + config.reporter.error(err.message); + return null; + } else { + throw err; + } + } + }); + + return function maybeFetchOne(_x6, _x7) { + return _ref4.apply(this, arguments); + }; +})(); + +exports.fetch = fetch; + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); } -Duplexify.prototype._write = function(data, enc, cb) { - if (this.destroyed) return cb() - if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) - if (data === SIGNAL_FLUSH) return this._finish(cb) - if (!this._writable) return cb() +var _index; - if (this._writable.write(data) === false) this._ondrain = cb - else cb() +function _load_index() { + return _index = _interopRequireWildcard(__webpack_require__(412)); } +var _fs; -Duplexify.prototype._finish = function(cb) { - var self = this - this.emit('preend') - onuncork(this, function() { - end(self._forwardEnd && self._writable, function() { - // haxx to not emit prefinish twice - if (self._writableState.prefinished === false) self._writableState.prefinished = true - self.emit('prefinish') - onuncork(self, cb) - }) - }) +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } -Duplexify.prototype.end = function(data, enc, cb) { - if (typeof data === 'function') return this.end(null, null, data) - if (typeof enc === 'function') return this.end(data, null, enc) - this._ended = true - if (data) this.write(data) - if (!this._writableState.ending) this.write(SIGNAL_FLUSH) - return stream.Writable.prototype.end.call(this, cb) +var _promise; + +function _load_promise() { + return _promise = _interopRequireWildcard(__webpack_require__(53)); } -module.exports = Duplexify +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 229 */ -/***/ (function(module, exports, __webpack_require__) { +function fetch(pkgs, config) { + const pkgsPerDest = new Map(); + pkgs = pkgs.filter(pkg => { + const ref = pkg._reference; + if (!ref) { + return false; + } + const dest = config.generateHardModulePath(ref); + const otherPkg = pkgsPerDest.get(dest); + if (otherPkg) { + config.reporter.warn(config.reporter.lang('multiplePackagesCantUnpackInSameDestination', ref.patterns, dest, otherPkg.patterns)); + return false; + } + pkgsPerDest.set(dest, ref); + return true; + }); + const tick = config.reporter.progress(pkgs.length); -var crypto = __webpack_require__(7); -var BigInteger = __webpack_require__(40).BigInteger; -var ECPointFp = __webpack_require__(93).ECPointFp; -exports.ECCurves = __webpack_require__(459); + return (_promise || _load_promise()).queue(pkgs, (() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (pkg) { + const ref = pkg._reference; + if (!ref) { + return pkg; + } -// zero prepad -function unstupid(hex,len) -{ - return (hex.length >= len) ? hex : unstupid("0"+hex,len); -} + const res = yield maybeFetchOne(ref, config); + let newPkg; -exports.ECKey = function(curve, key, isPublic) -{ - var priv; - var c = curve(); - var n = c.getN(); - var bytes = Math.floor(n.bitLength()/8); + if (res) { + newPkg = res.package; - if(key) - { - if(isPublic) - { - var curve = c.getCurve(); -// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format -// var y = key.slice(bytes+1); -// this.P = new ECPointFp(curve, -// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), -// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); - this.P = curve.decodePointHex(key.toString("hex")); - }else{ - if(key.length != bytes) return false; - priv = new BigInteger(key.toString("hex"), 16); - } - }else{ - var n1 = n.subtract(BigInteger.ONE); - var r = new BigInteger(crypto.randomBytes(n.bitLength())); - priv = r.mod(n1).add(BigInteger.ONE); - this.P = c.getG().multiply(priv); - } - if(this.P) - { -// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); -// this.PublicKey = new Buffer("04"+pubhex,"hex"); - this.PublicKey = new Buffer(c.getCurve().encodeCompressedPointHex(this.P),"hex"); - } - if(priv) - { - this.PrivateKey = new Buffer(unstupid(priv.toString(16),bytes*2),"hex"); - this.deriveSharedSecret = function(key) - { - if(!key || !key.P) return false; - var S = key.P.multiply(priv); - return new Buffer(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); - } - } -} + // update with new remote + // but only if there was a hash previously as the tarball fetcher does not provide a hash. + if (ref.remote.hash) { + ref.remote.hash = res.hash; + } + } + + if (tick) { + tick(); + } + + if (newPkg) { + newPkg._reference = ref; + newPkg._remote = ref.remote; + newPkg.name = pkg.name; + newPkg.fresh = pkg.fresh; + return newPkg; + } + return pkg; + }); + return function (_x8) { + return _ref5.apply(this, arguments); + }; + })(), config.networkConcurrency); +} /***/ }), -/* 230 */ +/* 264 */ /***/ (function(module, exports, __webpack_require__) { -var once = __webpack_require__(104); +"use strict"; -var noop = function() {}; -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; +var _asyncToGenerator2; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - callback = once(callback || noop); +var _index; - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); +function _load_index() { + return _index = __webpack_require__(35); +} - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; +var _packageRequest; - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; +function _load_packageRequest() { + return _packageRequest = _interopRequireDefault(__webpack_require__(94)); +} - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; +var _normalizePattern2; - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; +function _load_normalizePattern() { + return _normalizePattern2 = __webpack_require__(30); +} - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); - }; +var _requestManager; - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +function _load_requestManager() { + return _requestManager = _interopRequireDefault(__webpack_require__(277)); +} - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } +var _blockingQueue; - if (isChildProcess(stream)) stream.on('exit', onexit); +function _load_blockingQueue() { + return _blockingQueue = _interopRequireDefault(__webpack_require__(79)); +} - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', callback); - stream.on('close', onclose); +var _lockfile; - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', callback); - stream.removeListener('close', onclose); - }; -}; +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} -module.exports = eos; +var _map; +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); +} -/***/ }), -/* 231 */ -/***/ (function(module, exports, __webpack_require__) { +var _workspaceLayout; -"use strict"; +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(80)); +} +var _resolutionMap; -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +function _load_resolutionMap() { + return _resolutionMap = _interopRequireDefault(__webpack_require__(267)); +} -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return str.replace(matchOperatorsRe, '\\$&'); -}; +const invariant = __webpack_require__(7); +const semver = __webpack_require__(22); -/***/ }), -/* 232 */ -/***/ (function(module, exports, __webpack_require__) { +class PackageResolver { + constructor(config, lockfile) { + let resolutionMap = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new (_resolutionMap || _load_resolutionMap()).default(config); -/* - * extsprintf.js: extended POSIX-style sprintf - */ + this.patternsByPackage = (0, (_map || _load_map()).default)(); + this.fetchingPatterns = (0, (_map || _load_map()).default)(); + this.fetchingQueue = new (_blockingQueue || _load_blockingQueue()).default('resolver fetching'); + this.patterns = (0, (_map || _load_map()).default)(); + this.resolutionMap = resolutionMap; + this.usedRegistries = new Set(); + this.flat = false; -var mod_assert = __webpack_require__(22); -var mod_util = __webpack_require__(2); + this.reporter = config.reporter; + this.lockfile = lockfile; + this.config = config; + this.delayedResolveQueue = []; + } -/* - * Public interface - */ -exports.sprintf = jsSprintf; + // whether the dependency graph will be flattened -/* - * Stripped down version of s[n]printf(3c). We make a best effort to throw an - * exception when given a format string we don't understand, rather than - * ignoring it, so that we won't break existing programs if/when we go implement - * the rest of this. - * - * This implementation currently supports specifying - * - field alignment ('-' flag), - * - zero-pad ('0' flag) - * - always show numeric sign ('+' flag), - * - field width - * - conversions for strings, decimal integers, and floats (numbers). - * - argument size specifiers. These are all accepted but ignored, since - * Javascript has no notion of the physical size of an argument. - * - * Everything else is currently unsupported, most notably precision, unsigned - * numbers, non-decimal numbers, and characters. - */ -function jsSprintf(fmt) -{ - var regex = [ - '([^%]*)', /* normal text */ - '%', /* start of format */ - '([\'\\-+ #0]*?)', /* flags (optional) */ - '([1-9]\\d*)?', /* width (optional) */ - '(\\.([1-9]\\d*))?', /* precision (optional) */ - '[lhjztL]*?', /* length mods (ignored) */ - '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ - ].join(''); - var re = new RegExp(regex); - var args = Array.prototype.slice.call(arguments, 1); - var flags, width, precision, conversion; - var left, pad, sign, arg, match; - var ret = ''; - var argn = 1; + // list of registries that have been used in this resolution - mod_assert.equal('string', typeof (fmt)); - while ((match = re.exec(fmt)) !== null) { - ret += match[1]; - fmt = fmt.substring(match[0].length); + // activity monitor - flags = match[2] || ''; - width = match[3] || 0; - precision = match[4] || ''; - conversion = match[6]; - left = false; - sign = false; - pad = ' '; - if (conversion == '%') { - ret += '%'; - continue; - } + // patterns we've already resolved or are in the process of resolving - if (args.length === 0) - throw (new Error('too few args to sprintf')); - arg = args.shift(); - argn++; + // TODO - if (flags.match(/[\' #]/)) - throw (new Error( - 'unsupported flags: ' + flags)); - if (precision.length > 0) - throw (new Error( - 'non-zero precision not supported')); + // manages and throttles json api http requests - if (flags.match(/-/)) - left = true; - if (flags.match(/0/)) - pad = '0'; + // list of patterns associated with a package - if (flags.match(/\+/)) - sign = true; - switch (conversion) { - case 's': - if (arg === undefined || arg === null) - throw (new Error('argument ' + argn + - ': attempted to print undefined or null ' + - 'as a string')); - ret += doPad(pad, width, left, arg.toString()); - break; + // lockfile instance which we can use to retrieve version info - case 'd': - arg = Math.floor(arg); - /*jsl:fallthru*/ - case 'f': - sign = sign && arg > 0 ? '+' : ''; - ret += sign + doPad(pad, width, left, - arg.toString()); - break; - case 'j': /* non-standard */ - if (width === 0) - width = 10; - ret += mod_util.inspect(arg, false, width); - break; + // a map of dependency patterns to packages - case 'r': /* non-standard */ - ret += dumpException(arg); - break; - default: - throw (new Error('unsupported conversion: ' + - conversion)); - } - } + // reporter instance, abstracts out display logic - ret += fmt; - return (ret); -} -function doPad(chr, width, left, str) -{ - var ret = str; + // environment specific config methods and options - while (ret.length < width) { - if (left) - ret += chr; - else - ret = chr + ret; - } - return (ret); -} - -/* - * This function dumps long stack traces for exceptions having a cause() method. - * See node-verror for an example. - */ -function dumpException(ex) -{ - var ret; + // list of packages need to be resolved later (they found a matching version in the + // resolver, but better matches can still arrive later in the resolve process) - if (!(ex instanceof Error)) - throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); - /* Note that V8 prepends "ex.stack" with ex.toString(). */ - ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; + /** + * TODO description + */ - if (ex.cause && typeof (ex.cause) === 'function') { - var cex = ex.cause(); - if (cex) { - ret += '\nCaused by: ' + dumpException(cex); - } - } + isNewPattern(pattern) { + return !!this.patterns[pattern].fresh; + } - return (ret); -} + updateManifest(ref, newPkg) { + // inherit fields + const oldPkg = this.patterns[ref.patterns[0]]; + newPkg._reference = ref; + newPkg._remote = ref.remote; + newPkg.name = oldPkg.name; + newPkg.fresh = oldPkg.fresh; + // update patterns + for (const pattern of ref.patterns) { + this.patterns[pattern] = newPkg; + } -/***/ }), -/* 233 */ -/***/ (function(module, exports, __webpack_require__) { + return Promise.resolve(); + } -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch + updateManifests(newPkgs) { + for (const newPkg of newPkgs) { + if (newPkg._reference) { + for (const pattern of newPkg._reference.patterns) { + this.patterns[pattern] = newPkg; + } + } + } -var fs = __webpack_require__(6) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync + return Promise.resolve(); + } -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __webpack_require__(475) + /** + * Given a list of patterns, dedupe them to a list of unique patterns. + */ -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} + dedupePatterns(patterns) { + const deduped = []; + const seen = new Set(); -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } + for (const pattern of patterns) { + const info = this.getResolvedPattern(pattern); + if (seen.has(info)) { + continue; + } - if (typeof cache === 'function') { - cb = cache - cache = null - } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) + seen.add(info); + deduped.push(pattern); } - }) -} -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) + return deduped; } - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } - } -} + /** + * Get a list of all manifests by topological order. + */ -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync -} + getTopologicalManifests(seedPatterns) { + const pkgs = new Set(); + const skip = new Set(); -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync -} + const add = seedPatterns => { + for (const pattern of seedPatterns) { + const pkg = this.getStrictResolvedPattern(pattern); + if (skip.has(pkg)) { + continue; + } + const ref = pkg._reference; + invariant(ref, 'expected reference'); + skip.add(pkg); + add(ref.dependencies); + pkgs.add(pkg); + } + }; -/***/ }), -/* 234 */ -/***/ (function(module, exports, __webpack_require__) { + add(seedPatterns); -exports.alphasort = alphasort -exports.alphasorti = alphasorti -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored + return pkgs; + } -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} + /** + * Get a list of all manifests by level sort order. + */ -var path = __webpack_require__(1) -var minimatch = __webpack_require__(159) -var isAbsolute = __webpack_require__(161) -var Minimatch = minimatch.Minimatch + getLevelOrderManifests(seedPatterns) { + const pkgs = new Set(); + const skip = new Set(); -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} + const add = seedPatterns => { + const refs = []; -function alphasort (a, b) { - return a.localeCompare(b) -} + for (const pattern of seedPatterns) { + const pkg = this.getStrictResolvedPattern(pattern); + if (skip.has(pkg)) { + continue; + } -function setupIgnores (self, options) { - self.ignore = options.ignore || [] + const ref = pkg._reference; + invariant(ref, 'expected reference'); - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] + refs.push(ref); + skip.add(pkg); + pkgs.add(pkg); + } - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) - } -} + for (const ref of refs) { + add(ref.dependencies); + } + }; -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } + add(seedPatterns); - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher + return pkgs; } -} -function setopts (self, pattern, options) { - if (!options) - options = {} + /** + * Get a list of all package names in the depenency graph. + */ - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") + getAllDependencyNamesByLevelOrder(seedPatterns) { + const names = new Set(); + for (const _ref of this.getLevelOrderManifests(seedPatterns)) { + const name = _ref.name; + + names.add(name); } - pattern = "**/" + pattern + return names; } - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute + /** + * Retrieve all the package info stored for this package name. + */ - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) + getAllInfoForPackageName(name) { + const patterns = this.patternsByPackage[name] || []; + const infos = []; + const seen = new Set(); - setupIgnores(self, options) + for (const pattern of patterns) { + const info = this.patterns[pattern]; + if (seen.has(info)) { + continue; + } - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd + seen.add(info); + infos.push(info); + } + + return infos; } - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") + /** + * Get a flat list of all package info. + */ - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount + getManifests() { + const infos = []; + const seen = new Set(); - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true + for (const pattern in this.patterns) { + const info = this.patterns[pattern]; + if (seen.has(info)) { + continue; + } - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} + infos.push(info); + seen.add(info); + } -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) + return infos; + } - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } + /** + * replace pattern in resolver, e.g. `name` is replaced with `name@^1.0.1` + */ + replacePattern(pattern, newPattern) { + const pkg = this.getResolvedPattern(pattern); + invariant(pkg, `missing package ${pattern}`); + const ref = pkg._reference; + invariant(ref, 'expected package reference'); + ref.patterns = [newPattern]; + this.addPattern(newPattern, pkg); + this.removePattern(pattern); } - if (!nou) - all = Object.keys(all) + /** + * Make all versions of this package resolve to it. + */ - if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) + collapseAllVersionsOfPackage(name, version) { + const patterns = this.dedupePatterns(this.patternsByPackage[name]); + const human = `${name}@${version}`; - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) + // get manifest that matches the version we're collapsing too + let collapseToReference; + let collapseToManifest; + let collapseToPattern; + for (const pattern of patterns) { + const _manifest = this.patterns[pattern]; + if (_manifest.version === version) { + collapseToReference = _manifest._reference; + collapseToManifest = _manifest; + collapseToPattern = pattern; + break; + } } - } - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) - - self.found = all -} + invariant(collapseToReference && collapseToManifest && collapseToPattern, `Couldn't find package manifest for ${human}`); -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' + for (const pattern of patterns) { + // don't touch the pattern we're collapsing to + if (pattern === collapseToPattern) { + continue; + } - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) + // remove this pattern + const ref = this.getStrictResolvedPattern(pattern)._reference; + invariant(ref, 'expected package reference'); + const refPatterns = ref.patterns.slice(); + ref.prune(); - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] + // add pattern to the manifest we're collapsing to + for (const pattern of refPatterns) { + collapseToReference.addPattern(pattern, collapseToManifest); + } } + + return collapseToPattern; } - return m -} + /** + * TODO description + */ -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) + addPattern(pattern, info) { + this.patterns[pattern] = info; + + const byName = this.patternsByPackage[info.name] = this.patternsByPackage[info.name] || []; + byName.push(pattern); } - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') + /** + * TODO description + */ - return abs -} + removePattern(pattern) { + const pkg = this.patterns[pattern]; + if (!pkg) { + return; + } + const byName = this.patternsByPackage[pkg.name]; + if (!byName) { + return; + } -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false + byName.splice(byName.indexOf(pattern), 1); + delete this.patterns[pattern]; + } - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + /** + * TODO description + */ -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false + getResolvedPattern(pattern) { + return this.patterns[pattern]; + } - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + /** + * TODO description + */ + getStrictResolvedPattern(pattern) { + const manifest = this.getResolvedPattern(pattern); + invariant(manifest, 'expected manifest'); + return manifest; + } -/***/ }), -/* 235 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * TODO description + */ -"use strict"; + getExactVersionMatch(name, version, manifest) { + const patterns = this.patternsByPackage[name]; + if (!patterns) { + return null; + } + for (const pattern of patterns) { + const info = this.getStrictResolvedPattern(pattern); + if (info.version === version) { + return info; + } + } -var fs = __webpack_require__(6) + if (manifest && (0, (_index || _load_index()).getExoticResolver)(version)) { + return this.exoticRangeMatch(patterns.map(this.getStrictResolvedPattern.bind(this)), manifest); + } -module.exports = clone(fs) - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj + return null; + } - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) + /** + * Get the manifest of the highest known version that satisfies a package range + */ - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) + getHighestRangeVersionMatch(name, range, manifest) { + const patterns = this.patternsByPackage[name]; - return copy -} + if (!patterns) { + return null; + } + const versionNumbers = []; + const resolvedPatterns = patterns.map(pattern => { + const info = this.getStrictResolvedPattern(pattern); + versionNumbers.push(info.version); -/***/ }), -/* 236 */ -/***/ (function(module, exports, __webpack_require__) { + return info; + }); -var fs = __webpack_require__(6) -var polyfills = __webpack_require__(480) -var legacy = __webpack_require__(479) -var queue = [] + const maxValidRange = semver.maxSatisfying(versionNumbers, range); -var util = __webpack_require__(2) + if (!maxValidRange) { + return manifest && (0, (_index || _load_index()).getExoticResolver)(range) ? this.exoticRangeMatch(resolvedPatterns, manifest) : null; + } -function noop () {} + const indexOfmaxValidRange = versionNumbers.indexOf(maxValidRange); + const maxValidRangeManifest = resolvedPatterns[indexOfmaxValidRange]; -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) + return maxValidRangeManifest; } -if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(queue) - __webpack_require__(22).equal(queue.length, 0) - }) -} + /** + * Get the manifest of the package that matches an exotic range + */ -module.exports = patch(__webpack_require__(235)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { - module.exports = patch(fs) -} + exoticRangeMatch(resolvedPkgs, manifest) { + const remote = manifest._remote; + if (!(remote && remote.reference && remote.type === 'copy')) { + return null; + } -// Always patch fs.close/closeSync, because we want to -// retry() whenever a close happens *anywhere* in the program. -// This is essential when multiple graceful-fs instances are -// in play at the same time. -module.exports.close = -fs.close = (function (fs$close) { return function (fd, cb) { - return fs$close.call(fs, fd, function (err) { - if (!err) - retry() + const matchedPkg = resolvedPkgs.find((_ref2) => { + let pkgRemote = _ref2._remote; + return pkgRemote && pkgRemote.reference === remote.reference && pkgRemote.type === 'copy'; + }); - if (typeof cb === 'function') - cb.apply(this, arguments) - }) -}})(fs.close) + if (matchedPkg) { + manifest._remote = matchedPkg._remote; + } -module.exports.closeSync = -fs.closeSync = (function (fs$closeSync) { return function (fd) { - // Note that graceful-fs also retries when fs.closeSync() fails. - // Looks like a bug to me, although it's probably a harmless one. - var rval = fs$closeSync.apply(fs, arguments) - retry() - return rval -}})(fs.closeSync) + return matchedPkg; + } -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - fs.FileReadStream = ReadStream; // Legacy name. - fs.FileWriteStream = WriteStream; // Legacy name. - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null + /** + * Determine if LockfileEntry is incorrect, remove it from lockfile cache and consider the pattern as new + */ + isLockfileEntryOutdated(version, range, hasVersion) { + return !!(semver.validRange(range) && semver.valid(version) && !(0, (_index || _load_index()).getExoticResolver)(range) && hasVersion && !semver.satisfies(version, range)); + } - return go$readFile(path, options, cb) + /** + * TODO description + */ - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } + find(initialReq) { + var _this = this; - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const req = _this.resolveToResolution(initialReq); - return go$writeFile(path, data, options, cb) + // we've already resolved it with a resolution + if (!req) { + return; + } - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } + const fetchKey = `${req.registry}:${req.pattern}`; - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + if (_this.fetchingPatterns[fetchKey]) { + return; + } else { + _this.fetchingPatterns[fetchKey] = true; + } - return go$appendFile(path, data, options, cb) + if (_this.activity) { + _this.activity.tick(req.pattern); + } - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } - } + const lockfileEntry = _this.lockfile.getLocked(req.pattern); + let fresh = false; - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options - } - args.push(go$readdir$cb) + if (lockfileEntry) { + var _normalizePattern = (0, (_normalizePattern2 || _load_normalizePattern()).normalizePattern)(req.pattern); - return go$readdir(args) + const range = _normalizePattern.range, + hasVersion = _normalizePattern.hasVersion; - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() + if (_this.isLockfileEntryOutdated(lockfileEntry.version, range, hasVersion)) { + _this.reporter.warn(_this.reporter.lang('incorrectLockfileEntry', req.pattern)); + _this.removePattern(req.pattern); + _this.lockfile.removePattern(req.pattern); + fresh = true; + } + } else { + fresh = true; } - } - } - function go$readdir (args) { - return fs$readdir.apply(fs, args) + const request = new (_packageRequest || _load_packageRequest()).default(req, _this); + yield request.find({ fresh, frozen: _this.frozen }); + })(); } - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } + /** + * TODO description + */ - var fs$ReadStream = fs.ReadStream - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open + init(deps) { + var _this2 = this; - var fs$WriteStream = fs.WriteStream - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open + var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { isFlat: false, isFrozen: false, workspaceLayout: undefined }; - fs.ReadStream = ReadStream - fs.WriteStream = WriteStream + let isFlat = _ref3.isFlat, + isFrozen = _ref3.isFrozen, + workspaceLayout = _ref3.workspaceLayout; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this2.flat = Boolean(isFlat); + _this2.frozen = Boolean(isFrozen); + _this2.workspaceLayout = workspaceLayout; + const activity = _this2.activity = _this2.reporter.activity(); - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } + for (const req of deps) { + yield _this2.find(req); + } - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() + // all required package versions have been discovered, so now packages that + // resolved to existing versions can be resolved to their best available version + _this2.resolvePackagesWithExistingVersions(); - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) + activity.end(); + _this2.activity = null; + })(); } - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } + /** + * Called by the package requester for packages that this resolver already had + * a matching version for. Delay the resolve, because better matches can still be + * discovered. + */ - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) + reportPackageWithExistingVersion(req, info) { + this.delayedResolveQueue.push({ req, info }); } - function createReadStream (path, options) { - return new ReadStream(path, options) - } + /** + * Executes the resolve to existing versions for packages after the find process, + * when all versions that are going to be used have been discovered. + */ - function createWriteStream (path, options) { - return new WriteStream(path, options) + resolvePackagesWithExistingVersions() { + for (const _ref4 of this.delayedResolveQueue) { + const req = _ref4.req, + info = _ref4.info; + + req.resolveToExistingVersion(info); + } } - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null + resolveToResolution(req) { + const parentNames = req.parentNames, + pattern = req.pattern; - return go$open(path, flags, mode, cb) - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) + if (!parentNames) { + return req; } - } - return fs -} + const resolution = this.resolutionMap.find(pattern, parentNames); -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - queue.push(elem) -} + if (resolution) { + const resolutionManifest = this.getStrictResolvedPattern(resolution); + invariant(resolutionManifest._reference, 'resolutions should have a resolved reference'); -function retry () { - var elem = queue.shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) + resolutionManifest._reference.patterns.push(pattern); + this.addPattern(pattern, resolutionManifest); + this.lockfile.removePattern(pattern); + + return null; + } + + return req; } } - +exports.default = PackageResolver; /***/ }), -/* 237 */ +/* 265 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _ = __webpack_require__(21); -var MuteStream = __webpack_require__(245); -var readline = __webpack_require__(115); - -/** - * Base interface class other can inherits from - */ -var UI = module.exports = function (opt) { - // Instantiate the Readline interface - // @Note: Don't reassign if already present (allow test to override the Stream) - if (!this.rl) { - this.rl = readline.createInterface(setupReadlineOptions(opt)); +Object.defineProperty(exports, "__esModule", { + value: true +}); +function formatFunction() { + for (var _len = arguments.length, strs = Array(_len), _key = 0; _key < _len; _key++) { + strs[_key] = arguments[_key]; } - this.rl.resume(); - - this.onForceClose = this.onForceClose.bind(this); - // Make sure new prompt start on a newline when closing - this.rl.on('SIGINT', this.onForceClose); - process.on('exit', this.onForceClose); -}; - -/** - * Handle the ^C exit - * @return {null} - */ + return strs.join(' '); +} -UI.prototype.onForceClose = function () { - this.close(); - console.log(''); +const defaultFormatter = exports.defaultFormatter = { + bold: formatFunction, + dim: formatFunction, + italic: formatFunction, + underline: formatFunction, + inverse: formatFunction, + strikethrough: formatFunction, + black: formatFunction, + red: formatFunction, + green: formatFunction, + yellow: formatFunction, + blue: formatFunction, + magenta: formatFunction, + cyan: formatFunction, + white: formatFunction, + gray: formatFunction, + grey: formatFunction, + stripColor: formatFunction }; -/** - * Close the interface and cleanup listeners - */ - -UI.prototype.close = function () { - // Remove events listeners - this.rl.removeListener('SIGINT', this.onForceClose); - process.removeListener('exit', this.onForceClose); - - this.rl.output.unmute(); - - if (this.activePrompt && typeof this.activePrompt.close === 'function') { - this.activePrompt.close(); - } +/***/ }), +/* 266 */ +/***/ (function(module, exports, __webpack_require__) { - // Close the readline - this.rl.output.end(); - this.rl.pause(); - this.rl.close(); -}; +"use strict"; -function setupReadlineOptions(opt) { - opt = opt || {}; - // Default `input` to stdin - var input = opt.input || process.stdin; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.en = undefined; - // Add mute capabilities to the output - var ms = new MuteStream(); - ms.pipe(opt.output || process.stdout); - var output = ms; +var _en; - return _.extend({ - terminal: true, - input: input, - output: output - }, _.omit(opt, ['input', 'output'])); +function _load_en() { + return _en = _interopRequireDefault(__webpack_require__(426)); } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +exports.en = (_en || _load_en()).default; /***/ }), -/* 238 */ +/* 267 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ansiEscapes = __webpack_require__(315); - -/** - * Move cursor left by `x` - * @param {Readline} rl - Readline instance - * @param {Number} x - How far to go left (default to 1) - */ -exports.left = function (rl, x) { - rl.output.write(ansiEscapes.cursorBackward(x)); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); -/** - * Move cursor right by `x` - * @param {Readline} rl - Readline instance - * @param {Number} x - How far to go left (default to 1) - */ +var _semver; -exports.right = function (rl, x) { - rl.output.write(ansiEscapes.cursorForward(x)); -}; +function _load_semver() { + return _semver = _interopRequireDefault(__webpack_require__(22)); +} -/** - * Move cursor up by `x` - * @param {Readline} rl - Readline instance - * @param {Number} x - How far to go up (default to 1) - */ +var _minimatch; -exports.up = function (rl, x) { - rl.output.write(ansiEscapes.cursorUp(x)); -}; +function _load_minimatch() { + return _minimatch = _interopRequireDefault(__webpack_require__(57)); +} -/** - * Move cursor down by `x` - * @param {Readline} rl - Readline instance - * @param {Number} x - How far to go down (default to 1) - */ +var _map; -exports.down = function (rl, x) { - rl.output.write(ansiEscapes.cursorDown(x)); -}; +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); +} -/** - * Clear current line - * @param {Readline} rl - Readline instance - * @param {Number} len - number of line to delete - */ -exports.clearLine = function (rl, len) { - rl.output.write(ansiEscapes.eraseLines(len)); -}; +var _normalizePattern2; +function _load_normalizePattern() { + return _normalizePattern2 = __webpack_require__(30); +} -/***/ }), -/* 239 */ -/***/ (function(module, exports, __webpack_require__) { +var _parsePackagePath; -"use strict"; -/*! - * is-number <https://github.com/jonschlinkert/is-number> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ +function _load_parsePackagePath() { + return _parsePackagePath = _interopRequireDefault(__webpack_require__(275)); +} +var _parsePackagePath2; +function _load_parsePackagePath2() { + return _parsePackagePath2 = __webpack_require__(275); +} -var typeOf = __webpack_require__(157); +var _resolvers; -module.exports = function isNumber(num) { - var type = typeOf(num); - if (type !== 'number' && type !== 'string') { - return false; - } - var n = +num; - return (n - n + 1) >= 0 && num !== ''; -}; +function _load_resolvers() { + return _resolvers = __webpack_require__(35); +} +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 240 */ -/***/ (function(module, exports, __webpack_require__) { +const DIRECTORY_SEPARATOR = '/'; +const GLOBAL_NESTED_DEP_PATTERN = '**/'; -"use strict"; -/*! - * is-primitive <https://github.com/jonschlinkert/is-primitive> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ +class ResolutionMap { + constructor(config) { + this.resolutionsByPackage = (0, (_map || _load_map()).default)(); + this.config = config; + this.reporter = config.reporter; + } + init() { + let resolutions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + for (const globPattern in resolutions) { + const info = this.parsePatternInfo(globPattern, resolutions[globPattern]); -// see http://jsperf.com/testing-value-is-primitive/7 -module.exports = function isPrimitive(value) { - return value == null || (typeof value !== 'function' && typeof value !== 'object'); -}; + if (info) { + const resolution = this.resolutionsByPackage[info.name] || []; + this.resolutionsByPackage[info.name] = [...resolution, info]; + } + } + } + parsePatternInfo(globPattern, range) { + if (!(0, (_parsePackagePath2 || _load_parsePackagePath2()).isValidPackagePath)(globPattern)) { + this.reporter.warn(this.reporter.lang('invalidResolutionName', globPattern)); + return null; + } -/***/ }), -/* 241 */ -/***/ (function(module, exports) { + const directories = (0, (_parsePackagePath || _load_parsePackagePath()).default)(globPattern); + const name = directories.pop(); -var toString = {}.toString; + if (!(_semver || _load_semver()).default.validRange(range) && !(0, (_resolvers || _load_resolvers()).getExoticResolver)(range)) { + this.reporter.warn(this.reporter.lang('invalidResolutionVersion', range)); + return null; + } -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; + // For legacy support of resolutions, replace `name` with `**/name` + if (name === globPattern) { + globPattern = `${GLOBAL_NESTED_DEP_PATTERN}${name}`; + } + return { + name, + range, + globPattern, + pattern: `${name}@${range}` + }; + } -/***/ }), -/* 242 */ -/***/ (function(module, exports, __webpack_require__) { + find(reqPattern, parentNames) { + var _normalizePattern = (0, (_normalizePattern2 || _load_normalizePattern()).normalizePattern)(reqPattern); -var stream = __webpack_require__(20) + const name = _normalizePattern.name, + reqRange = _normalizePattern.range; + const resolutions = this.resolutionsByPackage[name]; -function isStream (obj) { - return obj instanceof stream.Stream -} + if (!resolutions) { + return ''; + } + const modulePath = [...parentNames, name].join(DIRECTORY_SEPARATOR); -function isReadable (obj) { - return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' -} + var _ref = resolutions.find((_ref2) => { + let globPattern = _ref2.globPattern; + return (0, (_minimatch || _load_minimatch()).default)(modulePath, globPattern); + }) || {}; + const pattern = _ref.pattern, + range = _ref.range; -function isWritable (obj) { - return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' -} + if (pattern) { + if ((_semver || _load_semver()).default.validRange(reqRange) && (_semver || _load_semver()).default.valid(range) && !(_semver || _load_semver()).default.satisfies(range, reqRange)) { + this.reporter.warn(this.reporter.lang('incompatibleResolutionVersion', pattern, reqPattern)); + } + } -function isDuplex (obj) { - return isReadable(obj) && isWritable(obj) + return pattern; + } } - - -module.exports = isStream -module.exports.isReadable = isReadable -module.exports.isWritable = isWritable -module.exports.isDuplex = isDuplex - +exports.default = ResolutionMap; /***/ }), -/* 243 */ +/* 268 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * micromatch <https://github.com/jonschlinkert/micromatch> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); -var expand = __webpack_require__(555); -var utils = __webpack_require__(158); +var _hostedGitResolver; -/** - * The main function. Pass an array of filepaths, - * and a string or array of glob patterns - * - * @param {Array|String} `files` - * @param {Array|String} `patterns` - * @param {Object} `opts` - * @return {Array} Array of matches - */ +function _load_hostedGitResolver() { + return _hostedGitResolver = _interopRequireDefault(__webpack_require__(78)); +} -function micromatch(files, patterns, opts) { - if (!files || !patterns) return []; - opts = opts || {}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (typeof opts.cache === 'undefined') { - opts.cache = true; +class GitHubResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default { + + static isVersion(pattern) { + // github proto + if (pattern.startsWith('github:')) { + return true; + } + + // github shorthand + if (/^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(pattern)) { + return true; + } + + return false; } - if (!Array.isArray(patterns)) { - return match(files, patterns, opts); + static getTarballUrl(parts, hash) { + return `https://codeload.${this.hostname}/${parts.user}/${parts.repo}/tar.gz/${hash}`; } - var len = patterns.length, i = 0; - var omit = [], keep = []; + static getGitSSHUrl(parts) { + return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; + } - while (len--) { - var glob = patterns[i++]; - if (typeof glob === 'string' && glob.charCodeAt(0) === 33 /* ! */) { - omit.push.apply(omit, match(files, glob.slice(1), opts)); - } else { - keep.push.apply(keep, match(files, glob, opts)); - } + static getGitHTTPBaseUrl(parts) { + return `https://${this.hostname}/${parts.user}/${parts.repo}`; } - return utils.diff(keep, omit); -} -/** - * Return an array of files that match the given glob pattern. - * - * This function is called by the main `micromatch` function If you only - * need to pass a single pattern you might get very minor speed improvements - * using this function. - * - * @param {Array} `files` - * @param {String} `pattern` - * @param {Object} `options` - * @return {Array} - */ + static getGitHTTPUrl(parts) { + return `${GitHubResolver.getGitHTTPBaseUrl(parts)}.git`; + } -function match(files, pattern, opts) { - if (utils.typeOf(files) !== 'string' && !Array.isArray(files)) { - throw new Error(msg('match', 'files', 'a string or array')); + static getHTTPFileUrl(parts, filename, commit) { + return `https://raw.githubusercontent.com/${parts.user}/${parts.repo}/${commit}/${filename}`; } +} +exports.default = GitHubResolver; +GitHubResolver.protocol = 'github'; +GitHubResolver.hostname = 'github.com'; - files = utils.arrayify(files); - opts = opts || {}; +/***/ }), +/* 269 */ +/***/ (function(module, exports, __webpack_require__) { - var negate = opts.negate || false; - var orig = pattern; +"use strict"; - if (typeof pattern === 'string') { - negate = pattern.charAt(0) === '!'; - if (negate) { - pattern = pattern.slice(1); - } - // we need to remove the character regardless, - // so the above logic is still needed - if (opts.nonegate === true) { - negate = false; - } - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.LINK_PROTOCOL_PREFIX = undefined; - var _isMatch = matcher(pattern, opts); - var len = files.length, i = 0; - var res = []; +var _asyncToGenerator2; - while (i < len) { - var file = files[i++]; - var fp = utils.unixify(file, opts); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - if (!_isMatch(fp)) { continue; } - res.push(fp); - } +var _exoticResolver; - if (res.length === 0) { - if (opts.failglob === true) { - throw new Error('micromatch.match() found no matches for: "' + orig + '".'); - } +function _load_exoticResolver() { + return _exoticResolver = _interopRequireDefault(__webpack_require__(61)); +} - if (opts.nonull || opts.nullglob) { - res.push(utils.unescapeGlob(orig)); - } - } +var _misc; - // if `negate` was defined, diff negated files - if (negate) { res = utils.diff(files, res); } +function _load_misc() { + return _misc = _interopRequireWildcard(__webpack_require__(10)); +} - // if `ignore` was defined, diff ignored filed - if (opts.ignore && opts.ignore.length) { - pattern = opts.ignore; - opts = utils.omit(opts, ['ignore']); - res = utils.diff(res, micromatch(res, pattern, opts)); - } +var _fs; - if (opts.nodupes) { - return utils.unique(res); - } - return res; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } -/** - * Returns a function that takes a glob pattern or array of glob patterns - * to be used with `Array#filter()`. (Internally this function generates - * the matching function using the [matcher] method). - * - * ```js - * var fn = mm.filter('[a-c]'); - * ['a', 'b', 'c', 'd', 'e'].filter(fn); - * //=> ['a', 'b', 'c'] - * ``` - * @param {String|Array} `patterns` Can be a glob or array of globs. - * @param {Options} `opts` Options to pass to the [matcher] method. - * @return {Function} Filter function to be passed to `Array#filter()`. - */ +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -function filter(patterns, opts) { - if (!Array.isArray(patterns) && typeof patterns !== 'string') { - throw new TypeError(msg('filter', 'patterns', 'a string or array')); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - patterns = utils.arrayify(patterns); - var len = patterns.length, i = 0; - var patternMatchers = Array(len); - while (i < len) { - patternMatchers[i] = matcher(patterns[i++], opts); +const path = __webpack_require__(0); + +const LINK_PROTOCOL_PREFIX = exports.LINK_PROTOCOL_PREFIX = 'link:'; + +class LinkResolver extends (_exoticResolver || _load_exoticResolver()).default { + constructor(request, fragment) { + super(request, fragment); + this.loc = (_misc || _load_misc()).removePrefix(fragment, LINK_PROTOCOL_PREFIX); } - return function(fp) { - if (fp == null) return []; - var len = patternMatchers.length, i = 0; - var res = true; + resolve() { + var _this = this; - fp = utils.unixify(fp, opts); - while (i < len) { - var fn = patternMatchers[i++]; - if (!fn(fp)) { - res = false; - break; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let loc = _this.loc; + if (!path.isAbsolute(loc)) { + loc = path.resolve(_this.config.lockfileFolder, loc); } - } - return res; - }; -} -/** - * Returns true if the filepath contains the given - * pattern. Can also return a function for matching. - * - * ```js - * isMatch('foo.md', '*.md', {}); - * //=> true - * - * isMatch('*.md', {})('foo.md') - * //=> true - * ``` - * @param {String} `fp` - * @param {String} `pattern` - * @param {Object} `opts` - * @return {Boolean} - */ + const name = path.basename(loc); + const registry = 'npm'; -function isMatch(fp, pattern, opts) { - if (typeof fp !== 'string') { - throw new TypeError(msg('isMatch', 'filepath', 'a string')); - } + const manifest = !(yield (_fs || _load_fs()).exists(loc)) ? { _uid: '', name, version: '0.0.0', _registry: registry } : yield _this.config.readManifest(loc, _this.registry); - fp = utils.unixify(fp, opts); - if (utils.typeOf(pattern) === 'object') { - return matcher(fp, pattern); - } - return matcher(pattern, opts)(fp); -} + manifest._remote = { + type: 'link', + registry, + hash: null, + reference: loc + }; -/** - * Returns true if the filepath matches the - * given pattern. - */ + manifest._uid = manifest.version; -function contains(fp, pattern, opts) { - if (typeof fp !== 'string') { - throw new TypeError(msg('contains', 'pattern', 'a string')); + return manifest; + })(); } +} +exports.default = LinkResolver; +LinkResolver.protocol = 'link'; - opts = opts || {}; - opts.contains = (pattern !== ''); - fp = utils.unixify(fp, opts); +/***/ }), +/* 270 */ +/***/ (function(module, exports, __webpack_require__) { - if (opts.contains && !utils.isGlob(pattern)) { - return fp.indexOf(pattern) !== -1; - } - return matcher(pattern, opts)(fp); -} +"use strict"; -/** - * Returns true if a file path matches any of the - * given patterns. - * - * @param {String} `fp` The filepath to test. - * @param {String|Array} `patterns` Glob patterns to use. - * @param {Object} `opts` Options to pass to the `matcher()` function. - * @return {String} - */ -function any(fp, patterns, opts) { - if (!Array.isArray(patterns) && typeof patterns !== 'string') { - throw new TypeError(msg('any', 'patterns', 'a string or array')); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); - patterns = utils.arrayify(patterns); - var len = patterns.length; +var _npmResolver; - fp = utils.unixify(fp, opts); - while (len--) { - var isMatch = matcher(patterns[len], opts); - if (isMatch(fp)) { - return true; - } - } - return false; +function _load_npmResolver() { + return _npmResolver = _interopRequireDefault(__webpack_require__(164)); } -/** - * Filter the keys of an object with the given `glob` pattern - * and `options` - * - * @param {Object} `object` - * @param {Pattern} `object` - * @return {Array} - */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function matchKeys(obj, glob, options) { - if (utils.typeOf(obj) !== 'object') { - throw new TypeError(msg('matchKeys', 'first argument', 'an object')); - } +class YarnResolver extends (_npmResolver || _load_npmResolver()).default {} +exports.default = YarnResolver; - var fn = matcher(glob, options); - var res = {}; +/***/ }), +/* 271 */ +/***/ (function(module, exports, __webpack_require__) { - for (var key in obj) { - if (obj.hasOwnProperty(key) && fn(key)) { - res[key] = obj[key]; - } - } - return res; -} +"use strict"; -/** - * Return a function for matching based on the - * given `pattern` and `options`. - * - * @param {String} `pattern` - * @param {Object} `options` - * @return {Function} - */ -function matcher(pattern, opts) { - // pattern is a function - if (typeof pattern === 'function') { - return pattern; - } - // pattern is a regex - if (pattern instanceof RegExp) { - return function(fp) { - return pattern.test(fp); - }; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); - if (typeof pattern !== 'string') { - throw new TypeError(msg('matcher', 'pattern', 'a string, regex, or function')); +exports.default = function (from, to) { + const validFrom = (_semver || _load_semver()).default.valid(from); + const validTo = (_semver || _load_semver()).default.valid(to); + let versionBump = 'unknown'; + if (validFrom && validTo) { + versionBump = (_semver || _load_semver()).default.diff(validFrom, validTo) || 'unchanged'; } + return (_constants || _load_constants()).VERSION_COLOR_SCHEME[versionBump]; +}; - // strings, all the way down... - pattern = utils.unixify(pattern, opts); - - // pattern is a non-glob string - if (!utils.isGlob(pattern)) { - return utils.matchPath(pattern, opts); - } - // pattern is a glob string - var re = makeRe(pattern, opts); +var _semver; - // `matchBase` is defined - if (opts && opts.matchBase) { - return utils.hasFilename(re, opts); - } - // `matchBase` is not defined - return function(fp) { - fp = utils.unixify(fp, opts); - return re.test(fp); - }; +function _load_semver() { + return _semver = _interopRequireDefault(__webpack_require__(22)); } -/** - * Create and cache a regular expression for matching - * file paths. - * - * If the leading character in the `glob` is `!`, a negation - * regex is returned. - * - * @param {String} `glob` - * @param {Object} `options` - * @return {RegExp} - */ +var _constants; -function toRegex(glob, options) { - // clone options to prevent mutating the original object - var opts = Object.create(options || {}); - var flags = opts.flags || ''; - if (opts.nocase && flags.indexOf('i') === -1) { - flags += 'i'; - } +function _load_constants() { + return _constants = __webpack_require__(6); +} - var parsed = expand(glob, opts); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // pass in tokens to avoid parsing more than once - opts.negated = opts.negated || parsed.negated; - opts.negate = opts.negated; - glob = wrapGlob(parsed.pattern, opts); - var re; +/***/ }), +/* 272 */ +/***/ (function(module, exports, __webpack_require__) { - try { - re = new RegExp(glob, flags); - return re; - } catch (err) { - err.reason = 'micromatch invalid regex: (' + re + ')'; - if (opts.strict) throw new SyntaxError(err); - } +"use strict"; - // we're only here if a bad pattern was used and the user - // passed `options.silent`, so match nothing - return /$^/; -} -/** - * Create the regex to do the matching. If the leading - * character in the `glob` is `!` a negation regex is returned. - * - * @param {String} `glob` - * @param {Boolean} `negate` - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); -function wrapGlob(glob, opts) { - var prefix = (opts && !opts.contains) ? '^' : ''; - var after = (opts && !opts.contains) ? '$' : ''; - glob = ('(?:' + glob + ')' + after); - if (opts && opts.negate) { - return prefix + ('(?!^' + glob + ').*$'); - } - return prefix + glob; -} +exports.default = function (from, to, reporter) { + const parts = to.split('.'); + const fromParts = from.split('.'); -/** - * Create and cache a regular expression for matching file paths. - * If the leading character in the `glob` is `!`, a negation - * regex is returned. - * - * @param {String} `glob` - * @param {Object} `options` - * @return {RegExp} - */ + const index = parts.findIndex((part, i) => part !== fromParts[i]); + const splitIndex = index >= 0 ? index : parts.length; -function makeRe(glob, opts) { - if (utils.typeOf(glob) !== 'string') { - throw new Error(msg('makeRe', 'glob', 'a string')); - } - return utils.cache(toRegex, glob, opts); -} + const colorized = reporter.format.green(parts.slice(splitIndex).join('.')); + return parts.slice(0, splitIndex).concat(colorized).join('.'); +}; -/** - * Make error messages consistent. Follows this format: - * - * ```js - * msg(methodName, argNumber, nativeType); - * // example: - * msg('matchKeys', 'first', 'an object'); - * ``` - * - * @param {String} `method` - * @param {String} `num` - * @param {String} `type` - * @return {String} - */ +/***/ }), +/* 273 */ +/***/ (function(module, exports, __webpack_require__) { -function msg(method, what, type) { - return 'micromatch.' + method + '(): ' + what + ' should be ' + type + '.'; -} +"use strict"; -/** - * Public methods - */ - -/* eslint no-multi-spaces: 0 */ -micromatch.any = any; -micromatch.braces = micromatch.braceExpand = utils.braces; -micromatch.contains = contains; -micromatch.expand = expand; -micromatch.filter = filter; -micromatch.isMatch = isMatch; -micromatch.makeRe = makeRe; -micromatch.match = match; -micromatch.matcher = matcher; -micromatch.matchKeys = matchKeys; - -/** - * Expose `micromatch` - */ - -module.exports = micromatch; - - -/***/ }), -/* 244 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sortFilter = sortFilter; +exports.matchesFilter = matchesFilter; +exports.ignoreLinesToRegex = ignoreLinesToRegex; +exports.filterOverridenGitignores = filterOverridenGitignores; +var _misc; -/** - * Module dependencies. - * @private - */ +function _load_misc() { + return _misc = __webpack_require__(10); +} -var db = __webpack_require__(558) -var extname = __webpack_require__(1).extname +const mm = __webpack_require__(219); +const path = __webpack_require__(0); -/** - * Module variables. - * @private - */ +const WHITESPACE_RE = /^\s+$/; -var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/ -var textTypeRegExp = /^text\//i +function sortFilter(files, filters) { + let keepFiles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Set(); + let possibleKeepFiles = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new Set(); + let ignoreFiles = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : new Set(); -/** - * Module exports. - * @public - */ + for (const file of files) { + let keep = false; -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) + // always keep a file if a ! pattern matches it + for (const filter of filters) { + if (filter.isNegation && matchesFilter(filter, file.basename, file.relative)) { + keep = true; + break; + } + } -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) + // + if (keep) { + keepFiles.add(file.relative); + continue; + } -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ + // otherwise don't keep it if a pattern matches it + keep = true; + for (const filter of filters) { + if (!filter.isNegation && matchesFilter(filter, file.basename, file.relative)) { + keep = false; + break; + } + } -function charset (type) { - if (!type || typeof type !== 'string') { - return false + if (keep) { + possibleKeepFiles.add(file.relative); + } else { + ignoreFiles.add(file.relative); + } } - // TODO: use media-typer - var match = extractTypeRegExp.exec(type) - var mime = match && db[match[1].toLowerCase()] + // exclude file + for (const file of possibleKeepFiles) { + const parts = path.dirname(file).split(path.sep); - if (mime && mime.charset) { - return mime.charset + while (parts.length) { + const folder = parts.join(path.sep); + if (ignoreFiles.has(folder)) { + ignoreFiles.add(file); + break; + } + parts.pop(); + } } - // default text/* to utf-8 - if (match && textTypeRegExp.test(match[1])) { - return 'UTF-8' + // + for (const file of possibleKeepFiles) { + if (!ignoreFiles.has(file)) { + keepFiles.add(file); + } } - return false -} - -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ + // + for (const file of keepFiles) { + const parts = path.dirname(file).split(path.sep); -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false + while (parts.length) { + // deregister this folder from being ignored, any files inside + // will still be marked as ignored + ignoreFiles.delete(parts.join(path.sep)); + parts.pop(); + } } - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str + return { ignoreFiles, keepFiles }; +} - if (!mime) { - return false +function matchesFilter(filter, basename, loc) { + if (filter.base && filter.base !== '.') { + loc = path.relative(filter.base, loc); } + return filter.regex.test(loc) || filter.regex.test(`/${loc}`) || filter.regex.test(basename) || mm.isMatch(loc, filter.pattern); +} - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } +function ignoreLinesToRegex(lines) { + let base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.'; - return mime -} + return lines + // create regex + .map(line => { + // remove empty lines, comments, etc + if (line === '' || line === '!' || line[0] === '#' || WHITESPACE_RE.test(line)) { + return null; + } -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ + let pattern = line; + let isNegation = false; -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } + // hide the fact that it's a negation from minimatch since we'll handle this specifically + // ourselves + if (pattern[0] === '!') { + isNegation = true; + pattern = pattern.slice(1); + } - // TODO: use media-typer - var match = extractTypeRegExp.exec(type) + // remove trailing slash + pattern = (0, (_misc || _load_misc()).removeSuffix)(pattern, '/'); - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] + const regex = mm.makeRe(pattern.trim(), { nocase: true }); - if (!exts || !exts.length) { - return false - } + if (regex) { + return { + base, + isNegation, + pattern, + regex + }; + } else { + return null; + } + }).filter(Boolean); +} - return exts[0] +function filterOverridenGitignores(files) { + const IGNORE_FILENAMES = ['.yarnignore', '.npmignore', '.gitignore']; + const GITIGNORE_NAME = IGNORE_FILENAMES[2]; + return files.filter(file => IGNORE_FILENAMES.indexOf(file.basename) > -1).reduce((acc, file) => { + if (file.basename !== GITIGNORE_NAME) { + return [...acc, file]; + } else { + //don't include .gitignore if .npmignore or .yarnignore are present + const dir = path.dirname(file.absolute); + const higherPriorityIgnoreFilePaths = [`${dir}/${IGNORE_FILENAMES[0]}`, `${dir}/${IGNORE_FILENAMES[1]}`]; + const hasHigherPriorityFiles = files.find(file => higherPriorityIgnoreFilePaths.indexOf(file.absolute) > -1); + if (!hasHigherPriorityFiles) { + return [...acc, file]; + } + } + return acc; + }, []); } -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ +/***/ }), +/* 274 */ +/***/ (function(module, exports, __webpack_require__) { -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } +"use strict"; - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - if (!extension) { - return false - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.spawn = undefined; - return exports.types[extension] || false +var _extends2; + +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); } -/** - * Populate the extensions and types maps. - * @private - */ +var _path; -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] +function _load_path() { + return _path = _interopRequireDefault(__webpack_require__(0)); +} - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions +var _child; - if (!exts || !exts.length) { - return - } +function _load_child() { + return _child = _interopRequireWildcard(__webpack_require__(48)); +} - // mime -> extensions - extensions[type] = exts +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) +const BATCH_MODE_ARGS = new Map([['ssh', '-oBatchMode=yes'], ['plink', '-batch']]); - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } +// Suppress any password prompts since we run these in the background +const env = (0, (_extends2 || _load_extends()).default)({ + GIT_ASKPASS: '', + GIT_TERMINAL_PROMPT: 0 +}, process.env); - // set the extension -> mime - types[extension] = type - } - }) +const sshCommand = env.GIT_SSH || 'ssh'; +const sshExecutable = (_path || _load_path()).default.basename(sshCommand.toLowerCase(), '.exe'); +const sshBatchArgs = BATCH_MODE_ARGS.get(sshExecutable); + +if (!env.GIT_SSH_COMMAND && sshBatchArgs) { + env.GIT_SSH_COMMAND = `"${sshCommand}" ${sshBatchArgs}`; } +const spawn = exports.spawn = function (args) { + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + return (_child || _load_child()).spawn('git', args, (0, (_extends2 || _load_extends()).default)({}, opts, { env })); +}; /***/ }), -/* 245 */ +/* 275 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(20) +"use strict"; -module.exports = MuteStream -// var out = new MuteStream(process.stdout) -// argument auto-pipes -function MuteStream (opts) { - Stream.apply(this) - opts = opts || {} - this.writable = this.readable = true - this.muted = false - this.on('pipe', this._onpipe) - this.replace = opts.replace +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = parsePackagePath; +exports.isValidPackagePath = isValidPackagePath; - // For readline-type situations - // This much at the start of a line being redrawn after a ctrl char - // is seen (such as backspace) won't be redrawn as the replacement - this._prompt = opts.prompt || null - this._hadControl = false -} -MuteStream.prototype = Object.create(Stream.prototype) +/** + * Parse input strings like `package-1/package-2` to an array of packages + */ +function parsePackagePath(input) { + return input.match(/(@[^\/]+\/)?([^/]+)/g) || []; +} -Object.defineProperty(MuteStream.prototype, 'constructor', { - value: MuteStream, - enumerable: false -}) +const WRONG_PATTERNS = /\/$|\/{2,}|\*+$/; -MuteStream.prototype.mute = function () { - this.muted = true +function isValidPackagePath(input) { + return !WRONG_PATTERNS.test(input); } -MuteStream.prototype.unmute = function () { - this.muted = false +/***/ }), +/* 276 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getPosixPath = getPosixPath; +exports.expandPath = expandPath; +exports.resolveWithHome = resolveWithHome; + +var _path; + +function _load_path() { + return _path = __webpack_require__(0); } -Object.defineProperty(MuteStream.prototype, '_onpipe', { - value: onPipe, - enumerable: false, - writable: true, - configurable: true -}) +const userHome = __webpack_require__(62).default; -function onPipe (src) { - this._src = src +function getPosixPath(path) { + return path.replace(/\\/g, '/'); } -Object.defineProperty(MuteStream.prototype, 'isTTY', { - get: getIsTTY, - set: setIsTTY, - enumerable: true, - configurable: true -}) +function expandPath(path) { + if (process.platform !== 'win32') { + path = path.replace(/^\s*~(?=$|\/|\\)/, userHome); + } -function getIsTTY () { - return( (this._dest) ? this._dest.isTTY - : (this._src) ? this._src.isTTY - : false - ) + return path; } -// basically just get replace the getter/setter with a regular value -function setIsTTY (isTTY) { - Object.defineProperty(this, 'isTTY', { - value: isTTY, - enumerable: true, - writable: true, - configurable: true - }) +function resolveWithHome(path) { + const homePattern = process.platform === 'win32' ? /^~(\/|\\)/ : /^~\//; + if (path.match(homePattern)) { + return (0, (_path || _load_path()).resolve)(userHome, path.substr(2)); + } + + return (0, (_path || _load_path()).resolve)(path); } -Object.defineProperty(MuteStream.prototype, 'rows', { - get: function () { - return( this._dest ? this._dest.rows - : this._src ? this._src.rows - : undefined ) - }, enumerable: true, configurable: true }) +/***/ }), +/* 277 */ +/***/ (function(module, exports, __webpack_require__) { -Object.defineProperty(MuteStream.prototype, 'columns', { - get: function () { - return( this._dest ? this._dest.columns - : this._src ? this._src.columns - : undefined ) - }, enumerable: true, configurable: true }) +"use strict"; -MuteStream.prototype.pipe = function (dest, options) { - this._dest = dest - return Stream.prototype.pipe.call(this, dest, options) -} +Object.defineProperty(exports, "__esModule", { + value: true +}); -MuteStream.prototype.pause = function () { - if (this._src) return this._src.pause() -} +var _errors; -MuteStream.prototype.resume = function () { - if (this._src) return this._src.resume() +function _load_errors() { + return _errors = __webpack_require__(3); } -MuteStream.prototype.write = function (c) { - if (this.muted) { - if (!this.replace) return true - if (c.match(/^\u001b/)) { - if(c.indexOf(this._prompt) === 0) { - c = c.substr(this._prompt.length); - c = c.replace(/./g, this.replace); - c = this._prompt + c; - } - this._hadControl = true - return this.emit('data', c) - } else { - if (this._prompt && this._hadControl && - c.indexOf(this._prompt) === 0) { - this._hadControl = false - this.emit('data', this._prompt) - c = c.substr(this._prompt.length) - } - c = c.toString().replace(/./g, this.replace) - } - } - this.emit('data', c) -} +var _blockingQueue; -MuteStream.prototype.end = function (c) { - if (this.muted) { - if (c && this.replace) { - c = c.toString().replace(/./g, this.replace) - } else { - c = null - } - } - if (c) this.emit('data', c) - this.emit('end') +function _load_blockingQueue() { + return _blockingQueue = _interopRequireDefault(__webpack_require__(79)); } -function proxy (fn) { return function () { - var d = this._dest - var s = this._src - if (d && d[fn]) d[fn].apply(d, arguments) - if (s && s[fn]) s[fn].apply(s, arguments) -}} +var _constants; -MuteStream.prototype.destroy = proxy('destroy') -MuteStream.prototype.destroySoon = proxy('destroySoon') -MuteStream.prototype.close = proxy('close') +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} +var _network; -/***/ }), -/* 246 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_network() { + return _network = _interopRequireWildcard(__webpack_require__(233)); +} -module.exports = __webpack_require__(561); +var _map; -/***/ }), -/* 247 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); +} -var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory){ - 'use strict'; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - /*istanbul ignore next:cant test*/ - if (typeof module === 'object' && typeof module.exports === 'object') { - module.exports = factory(); - } else if (true) { - // AMD. Register as an anonymous module. - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), - __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? - (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else { - // Browser globals - root.objectPath = factory(); - } -})(this, function(){ - 'use strict'; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var toStr = Object.prototype.toString; - function hasOwnProperty(obj, prop) { - if(obj == null) { - return false - } - //to handle objects with null prototypes (too edge case?) - return Object.prototype.hasOwnProperty.call(obj, prop) - } +const RequestCaptureHar = __webpack_require__(602); +const invariant = __webpack_require__(7); +const url = __webpack_require__(14); +const fs = __webpack_require__(5); - function isEmpty(value){ - if (!value) { - return true; - } - if (isArray(value) && value.length === 0) { - return true; - } else if (typeof value !== 'string') { - for (var i in value) { - if (hasOwnProperty(value, i)) { - return false; - } - } - return true; - } - return false; - } +const successHosts = (0, (_map || _load_map()).default)(); +const controlOffline = (_network || _load_network()).isOffline(); - function toString(type){ - return toStr.call(type); +class RequestManager { + constructor(reporter) { + this.offlineNoRequests = false; + this._requestCaptureHar = null; + this._requestModule = null; + this.offlineQueue = []; + this.captureHar = false; + this.httpsProxy = null; + this.ca = null; + this.httpProxy = null; + this.strictSSL = true; + this.userAgent = ''; + this.reporter = reporter; + this.running = 0; + this.queue = []; + this.cache = {}; + this.max = (_constants || _load_constants()).NETWORK_CONCURRENCY; + this.maxRetryAttempts = 5; } - function isObject(obj){ - return typeof obj === 'object' && toString(obj) === "[object Object]"; - } + setOptions(opts) { + if (opts.userAgent != null) { + this.userAgent = opts.userAgent; + } - var isArray = Array.isArray || function(obj){ - /*istanbul ignore next:cant test*/ - return toStr.call(obj) === '[object Array]'; - } + if (opts.offline != null) { + this.offlineNoRequests = opts.offline; + } - function isBoolean(obj){ - return typeof obj === 'boolean' || toString(obj) === '[object Boolean]'; - } + if (opts.captureHar != null) { + this.captureHar = opts.captureHar; + } - function getKey(key){ - var intKey = parseInt(key); - if (intKey.toString() === key) { - return intKey; + if (opts.httpProxy != null) { + this.httpProxy = opts.httpProxy; } - return key; - } - function factory(options) { - options = options || {} + if (opts.httpsProxy != null) { + this.httpsProxy = opts.httpsProxy; + } - var objectPath = function(obj) { - return Object.keys(objectPath).reduce(function(proxy, prop) { - if(prop === 'create') { - return proxy; - } + if (opts.strictSSL !== null && typeof opts.strictSSL !== 'undefined') { + this.strictSSL = opts.strictSSL; + } - /*istanbul ignore else*/ - if (typeof objectPath[prop] === 'function') { - proxy[prop] = objectPath[prop].bind(objectPath, obj); - } + if (opts.ca != null && opts.ca.length > 0) { + this.ca = opts.ca; + } - return proxy; - }, {}); - }; + if (opts.networkConcurrency != null) { + this.max = opts.networkConcurrency; + } - function hasShallowProperty(obj, prop) { - return (options.includeInheritedProps || (typeof prop === 'number' && Array.isArray(obj)) || hasOwnProperty(obj, prop)) + if (opts.networkTimeout != null) { + this.timeout = opts.networkTimeout; } - function getShallowProperty(obj, prop) { - if (hasShallowProperty(obj, prop)) { - return obj[prop]; - } + if (opts.maxRetryAttempts != null) { + this.maxRetryAttempts = opts.maxRetryAttempts; } - function set(obj, path, value, doNotReplace){ - if (typeof path === 'number') { - path = [path]; - } - if (!path || path.length === 0) { - return obj; - } - if (typeof path === 'string') { - return set(obj, path.split('.').map(getKey), value, doNotReplace); - } - var currentPath = path[0]; - var currentValue = getShallowProperty(obj, currentPath); - if (path.length === 1) { - if (currentValue === void 0 || !doNotReplace) { - obj[currentPath] = value; - } - return currentValue; + if (opts.cafile != null && opts.cafile != '') { + // The CA bundle file can contain one or more certificates with comments/text between each PEM block. + // tls.connect wants an array of certificates without any comments/text, so we need to split the string + // and strip out any text in between the certificates + try { + const bundle = fs.readFileSync(opts.cafile).toString(); + const hasPemPrefix = block => block.startsWith('-----BEGIN '); + // opts.cafile overrides opts.ca, this matches with npm behavior + this.ca = bundle.split(/(-----BEGIN .*\r?\n[^-]+\r?\n--.*)/).filter(hasPemPrefix); + } catch (err) { + this.reporter.error(`Could not open cafile: ${err.message}`); } + } - if (currentValue === void 0) { - //check if we assume an array - if(typeof path[1] === 'number') { - obj[currentPath] = []; - } else { - obj[currentPath] = {}; - } - } + if (opts.cert != null) { + this.cert = opts.cert; + } - return set(obj[currentPath], path.slice(1), value, doNotReplace); + if (opts.key != null) { + this.key = opts.key; } + } - objectPath.has = function (obj, path) { - if (typeof path === 'number') { - path = [path]; - } else if (typeof path === 'string') { - path = path.split('.'); - } + /** + * Lazy load `request` since it is exceptionally expensive to load and is + * often not needed at all. + */ - if (!path || path.length === 0) { - return !!obj; + _getRequestModule() { + if (!this._requestModule) { + const request = __webpack_require__(603); + if (this.captureHar) { + this._requestCaptureHar = new RequestCaptureHar(request); + this._requestModule = this._requestCaptureHar.request.bind(this._requestCaptureHar); + } else { + this._requestModule = request; } + } + return this._requestModule; + } - for (var i = 0; i < path.length; i++) { - var j = getKey(path[i]); + /** + * Queue up a request. + */ - if((typeof j === 'number' && isArray(obj) && j < obj.length) || - (options.includeInheritedProps ? (j in Object(obj)) : hasOwnProperty(obj, j))) { - obj = obj[j]; - } else { - return false; - } - } + request(params) { + if (this.offlineNoRequests) { + return Promise.reject(new (_errors || _load_errors()).MessageError(this.reporter.lang('cantRequestOffline', params.url))); + } - return true; - }; + const cached = this.cache[params.url]; + if (cached) { + return cached; + } - objectPath.ensureExists = function (obj, path, value){ - return set(obj, path, value, true); - }; + params.method = params.method || 'GET'; + params.forever = true; + params.retryAttempts = 0; + params.strictSSL = this.strictSSL; + params.headers = Object.assign({ + 'User-Agent': this.userAgent + }, params.headers); - objectPath.set = function (obj, path, value, doNotReplace){ - return set(obj, path, value, doNotReplace); - }; + const promise = new Promise((resolve, reject) => { + this.queue.push({ params, reject, resolve }); + this.shiftQueue(); + }); - objectPath.insert = function (obj, path, value, at){ - var arr = objectPath.get(obj, path); - at = ~~at; - if (!isArray(arr)) { - arr = []; - objectPath.set(obj, path, arr); - } - arr.splice(at, 0, value); - }; + // we can't cache a request with a processor + if (!params.process) { + this.cache[params.url] = promise; + } - objectPath.empty = function(obj, path) { - if (isEmpty(path)) { - return void 0; - } - if (obj == null) { - return void 0; - } + return promise; + } - var value, i; - if (!(value = objectPath.get(obj, path))) { - return void 0; - } + /** + * Clear the request cache. This is important as we cache all HTTP requests so you'll + * want to do this as soon as you can. + */ - if (typeof value === 'string') { - return objectPath.set(obj, path, ''); - } else if (isBoolean(value)) { - return objectPath.set(obj, path, false); - } else if (typeof value === 'number') { - return objectPath.set(obj, path, 0); - } else if (isArray(value)) { - value.length = 0; - } else if (isObject(value)) { - for (i in value) { - if (hasShallowProperty(value, i)) { - delete value[i]; - } - } - } else { - return objectPath.set(obj, path, null); - } - }; + clearCache() { + this.cache = {}; + if (this._requestCaptureHar != null) { + this._requestCaptureHar.clear(); + } + } - objectPath.push = function (obj, path /*, values */){ - var arr = objectPath.get(obj, path); - if (!isArray(arr)) { - arr = []; - objectPath.set(obj, path, arr); - } + /** + * Check if an error is possibly due to lost or poor network connectivity. + */ - arr.push.apply(arr, Array.prototype.slice.call(arguments, 2)); - }; + isPossibleOfflineError(err) { + const code = err.code, + hostname = err.hostname; - objectPath.coalesce = function (obj, paths, defaultValue) { - var value; + if (!code) { + return false; + } - for (var i = 0, len = paths.length; i < len; i++) { - if ((value = objectPath.get(obj, paths[i])) !== void 0) { - return value; - } - } + // network was previously online but now we're offline + const possibleOfflineChange = !controlOffline && !(_network || _load_network()).isOffline(); + if (code === 'ENOTFOUND' && possibleOfflineChange) { + // can't resolve a domain + return true; + } - return defaultValue; - }; + // used to be able to resolve this domain! something is wrong + if (code === 'ENOTFOUND' && hostname && successHosts[hostname]) { + // can't resolve this domain but we've successfully resolved it before + return true; + } - objectPath.get = function (obj, path, defaultValue){ - if (typeof path === 'number') { - path = [path]; - } - if (!path || path.length === 0) { - return obj; - } - if (obj == null) { - return defaultValue; - } - if (typeof path === 'string') { - return objectPath.get(obj, path.split('.'), defaultValue); - } + // network was previously offline and we can't resolve the domain + if (code === 'ENOTFOUND' && controlOffline) { + return true; + } - var currentPath = getKey(path[0]); - var nextObj = getShallowProperty(obj, currentPath) - if (nextObj === void 0) { - return defaultValue; - } + // connection was reset or dropped + if (code === 'ECONNRESET') { + return true; + } - if (path.length === 1) { - return nextObj; - } + // TCP timeout + if (code === 'ESOCKETTIMEDOUT') { + return true; + } - return objectPath.get(obj[currentPath], path.slice(1), defaultValue); - }; + return false; + } - objectPath.del = function del(obj, path) { - if (typeof path === 'number') { - path = [path]; - } + /** + * Queue up request arguments to be retried. Start a network connectivity timer if there + * isn't already one. + */ - if (obj == null) { - return obj; - } + queueForOffline(opts) { + if (!this.offlineQueue.length) { + this.reporter.warn(this.reporter.lang('offlineRetrying')); + this.initOfflineRetry(); + } - if (isEmpty(path)) { - return obj; - } - if(typeof path === 'string') { - return objectPath.del(obj, path.split('.')); - } + this.offlineQueue.push(opts); + } - var currentPath = getKey(path[0]); - if (!hasShallowProperty(obj, currentPath)) { - return obj; - } + /** + * Begin timers to retry failed requests when we possibly establish network connectivity + * again. + */ - if(path.length === 1) { - if (isArray(obj)) { - obj.splice(currentPath, 1); - } else { - delete obj[currentPath]; - } - } else { - return objectPath.del(obj[currentPath], path.slice(1)); + initOfflineRetry() { + setTimeout(() => { + const queue = this.offlineQueue; + this.offlineQueue = []; + for (const opts of queue) { + this.execute(opts); } - - return obj; - } - - return objectPath; + }, 3000); } - var mod = factory(); - mod.create = factory; - mod.withInheritedProps = factory({includeInheritedProps: true}) - return mod; -}); + /** + * Execute a request. + */ + execute(opts) { + const params = opts.params; + const reporter = this.reporter; -/***/ }), -/* 248 */ -/***/ (function(module, exports, __webpack_require__) { -var once = __webpack_require__(104) -var eos = __webpack_require__(230) -var fs = __webpack_require__(6) // we only need fs to get the ReadStream and WriteStream prototypes + const buildNext = fn => data => { + fn(data); + this.running--; + this.shiftQueue(); + }; -var noop = function () {} + const resolve = buildNext(opts.resolve); -var isFn = function (fn) { - return typeof fn === 'function' -} + const rejectNext = buildNext(opts.reject); + const reject = function (err) { + err.message = `${params.url}: ${err.message}`; + rejectNext(err); + }; -var isFS = function (stream) { - if (!fs) return false // browser - return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) -} + let calledOnError = false; + const onError = err => { + if (calledOnError) { + return; + } + calledOnError = true; -var isRequest = function (stream) { - return stream.setHeader && isFn(stream.abort) -} + const attempts = params.retryAttempts || 0; + if (attempts < this.maxRetryAttempts - 1 && this.isPossibleOfflineError(err)) { + params.retryAttempts = attempts + 1; + if (typeof params.cleanup === 'function') { + params.cleanup(); + } + this.queueForOffline(opts); + } else { + reject(err); + } + }; -var destroyer = function (stream, reading, writing, callback) { - callback = once(callback) + if (!params.process) { + const parts = url.parse(params.url); - var closed = false - stream.on('close', function () { - closed = true - }) + params.callback = (err, res, body) => { + if (err) { + onError(err); + return; + } - eos(stream, {readable: reading, writable: writing}, function (err) { - if (err) return callback(err) - closed = true - callback() - }) + successHosts[parts.hostname] = true; - var destroyed = false - return function (err) { - if (closed) return - if (destroyed) return - destroyed = true + this.reporter.verbose(this.reporter.lang('verboseRequestFinish', params.url, res.statusCode)); - if (isFS(stream)) return stream.close() // use close for fs streams to avoid fd leaks - if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + if (body && typeof body.error === 'string') { + reject(new Error(body.error)); + return; + } - if (isFn(stream.destroy)) return stream.destroy() + if (res.statusCode === 403) { + const errMsg = body && body.message || reporter.lang('requestError', params.url, res.statusCode); + reject(new Error(errMsg)); + } else { + if (res.statusCode === 400 || res.statusCode === 404 || res.statusCode === 401) { + body = false; + } + resolve(body); + } + }; + } - callback(err || new Error('stream was destroyed')) - } -} + if (params.buffer) { + params.encoding = null; + } -var call = function (fn) { - fn() -} + let proxy = this.httpProxy; + if (params.url.startsWith('https:')) { + proxy = this.httpsProxy || proxy; + } + if (proxy) { + params.proxy = proxy; + } -var pipe = function (from, to) { - return from.pipe(to) -} + if (this.ca != null) { + params.ca = this.ca; + } -var pump = function () { - var streams = Array.prototype.slice.call(arguments) - var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop + if (this.cert != null) { + params.cert = this.cert; + } - if (Array.isArray(streams[0])) streams = streams[0] - if (streams.length < 2) throw new Error('pump requires two streams per minimum') + if (this.key != null) { + params.key = this.key; + } - var error - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1 - var writing = i > 0 - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err - if (err) destroys.forEach(call) - if (reading) return - destroys.forEach(call) - callback(error) - }) - }) + if (this.timeout != null) { + params.timeout = this.timeout; + } - return streams.reduce(pipe) -} + const request = this._getRequestModule(); + const req = request(params); + this.reporter.verbose(this.reporter.lang('verboseRequestStart', params.method, params.url)); -module.exports = pump + req.on('error', onError); + const queue = params.queue; + if (queue) { + req.on('data', queue.stillActive.bind(queue)); + } -/***/ }), -/* 249 */ -/***/ (function(module, exports, __webpack_require__) { + if (params.process) { + params.process(req, resolve, reject); + } + } -"use strict"; + /** + * Remove an item from the queue. Create it's request options and execute it. + */ + shiftQueue() { + if (this.running >= this.max || !this.queue.length) { + return; + } -var replace = String.prototype.replace; -var percentTwenties = /%20/g; + const opts = this.queue.shift(); -module.exports = { - 'default': 'RFC3986', - formatters: { - RFC1738: function (value) { - return replace.call(value, percentTwenties, '+'); - }, - RFC3986: function (value) { - return value; - } - }, - RFC1738: 'RFC1738', - RFC3986: 'RFC3986' -}; + this.running++; + this.execute(opts); + } + saveHar(filename) { + if (!this.captureHar) { + throw new Error(this.reporter.lang('requestManagerNotSetupHAR')); + } + // No request may have occurred at all. + this._getRequestModule(); + invariant(this._requestCaptureHar != null, 'request-capture-har not setup'); + this._requestCaptureHar.saveHar(filename); + } +} +exports.default = RequestManager; /***/ }), -/* 250 */ +/* 278 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var stringify = __webpack_require__(576); -var parse = __webpack_require__(575); -var formats = __webpack_require__(249); - -module.exports = { - formats: formats, - parse: parse, - stringify: stringify -}; +var crypto_hash_sha512 = __webpack_require__(146).lowlevel.crypto_hash; +/* + * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a + * result, it retains the original copyright and license. The two files are + * under slightly different (but compatible) licenses, and are here combined in + * one file. + * + * Credit for the actual porting work goes to: + * Devi Mandiri <me@devi.web.id> + */ -/***/ }), -/* 251 */ -/***/ (function(module, exports, __webpack_require__) { +/* + * The Blowfish portions are under the following license: + * + * Blowfish block cipher for OpenBSD + * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de> + * All rights reserved. + * + * Implementation advice by David Mazieres <dm@lcs.mit.edu>. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ -"use strict"; +/* + * The bcrypt_pbkdf portions are under the following license: + * + * Copyright (c) 2013 Ted Unangst <tedu@openbsd.org> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ +/* + * Performance improvements (Javascript-specific): + * + * Copyright 2016, Joyent Inc + * Author: Alex Wilson <alex.wilson@joyent.com> + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ -var has = Object.prototype.hasOwnProperty; +// Ported from OpenBSD bcrypt_pbkdf.c v1.9 -var hexTable = (function () { - var array = []; - for (var i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); - } +var BLF_J = 0; - return array; -}()); +var Blowfish = function() { + this.S = [ + new Uint32Array([ + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, + 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, + 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, + 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, + 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, + 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, + 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, + 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, + 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, + 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, + 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, + 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, + 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, + 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, + 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, + 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, + 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, + 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, + 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, + 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, + 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, + 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]), + new Uint32Array([ + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, + 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, + 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, + 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, + 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, + 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, + 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, + 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, + 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, + 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, + 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, + 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, + 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, + 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, + 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, + 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, + 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, + 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, + 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, + 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, + 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, + 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]), + new Uint32Array([ + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, + 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, + 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, + 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, + 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, + 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, + 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, + 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, + 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, + 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, + 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, + 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, + 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, + 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, + 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, + 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, + 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, + 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, + 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, + 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, + 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, + 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, + 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]), + new Uint32Array([ + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, + 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, + 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, + 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, + 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, + 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, + 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, + 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, + 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, + 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, + 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, + 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, + 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, + 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, + 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, + 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, + 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, + 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, + 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, + 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, + 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, + 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6]) + ]; + this.P = new Uint32Array([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b]); +}; -exports.arrayToObject = function (source, options) { - var obj = options && options.plainObjects ? Object.create(null) : {}; - for (var i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; - } - } +function F(S, x8, i) { + return (((S[0][x8[i+3]] + + S[1][x8[i+2]]) ^ + S[2][x8[i+1]]) + + S[3][x8[i]]); +}; - return obj; +Blowfish.prototype.encipher = function(x, x8) { + if (x8 === undefined) { + x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + } + x[0] ^= this.P[0]; + for (var i = 1; i < 16; i += 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i+1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[17]; + x[1] = t; }; -exports.merge = function (target, source, options) { - if (!source) { - return target; - } +Blowfish.prototype.decipher = function(x) { + var x8 = new Uint8Array(x.buffer); + if (x.byteOffset !== 0) + x8 = x8.subarray(x.byteOffset); + x[0] ^= this.P[17]; + for (var i = 16; i > 0; i -= 2) { + x[1] ^= F(this.S, x8, 0) ^ this.P[i]; + x[0] ^= F(this.S, x8, 4) ^ this.P[i-1]; + } + var t = x[0]; + x[0] = x[1] ^ this.P[0]; + x[1] = t; +}; - if (typeof source !== 'object') { - if (Array.isArray(target)) { - target.push(source); - } else if (typeof target === 'object') { - if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { - target[source] = true; - } - } else { - return [target, source]; - } +function stream2word(data, databytes){ + var i, temp = 0; + for (i = 0; i < 4; i++, BLF_J++) { + if (BLF_J >= databytes) BLF_J = 0; + temp = (temp << 8) | data[BLF_J]; + } + return temp; +}; - return target; - } +Blowfish.prototype.expand0state = function(key, keybytes) { + var d = new Uint32Array(2), i, k; + var d8 = new Uint8Array(d.buffer); - if (typeof target !== 'object') { - return [target].concat(source); - } + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } + BLF_J = 0; - var mergeTarget = target; - if (Array.isArray(target) && !Array.isArray(source)) { - mergeTarget = exports.arrayToObject(target, options); - } + for (i = 0; i < 18; i += 2) { + this.encipher(d, d8); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } - if (Array.isArray(target) && Array.isArray(source)) { - source.forEach(function (item, i) { - if (has.call(target, i)) { - if (target[i] && typeof target[i] === 'object') { - target[i] = exports.merge(target[i], item, options); - } else { - target.push(item); - } - } else { - target[i] = item; - } - }); - return target; + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + this.encipher(d, d8); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } + } +}; - return Object.keys(source).reduce(function (acc, key) { - var value = source[key]; +Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) { + var d = new Uint32Array(2), i, k; - if (Object.prototype.hasOwnProperty.call(acc, key)) { - acc[key] = exports.merge(acc[key], value, options); - } else { - acc[key] = value; - } - return acc; - }, mergeTarget); -}; + for (i = 0, BLF_J = 0; i < 18; i++) { + this.P[i] ^= stream2word(key, keybytes); + } -exports.decode = function (str) { - try { - return decodeURIComponent(str.replace(/\+/g, ' ')); - } catch (e) { - return str; + for (i = 0, BLF_J = 0; i < 18; i += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.P[i] = d[0]; + this.P[i+1] = d[1]; + } + + for (i = 0; i < 4; i++) { + for (k = 0; k < 256; k += 2) { + d[0] ^= stream2word(data, databytes); + d[1] ^= stream2word(data, databytes); + this.encipher(d); + this.S[i][k] = d[0]; + this.S[i][k+1] = d[1]; } + } + BLF_J = 0; }; -exports.encode = function (str) { - // This code was originally written by Brian White (mscdex) for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; - } +Blowfish.prototype.enc = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.encipher(data.subarray(i*2)); + } +}; - var string = typeof str === 'string' ? str : String(str); +Blowfish.prototype.dec = function(data, blocks) { + for (var i = 0; i < blocks; i++) { + this.decipher(data.subarray(i*2)); + } +}; - var out = ''; - for (var i = 0; i < string.length; ++i) { - var c = string.charCodeAt(i); +var BCRYPT_BLOCKS = 8, + BCRYPT_HASHSIZE = 32; - if ( - c === 0x2D || // - - c === 0x2E || // . - c === 0x5F || // _ - c === 0x7E || // ~ - (c >= 0x30 && c <= 0x39) || // 0-9 - (c >= 0x41 && c <= 0x5A) || // a-z - (c >= 0x61 && c <= 0x7A) // A-Z - ) { - out += string.charAt(i); - continue; - } +function bcrypt_hash(sha2pass, sha2salt, out) { + var state = new Blowfish(), + cdata = new Uint32Array(BCRYPT_BLOCKS), i, + ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105, + 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109, + 105,116,101]); //"OxychromaticBlowfishSwatDynamite" - if (c < 0x80) { - out = out + hexTable[c]; - continue; - } + state.expandstate(sha2salt, 64, sha2pass, 64); + for (i = 0; i < 64; i++) { + state.expand0state(sha2salt, 64); + state.expand0state(sha2pass, 64); + } - if (c < 0x800) { - out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } + for (i = 0; i < BCRYPT_BLOCKS; i++) + cdata[i] = stream2word(ciphertext, ciphertext.byteLength); + for (i = 0; i < 64; i++) + state.enc(cdata, cdata.byteLength / 8); - if (c < 0xD800 || c >= 0xE000) { - out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); - continue; - } + for (i = 0; i < BCRYPT_BLOCKS; i++) { + out[4*i+3] = cdata[i] >>> 24; + out[4*i+2] = cdata[i] >>> 16; + out[4*i+1] = cdata[i] >>> 8; + out[4*i+0] = cdata[i]; + } +}; - i += 1; - c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); - out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; // eslint-disable-line max-len - } +function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) { + var sha2pass = new Uint8Array(64), + sha2salt = new Uint8Array(64), + out = new Uint8Array(BCRYPT_HASHSIZE), + tmpout = new Uint8Array(BCRYPT_HASHSIZE), + countsalt = new Uint8Array(saltlen+4), + i, j, amt, stride, dest, count, + origkeylen = keylen; - return out; -}; + if (rounds < 1) + return -1; + if (passlen === 0 || saltlen === 0 || keylen === 0 || + keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20)) + return -1; -exports.compact = function (obj, references) { - if (typeof obj !== 'object' || obj === null) { - return obj; - } + stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength); + amt = Math.floor((keylen + stride - 1) / stride); - var refs = references || []; - var lookup = refs.indexOf(obj); - if (lookup !== -1) { - return refs[lookup]; - } + for (i = 0; i < saltlen; i++) + countsalt[i] = salt[i]; - refs.push(obj); + crypto_hash_sha512(sha2pass, pass, passlen); - if (Array.isArray(obj)) { - var compacted = []; + for (count = 1; keylen > 0; count++) { + countsalt[saltlen+0] = count >>> 24; + countsalt[saltlen+1] = count >>> 16; + countsalt[saltlen+2] = count >>> 8; + countsalt[saltlen+3] = count; - for (var i = 0; i < obj.length; ++i) { - if (obj[i] && typeof obj[i] === 'object') { - compacted.push(exports.compact(obj[i], refs)); - } else if (typeof obj[i] !== 'undefined') { - compacted.push(obj[i]); - } - } + crypto_hash_sha512(sha2salt, countsalt, saltlen + 4); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (i = out.byteLength; i--;) + out[i] = tmpout[i]; - return compacted; + for (i = 1; i < rounds; i++) { + crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength); + bcrypt_hash(sha2pass, sha2salt, tmpout); + for (j = 0; j < out.byteLength; j++) + out[j] ^= tmpout[j]; } - var keys = Object.keys(obj); - keys.forEach(function (key) { - obj[key] = exports.compact(obj[key], refs); - }); - - return obj; -}; + amt = Math.min(amt, keylen); + for (i = 0; i < amt; i++) { + dest = i * stride + (count - 1); + if (dest >= origkeylen) + break; + key[dest] = out[i]; + } + keylen -= i; + } -exports.isRegExp = function (obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; + return 0; }; -exports.isBuffer = function (obj) { - if (obj === null || typeof obj === 'undefined') { - return false; - } - - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +module.exports = { + BLOCKS: BCRYPT_BLOCKS, + HASHSIZE: BCRYPT_HASHSIZE, + hash: bcrypt_hash, + pbkdf: bcrypt_pbkdf }; /***/ }), -/* 252 */ +/* 279 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +const restoreCursor = __webpack_require__(613); -module.exports = Readable; +let hidden = false; -/*<replacement>*/ -var processNextTick = __webpack_require__(162); -/*</replacement>*/ +exports.show = stream => { + const s = stream || process.stderr; -/*<replacement>*/ -var isArray = __webpack_require__(241); -/*</replacement>*/ + if (!s.isTTY) { + return; + } -/*<replacement>*/ -var Duplex; -/*</replacement>*/ + hidden = false; + s.write('\u001b[?25h'); +}; -Readable.ReadableState = ReadableState; +exports.hide = stream => { + const s = stream || process.stderr; -/*<replacement>*/ -var EE = __webpack_require__(49).EventEmitter; + if (!s.isTTY) { + return; + } -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; + restoreCursor(); + hidden = true; + s.write('\u001b[?25l'); }; -/*</replacement>*/ - -/*<replacement>*/ -var Stream = __webpack_require__(255); -/*</replacement>*/ -var Buffer = __webpack_require__(76).Buffer; -/*<replacement>*/ -var bufferShim = __webpack_require__(132); -/*</replacement>*/ +exports.toggle = (force, stream) => { + if (force !== undefined) { + hidden = force; + } -/*<replacement>*/ -var util = __webpack_require__(71); -util.inherits = __webpack_require__(37); -/*</replacement>*/ + if (hidden) { + exports.show(stream); + } else { + exports.hide(stream); + } +}; -/*<replacement>*/ -var debugUtil = __webpack_require__(2); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/*</replacement>*/ -var BufferList = __webpack_require__(581); -var StringDecoder; +/***/ }), +/* 280 */ +/***/ (function(module, exports) { -util.inherits(Readable, Stream); -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +/** + * slice() reference. + */ -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } -} +var slice = Array.prototype.slice; -function ReadableState(options, stream) { - Duplex = Duplex || __webpack_require__(56); +/** + * Expose `co`. + */ - options = options || {}; +module.exports = co['default'] = co.co = co; - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; +/** + * Wrap the given generator `fn` into a + * function that returns a promise. + * This is a separate function so that + * every `co()` call doesn't create a new, + * unnecessary closure. + * + * @param {GeneratorFunction} fn + * @return {Function} + * @api public + */ - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; +co.wrap = function (fn) { + createPromise.__generatorFunction__ = fn; + return createPromise; + function createPromise() { + return co.call(this, fn.apply(this, arguments)); + } +}; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; +/** + * Execute the generator function or a generator + * and return a promise. + * + * @param {Function} fn + * @return {Promise} + * @api public + */ - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; +function co(gen) { + var ctx = this; + var args = slice.call(arguments, 1) - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + // we wrap everything in a promise to avoid promise chaining, + // which leads to memory leak errors. + // see https://github.com/tj/co/issues/180 + return new Promise(function(resolve, reject) { + if (typeof gen === 'function') gen = gen.apply(ctx, args); + if (!gen || typeof gen.next !== 'function') return resolve(gen); - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + onFulfilled(); - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + /** + * @param {Mixed} res + * @return {Promise} + * @api private + */ - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + function onFulfilled(res) { + var ret; + try { + ret = gen.next(res); + } catch (e) { + return reject(e); + } + next(ret); + } - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; + /** + * @param {Error} err + * @return {Promise} + * @api private + */ - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + function onRejected(err) { + var ret; + try { + ret = gen.throw(err); + } catch (e) { + return reject(e); + } + next(ret); + } - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + /** + * Get the next value in the generator, + * return a promise. + * + * @param {Object} ret + * @return {Promise} + * @api private + */ - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = __webpack_require__(256).StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } + function next(ret) { + if (ret.done) return resolve(ret.value); + var value = toPromise.call(ctx, ret.value); + if (value && isPromise(value)) return value.then(onFulfilled, onRejected); + return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, ' + + 'but the following object was passed: "' + String(ret.value) + '"')); + } + }); } -function Readable(options) { - Duplex = Duplex || __webpack_require__(56); +/** + * Convert a `yield`ed value into a promise. + * + * @param {Mixed} obj + * @return {Promise} + * @api private + */ - if (!(this instanceof Readable)) return new Readable(options); +function toPromise(obj) { + if (!obj) return obj; + if (isPromise(obj)) return obj; + if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj); + if ('function' == typeof obj) return thunkToPromise.call(this, obj); + if (Array.isArray(obj)) return arrayToPromise.call(this, obj); + if (isObject(obj)) return objectToPromise.call(this, obj); + return obj; +} - this._readableState = new ReadableState(options, this); +/** + * Convert a thunk to a promise. + * + * @param {Function} + * @return {Promise} + * @api private + */ - // legacy - this.readable = true; +function thunkToPromise(fn) { + var ctx = this; + return new Promise(function (resolve, reject) { + fn.call(ctx, function (err, res) { + if (err) return reject(err); + if (arguments.length > 2) res = slice.call(arguments, 1); + resolve(res); + }); + }); +} - if (options && typeof options.read === 'function') this._read = options.read; +/** + * Convert an array of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Array} obj + * @return {Promise} + * @api private + */ - Stream.call(this); +function arrayToPromise(obj) { + return Promise.all(obj.map(toPromise, this)); } -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; +/** + * Convert an object of "yieldables" to a promise. + * Uses `Promise.all()` internally. + * + * @param {Object} obj + * @return {Promise} + * @api private + */ - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = bufferShim.from(chunk, encoding); - encoding = ''; - } +function objectToPromise(obj){ + var results = new obj.constructor(); + var keys = Object.keys(obj); + var promises = []; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var promise = toPromise.call(this, obj[key]); + if (promise && isPromise(promise)) defer(promise, key); + else results[key] = obj[key]; } + return Promise.all(promises).then(function () { + return results; + }); - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; + function defer(promise, key) { + // predefine the key in the result + results[key] = undefined; + promises.push(promise.then(function (res) { + results[key] = res; + })); + } +} -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; +/** + * Check if `obj` is a promise. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */ -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - stream.emit('error', _e); - } else { - var skipAdd; - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } +function isPromise(obj) { + return 'function' == typeof obj.then; +} - if (!addToFront) state.reading = false; +/** + * Check if `obj` is a generator. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ - // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); +function isGenerator(obj) { + return 'function' == typeof obj.next && 'function' == typeof obj.throw; +} - if (state.needReadable) emitReadable(stream); - } - } +/** + * Check if `obj` is a generator function. + * + * @param {Mixed} obj + * @return {Boolean} + * @api private + */ +function isGeneratorFunction(obj) { + var constructor = obj.constructor; + if (!constructor) return false; + if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true; + return isGenerator(constructor.prototype); +} - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } +/** + * Check for plain object. + * + * @param {Mixed} val + * @return {Boolean} + * @api private + */ - return needMoreData(state); +function isObject(val) { + return Object == val.constructor; } -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = __webpack_require__(256).StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; +/***/ }), +/* 281 */ +/***/ (function(module, exports, __webpack_require__) { -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; +var util = __webpack_require__(2); +var Stream = __webpack_require__(26).Stream; +var DelayedStream = __webpack_require__(473); + +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + + this._released = false; + this._streams = []; + this._currentStream = null; } +util.inherits(CombinedStream, Stream); -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; +CombinedStream.create = function(options) { + var combinedStream = new this(); + + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; } - return state.length; -} -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + return combinedStream; +}; - if (n !== 0) state.emittedReadable = false; +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); - n = howMuchToRead(n, state); + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); + } } - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + this._streams.push(stream); + return this; +}; - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); +CombinedStream.prototype._getNext = function() { + this._currentStream = null; + var stream = this._streams.shift(); + + + if (typeof stream == 'undefined') { + this.end(); + return; } - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + this._pipeNext(stream); + }.bind(this)); +}; - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; } - if (ret !== null) this.emit('data', ret); + var value = stream; + this.write(value); + this._getNext(); +}; - return ret; +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); }; -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - processNextTick(maybeReadMore_, stream, state); - } -} + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); }; -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; } - } - function onend() { - debug('onend'); - dest.end(); + self.dataSize += stream.dataSize; + }); + + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; } +}; - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); - cleanedUp = true; +/***/ }), +/* 282 */ +/***/ (function(module, exports, __webpack_require__) { - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } +// Load modules - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } +var Crypto = __webpack_require__(8); +var Boom = __webpack_require__(124); - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); +// Declare internals - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); +var internals = {}; - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - // tell the dest that it's being piped to - dest.emit('pipe', src); +// Generate a cryptographically strong pseudo-random data - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } +exports.randomString = function (size) { - return dest; + var buffer = exports.randomBits((size + 1) * 6); + if (buffer instanceof Error) { + return buffer; + } + + var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, ''); + return string.slice(0, size); }; -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; +exports.randomBits = function (bits) { - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + if (!bits || + bits < 0) { - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + return Boom.internal('Invalid random bits count'); + } - if (!dest) dest = state.pipes; + var bytes = Math.ceil(bits / 8); + try { + return Crypto.randomBytes(bytes); + } + catch (err) { + return Boom.internal('Failed generating random bits: ' + err.message); + } +}; - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } - // slow case. multiple pipe destinations. +// Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match) - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +exports.fixedTimeComparison = function (a, b) { - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this); - }return this; - } + if (typeof a !== 'string' || + typeof b !== 'string') { - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; + return false; + } - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; + var mismatch = (a.length === b.length ? 0 : 1); + if (mismatch) { + b = a; + } - dest.emit('unpipe', this); + for (var i = 0, il = a.length; i < il; ++i) { + var ac = a.charCodeAt(i); + var bc = b.charCodeAt(i); + mismatch |= (ac ^ bc); + } - return this; + return (mismatch === 0); }; -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - processNextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this, state); - } - } - } - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} +/***/ }), +/* 283 */ +/***/ (function(module, exports, __webpack_require__) { -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; +var stream = __webpack_require__(74) +var eos = __webpack_require__(475) +var inherits = __webpack_require__(39) +var shift = __webpack_require__(635) -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - processNextTick(resume_, stream, state); - } +var SIGNAL_FLUSH = new Buffer([0]) + +var onuncork = function(self, fn) { + if (self._corked) self.once('uncork', fn) + else fn() } -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); +var destroyer = function(self, end) { + return function(err) { + if (err) self.destroy(err.message === 'premature close' ? null : err) + else if (end && !self._ended) self.end() } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); } -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; +var end = function(ws, fn) { + if (!ws) return fn() + if (ws._writableState && ws._writableState.finished) return fn() + if (ws._writableState) return ws.end(fn) + ws.end() + fn() +} -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} +var toStreams2 = function(rs) { + return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) } -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; +var Duplexify = function(writable, readable, opts) { + if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) + stream.Duplex.call(this, opts) - var self = this; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } + this._writable = null + this._readable = null + this._readable2 = null - self.push(null); - }); + this._forwardDestroy = !opts || opts.destroy !== false + this._forwardEnd = !opts || opts.end !== false + this._corked = 1 // start corked + this._ondrain = null + this._drained = false + this._forwarding = false + this._unwrite = null + this._unread = null + this._ended = false - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); + this.destroyed = false - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + if (writable) this.setWritable(writable) + if (readable) this.setReadable(readable) +} - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); +inherits(Duplexify, stream.Duplex) - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } +Duplexify.obj = function(writable, readable, opts) { + if (!opts) opts = {} + opts.objectMode = true + opts.highWaterMark = 16 + return new Duplexify(writable, readable, opts) +} + +Duplexify.prototype.cork = function() { + if (++this._corked === 1) this.emit('cork') +} + +Duplexify.prototype.uncork = function() { + if (this._corked && --this._corked === 0) this.emit('uncork') +} + +Duplexify.prototype.setWritable = function(writable) { + if (this._unwrite) this._unwrite() + + if (this.destroyed) { + if (writable && writable.destroy) writable.destroy() + return } - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + if (writable === null || writable === false) { + this.end() + return } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; + var self = this + var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) - return self; -}; + var ondrain = function() { + var ondrain = self._ondrain + self._ondrain = null + if (ondrain) ondrain() + } -// exposed for testing purposes only. -Readable._fromList = fromList; + var clear = function() { + self._writable.removeListener('drain', ondrain) + unend() + } -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; + if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } + this._writable = writable + this._writable.on('drain', ondrain) + this._unwrite = clear - return ret; + this.uncork() // always uncork setWritable } -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} +Duplexify.prototype.setReadable = function(readable) { + if (this._unread) this._unread() -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; + if (this.destroyed) { + if (readable && readable.destroy) readable.destroy() + return } - list.length -= c; - return ret; -} -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = bufferShim.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; + if (readable === null || readable === false) { + this.push(null) + this.resume() + return } - list.length -= c; - return ret; -} -function endReadable(stream) { - var state = stream._readableState; + var self = this + var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + var onreadable = function() { + self._forward() + } - if (!state.endEmitted) { - state.ended = true; - processNextTick(endReadableNT, state, stream); + var onend = function() { + self.push(null) } -} -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); + var clear = function() { + self._readable2.removeListener('readable', onreadable) + self._readable2.removeListener('end', onend) + unend() } + + this._drained = true + this._readable = readable + this._readable2 = readable._readableState ? readable : toStreams2(readable) + this._readable2.on('readable', onreadable) + this._readable2.on('end', onend) + this._unread = clear + + this._forward() } -function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } +Duplexify.prototype._read = function() { + this._drained = true + this._forward() } -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; +Duplexify.prototype._forward = function() { + if (this._forwarding || !this._readable2 || !this._drained) return + this._forwarding = true + + var data + + while (this._drained && (data = shift(this._readable2)) !== null) { + if (this.destroyed) continue + this._drained = this.push(data) } - return -1; + + this._forwarding = false } -/***/ }), -/* 253 */ -/***/ (function(module, exports, __webpack_require__) { +Duplexify.prototype.destroy = function(err) { + if (this.destroyed) return + this.destroyed = true -"use strict"; -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. + var self = this + process.nextTick(function() { + self._destroy(err) + }) +} +Duplexify.prototype._destroy = function(err) { + if (err) { + var ondrain = this._ondrain + this._ondrain = null + if (ondrain) ondrain(err) + else this.emit('error', err) + } + if (this._forwardDestroy) { + if (this._readable && this._readable.destroy) this._readable.destroy() + if (this._writable && this._writable.destroy) this._writable.destroy() + } -module.exports = Transform; + this.emit('close') +} -var Duplex = __webpack_require__(56); +Duplexify.prototype._write = function(data, enc, cb) { + if (this.destroyed) return cb() + if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) + if (data === SIGNAL_FLUSH) return this._finish(cb) + if (!this._writable) return cb() -/*<replacement>*/ -var util = __webpack_require__(71); -util.inherits = __webpack_require__(37); -/*</replacement>*/ + if (this._writable.write(data) === false) this._ondrain = cb + else cb() +} -util.inherits(Transform, Duplex); -function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; +Duplexify.prototype._finish = function(cb) { + var self = this + this.emit('preend') + onuncork(this, function() { + end(self._forwardEnd && self._writable, function() { + // haxx to not emit prefinish twice + if (self._writableState.prefinished === false) self._writableState.prefinished = true + self.emit('prefinish') + onuncork(self, cb) + }) + }) +} - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; +Duplexify.prototype.end = function(data, enc, cb) { + if (typeof data === 'function') return this.end(null, null, data) + if (typeof enc === 'function') return this.end(data, null, enc) + this._ended = true + if (data) this.write(data) + if (!this._writableState.ending) this.write(SIGNAL_FLUSH) + return stream.Writable.prototype.end.call(this, cb) } -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; +module.exports = Duplexify - var cb = ts.writecb; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); +/***/ }), +/* 284 */ +/***/ (function(module, exports, __webpack_require__) { - ts.writechunk = null; - ts.writecb = null; +var crypto = __webpack_require__(8); +var BigInteger = __webpack_require__(56).BigInteger; +var ECPointFp = __webpack_require__(130).ECPointFp; +exports.ECCurves = __webpack_require__(477); - if (data !== null && data !== undefined) stream.push(data); +// zero prepad +function unstupid(hex,len) +{ + return (hex.length >= len) ? hex : unstupid("0"+hex,len); +} - cb(er); +exports.ECKey = function(curve, key, isPublic) +{ + var priv; + var c = curve(); + var n = c.getN(); + var bytes = Math.floor(n.bitLength()/8); - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); + if(key) + { + if(isPublic) + { + var curve = c.getCurve(); +// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format +// var y = key.slice(bytes+1); +// this.P = new ECPointFp(curve, +// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)), +// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16))); + this.P = curve.decodePointHex(key.toString("hex")); + }else{ + if(key.length != bytes) return false; + priv = new BigInteger(key.toString("hex"), 16); + } + }else{ + var n1 = n.subtract(BigInteger.ONE); + var r = new BigInteger(crypto.randomBytes(n.bitLength())); + priv = r.mod(n1).add(BigInteger.ONE); + this.P = c.getG().multiply(priv); + } + if(this.P) + { +// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2); +// this.PublicKey = new Buffer("04"+pubhex,"hex"); + this.PublicKey = new Buffer(c.getCurve().encodeCompressedPointHex(this.P),"hex"); + } + if(priv) + { + this.PrivateKey = new Buffer(unstupid(priv.toString(16),bytes*2),"hex"); + this.deriveSharedSecret = function(key) + { + if(!key || !key.P) return false; + var S = key.P.multiply(priv); + return new Buffer(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex"); + } } } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = new TransformState(this); +/***/ }), +/* 285 */ +/***/ (function(module, exports, __webpack_require__) { - var stream = this; +var once = __webpack_require__(72); - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +var noop = function() {}; - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; +var isChildProcess = function(stream) { + return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 +}; - if (typeof options.flush === 'function') this._flush = options.flush; - } +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; - // When the writable side finishes, then flush out anything remaining. - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er, data) { - done(stream, er, data); - });else done(stream); - }); -} + callback = once(callback || noop); -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; + var onfinish = function() { + writable = false; + if (!readable) callback.call(stream); + }; -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; + var onend = function() { + readable = false; + if (!writable) callback.call(stream); + }; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; + var onexit = function(exitCode) { + callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); + }; -function done(stream, er, data) { - if (er) return stream.emit('error', er); + var onclose = function() { + if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); + if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); + }; - if (data !== null && data !== undefined) stream.push(data); + var onrequest = function() { + stream.req.on('finish', onfinish); + }; - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + if (isChildProcess(stream)) stream.on('exit', onexit); - if (ts.transforming) throw new Error('Calling transform done when still transforming'); + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', callback); + stream.on('close', onclose); + + return function() { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('exit', onexit); + stream.removeListener('end', onend); + stream.removeListener('error', callback); + stream.removeListener('close', onclose); + }; +}; + +module.exports = eos; - return stream.push(null); -} /***/ }), -/* 254 */ +/* 286 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -module.exports = Writable; - -/*<replacement>*/ -var processNextTick = __webpack_require__(162); -/*</replacement>*/ +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } -/*<replacement>*/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/*</replacement>*/ + return str.replace(matchOperatorsRe, '\\$&'); +}; -/*<replacement>*/ -var Duplex; -/*</replacement>*/ -Writable.WritableState = WritableState; +/***/ }), +/* 287 */ +/***/ (function(module, exports, __webpack_require__) { -/*<replacement>*/ -var util = __webpack_require__(71); -util.inherits = __webpack_require__(37); -/*</replacement>*/ +/* + * extsprintf.js: extended POSIX-style sprintf + */ -/*<replacement>*/ -var internalUtil = { - deprecate: __webpack_require__(631) -}; -/*</replacement>*/ +var mod_assert = __webpack_require__(18); +var mod_util = __webpack_require__(2); -/*<replacement>*/ -var Stream = __webpack_require__(255); -/*</replacement>*/ +/* + * Public interface + */ +exports.sprintf = jsSprintf; -var Buffer = __webpack_require__(76).Buffer; -/*<replacement>*/ -var bufferShim = __webpack_require__(132); -/*</replacement>*/ +/* + * Stripped down version of s[n]printf(3c). We make a best effort to throw an + * exception when given a format string we don't understand, rather than + * ignoring it, so that we won't break existing programs if/when we go implement + * the rest of this. + * + * This implementation currently supports specifying + * - field alignment ('-' flag), + * - zero-pad ('0' flag) + * - always show numeric sign ('+' flag), + * - field width + * - conversions for strings, decimal integers, and floats (numbers). + * - argument size specifiers. These are all accepted but ignored, since + * Javascript has no notion of the physical size of an argument. + * + * Everything else is currently unsupported, most notably precision, unsigned + * numbers, non-decimal numbers, and characters. + */ +function jsSprintf(fmt) +{ + var regex = [ + '([^%]*)', /* normal text */ + '%', /* start of format */ + '([\'\\-+ #0]*?)', /* flags (optional) */ + '([1-9]\\d*)?', /* width (optional) */ + '(\\.([1-9]\\d*))?', /* precision (optional) */ + '[lhjztL]*?', /* length mods (ignored) */ + '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */ + ].join(''); -util.inherits(Writable, Stream); + var re = new RegExp(regex); + var args = Array.prototype.slice.call(arguments, 1); + var flags, width, precision, conversion; + var left, pad, sign, arg, match; + var ret = ''; + var argn = 1; -function nop() {} + mod_assert.equal('string', typeof (fmt)); -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} + while ((match = re.exec(fmt)) !== null) { + ret += match[1]; + fmt = fmt.substring(match[0].length); -function WritableState(options, stream) { - Duplex = Duplex || __webpack_require__(56); + flags = match[2] || ''; + width = match[3] || 0; + precision = match[4] || ''; + conversion = match[6]; + left = false; + sign = false; + pad = ' '; - options = options || {}; + if (conversion == '%') { + ret += '%'; + continue; + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + if (args.length === 0) + throw (new Error('too few args to sprintf')); - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + arg = args.shift(); + argn++; - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + if (flags.match(/[\' #]/)) + throw (new Error( + 'unsupported flags: ' + flags)); - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; + if (precision.length > 0) + throw (new Error( + 'non-zero precision not supported')); - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + if (flags.match(/-/)) + left = true; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; + if (flags.match(/0/)) + pad = '0'; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + if (flags.match(/\+/)) + sign = true; - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + switch (conversion) { + case 's': + if (arg === undefined || arg === null) + throw (new Error('argument ' + argn + + ': attempted to print undefined or null ' + + 'as a string')); + ret += doPad(pad, width, left, arg.toString()); + break; - // a flag to see when we're in the middle of a write. - this.writing = false; + case 'd': + arg = Math.floor(arg); + /*jsl:fallthru*/ + case 'f': + sign = sign && arg > 0 ? '+' : ''; + ret += sign + doPad(pad, width, left, + arg.toString()); + break; - // when true all writes will be buffered until .uncork() call - this.corked = 0; + case 'j': /* non-standard */ + if (width === 0) + width = 10; + ret += mod_util.inspect(arg, false, width); + break; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + case 'r': /* non-standard */ + ret += dumpException(arg); + break; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; + default: + throw (new Error('unsupported conversion: ' + + conversion)); + } + } - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + ret += fmt; + return (ret); +} - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; +function doPad(chr, width, left, str) +{ + var ret = str; - // the amount that is being written when _write is called. - this.writelen = 0; + while (ret.length < width) { + if (left) + ret += chr; + else + ret = chr + ret; + } - this.bufferedRequest = null; - this.lastBufferedRequest = null; + return (ret); +} - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; +/* + * This function dumps long stack traces for exceptions having a cause() method. + * See node-verror for an example. + */ +function dumpException(ex) +{ + var ret; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; + if (!(ex instanceof Error)) + throw (new Error(jsSprintf('invalid type for %%r: %j', ex))); - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; + /* Note that V8 prepends "ex.stack" with ex.toString(). */ + ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack; - // count buffered requests - this.bufferedRequestCount = 0; + if (ex.cause && typeof (ex.cause) === 'function') { + var cex = ex.cause(); + if (cex) { + ret += '\nCaused by: ' + dumpException(cex); + } + } - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); + return (ret); } -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - } catch (_) {} -})(); +/***/ }), +/* 288 */ +/***/ (function(module, exports, __webpack_require__) { -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; +"use strict"; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} -function Writable(options) { - Duplex = Duplex || __webpack_require__(56); +var fs = __webpack_require__(5) - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. +module.exports = clone(fs) - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - this._writableState = new WritableState(options, this); + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) - // legacy. - this.writable = true; + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - if (options) { - if (typeof options.write === 'function') this._write = options.write; + return copy +} - if (typeof options.writev === 'function') this._writev = options.writev; - } - Stream.call(this); -} +/***/ }), +/* 289 */ +/***/ (function(module, exports, __webpack_require__) { -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; +var fs = __webpack_require__(5) +var polyfills = __webpack_require__(496) +var legacy = __webpack_require__(495) +var queue = [] -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - processNextTick(cb, er); -} +var util = __webpack_require__(2) -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; +function noop () {} - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - processNextTick(cb, er); - valid = false; +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) } - return valid; + +if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(queue) + __webpack_require__(18).equal(queue.length, 0) + }) } -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = Buffer.isBuffer(chunk); +module.exports = patch(__webpack_require__(288)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH) { + module.exports = patch(fs) +} - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +// Always patch fs.close/closeSync, because we want to +// retry() whenever a close happens *anywhere* in the program. +// This is essential when multiple graceful-fs instances are +// in play at the same time. +module.exports.close = +fs.close = (function (fs$close) { return function (fd, cb) { + return fs$close.call(fs, fd, function (err) { + if (!err) + retry() - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (typeof cb === 'function') + cb.apply(this, arguments) + }) +}})(fs.close) - if (typeof cb !== 'function') cb = nop; +module.exports.closeSync = +fs.closeSync = (function (fs$closeSync) { return function (fd) { + // Note that graceful-fs also retries when fs.closeSync() fails. + // Looks like a bug to me, although it's probably a harmless one. + var rval = fs$closeSync.apply(fs, arguments) + retry() + return rval +}})(fs.closeSync) - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + fs.FileReadStream = ReadStream; // Legacy name. + fs.FileWriteStream = WriteStream; // Legacy name. + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } } - return ret; -}; + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -Writable.prototype.cork = function () { - var state = this._writableState; + return go$writeFile(path, data, options, cb) - state.corked++; -}; + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } -Writable.prototype.uncork = function () { - var state = this._writableState; + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - if (state.corked) { - state.corked--; + return go$appendFile(path, data, options, cb) - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } } -}; -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) + } else { + cb = options + } + args.push(go$readdir$cb) -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = bufferShim.from(chunk, encoding); + return go$readdir(args) + + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() + + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + } } - return chunk; -} -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + function go$readdir (args) { + return fs$readdir.apply(fs, args) } - var len = state.objectMode ? 1 : chunk.length; - state.length += len; + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + var fs$ReadStream = fs.ReadStream + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } + var fs$WriteStream = fs.WriteStream + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open - return ret; -} + fs.ReadStream = ReadStream + fs.WriteStream = WriteStream -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) processNextTick(cb, er);else cb(er); + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } - onwriteStateUpdate(state); + function createReadStream (path, options) { + return new ReadStream(path, options) + } - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + function createWriteStream (path, options) { + return new WriteStream(path, options) + } - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null - if (sync) { - /*<replacement>*/ - asyncWrite(afterWrite, stream, state, finished, cb); - /*</replacement>*/ - } else { - afterWrite(stream, state, finished, cb); + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) } } + + return fs } -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + queue.push(elem) } -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); +function retry () { + var elem = queue.shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) } } -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; +/***/ }), +/* 290 */ +/***/ (function(module, exports, __webpack_require__) { - var count = 0; - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } +"use strict"; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); +var _ = __webpack_require__(28); +var MuteStream = __webpack_require__(297); +var readline = __webpack_require__(151); - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; +/** + * Base interface class other can inherits from + */ - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; +var UI = module.exports = function (opt) { + // Instantiate the Readline interface + // @Note: Don't reassign if already present (allow test to override the Stream) + if (!this.rl) { + this.rl = readline.createInterface(setupReadlineOptions(opt)); } + this.rl.resume(); - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + this.onForceClose = this.onForceClose.bind(this); -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); + // Make sure new prompt start on a newline when closing + this.rl.on('SIGINT', this.onForceClose); + process.on('exit', this.onForceClose); }; -Writable.prototype._writev = null; +/** + * Handle the ^C exit + * @return {null} + */ -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; +UI.prototype.onForceClose = function () { + this.close(); + console.log(''); +}; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +/** + * Close the interface and cleanup listeners + */ - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); +UI.prototype.close = function () { + // Remove events listeners + this.rl.removeListener('SIGINT', this.onForceClose); + process.removeListener('exit', this.onForceClose); - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); + this.rl.output.unmute(); + + if (this.activePrompt && typeof this.activePrompt.close === 'function') { + this.activePrompt.close(); } - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); + // Close the readline + this.rl.output.end(); + this.rl.pause(); + this.rl.close(); }; -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - return need; -} +function setupReadlineOptions(opt) { + opt = opt || {}; -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) processNextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} + // Default `input` to stdin + var input = opt.input || process.stdin; -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; + // Add mute capabilities to the output + var ms = new MuteStream(); + ms.pipe(opt.output || process.stdout); + var output = ms; - this.next = null; - this.entry = null; - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; + return _.extend({ + terminal: true, + input: input, + output: output + }, _.omit(opt, ['input', 'output'])); } -/***/ }), -/* 255 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = __webpack_require__(20); - /***/ }), -/* 256 */ +/* 291 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var ansiEscapes = __webpack_require__(370); -var Buffer = __webpack_require__(57).Buffer; +/** + * Move cursor left by `x` + * @param {Readline} rl - Readline instance + * @param {Number} x - How far to go left (default to 1) + */ -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } +exports.left = function (rl, x) { + rl.output.write(ansiEscapes.cursorBackward(x)); }; -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; +/** + * Move cursor right by `x` + * @param {Readline} rl - Readline instance + * @param {Number} x - How far to go left (default to 1) + */ -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} +exports.right = function (rl, x) { + rl.output.write(ansiEscapes.cursorForward(x)); +}; -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} +/** + * Move cursor up by `x` + * @param {Readline} rl - Readline instance + * @param {Number} x - How far to go up (default to 1) + */ -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; +exports.up = function (rl, x) { + rl.output.write(ansiEscapes.cursorUp(x)); }; -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; +/** + * Move cursor down by `x` + * @param {Readline} rl - Readline instance + * @param {Number} x - How far to go down (default to 1) + */ -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; +exports.down = function (rl, x) { + rl.output.write(ansiEscapes.cursorDown(x)); }; -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return -1; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} +/** + * Clear current line + * @param {Readline} rl - Readline instance + * @param {Number} len - number of line to delete + */ +exports.clearLine = function (rl, len) { + rl.output.write(ansiEscapes.eraseLines(len)); +}; -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'.repeat(p); - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'.repeat(p + 1); - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'.repeat(p + 2); - } - } - } -} -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} +/***/ }), +/* 292 */ +/***/ (function(module, exports, __webpack_require__) { -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} +"use strict"; +/*! + * is-number <https://github.com/jonschlinkert/is-number> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -// For UTF-8, a replacement character for each buffered byte of a (partial) -// character needs to be added to the output. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); - return r; -} -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} +var typeOf = __webpack_require__(218); -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; +module.exports = function isNumber(num) { + var type = typeOf(num); + if (type !== 'number' && type !== 'string') { + return false; } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} + var n = +num; + return (n - n + 1) >= 0 && num !== ''; +}; -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} /***/ }), -/* 257 */ +/* 293 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * repeat-element <https://github.com/jonschlinkert/repeat-element> + * is-primitive <https://github.com/jonschlinkert/is-primitive> * - * Copyright (c) 2015 Jon Schlinkert. - * Licensed under the MIT license. + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. */ -module.exports = function repeat(ele, num) { - var arr = new Array(num); +// see http://jsperf.com/testing-value-is-primitive/7 +module.exports = function isPrimitive(value) { + return value == null || (typeof value !== 'function' && typeof value !== 'object'); +}; - for (var i = 0; i < num; i++) { - arr[i] = ele; - } - return arr; +/***/ }), +/* 294 */ +/***/ (function(module, exports) { + +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; /***/ }), -/* 258 */ +/* 295 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +var stream = __webpack_require__(26) -var tough = __webpack_require__(627) -var Cookie = tough.Cookie - , CookieJar = tough.CookieJar +function isStream (obj) { + return obj instanceof stream.Stream +} -exports.parse = function(str) { - if (str && str.uri) { - str = str.uri - } - if (typeof str !== 'string') { - throw new Error('The cookie function only accepts STRING as param') - } - return Cookie.parse(str, {loose: true}) +function isReadable (obj) { + return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object' } -// Adapt the sometimes-Async api of tough.CookieJar to our requirements -function RequestJar(store) { - var self = this - self._jar = new CookieJar(store, {looseMode: true}) -} -RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) { - var self = this - return self._jar.setCookieSync(cookieOrStr, uri, options || {}) -} -RequestJar.prototype.getCookieString = function(uri) { - var self = this - return self._jar.getCookieStringSync(uri) -} -RequestJar.prototype.getCookies = function(uri) { - var self = this - return self._jar.getCookiesSync(uri) + +function isWritable (obj) { + return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object' } -exports.jar = function(store) { - return new RequestJar(store) + +function isDuplex (obj) { + return isReadable(obj) && isWritable(obj) } -/***/ }), -/* 259 */ +module.exports = isStream +module.exports.isReadable = isReadable +module.exports.isWritable = isWritable +module.exports.isDuplex = isDuplex + + +/***/ }), +/* 296 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -;(function (factory) { - var objectTypes = { - 'function': true, - 'object': true - }; - function checkGlobal(value) { - return (value && value.Object === Object) ? value : null; - } - var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null; - var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null; - var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global); - var freeSelf = checkGlobal(objectTypes[typeof self] && self); - var freeWindow = checkGlobal(objectTypes[typeof window] && window); - var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null; - var thisGlobal = checkGlobal(objectTypes[typeof this] && this); - var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); +/** + * Module dependencies. + * @private + */ - // Because of build optimizers - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { - return factory(root, exports, Rx); - }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof module === 'object' && module && module.exports === freeExports) { - module.exports = factory(root, module.exports, require('./rx')); - } else { - root.Rx = factory(root, {}, root.Rx); +var db = __webpack_require__(572) +var extname = __webpack_require__(0).extname + +/** + * Module variables. + * @private + */ + +var extractTypeRegExp = /^\s*([^;\s]*)(?:;|\s|$)/ +var textTypeRegExp = /^text\//i + +/** + * Module exports. + * @public + */ + +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) + +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) + +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ + +function charset (type) { + if (!type || typeof type !== 'string') { + return false } -}.call(this, function (root, exp, Rx, undefined) { - var Observable = Rx.Observable, - observableProto = Observable.prototype, - AnonymousObservable = Rx.AnonymousObservable, - ObservableBase = Rx.ObservableBase, - Subject = Rx.Subject, - AsyncSubject = Rx.AsyncSubject, - Observer = Rx.Observer, - ScheduledObserver = Rx.internals.ScheduledObserver, - disposableCreate = Rx.Disposable.create, - disposableEmpty = Rx.Disposable.empty, - BinaryDisposable = Rx.BinaryDisposable, - currentThreadScheduler = Rx.Scheduler.currentThread, - isFunction = Rx.helpers.isFunction, - inherits = Rx.internals.inherits, - addProperties = Rx.internals.addProperties, - checkDisposed = Rx.Disposable.checkDisposed; + // TODO: use media-typer + var match = extractTypeRegExp.exec(type) + var mime = match && db[match[1].toLowerCase()] - // Utilities - function cloneArray(arr) { - var len = arr.length, a = new Array(len); - for(var i = 0; i < len; i++) { a[i] = arr[i]; } - return a; + if (mime && mime.charset) { + return mime.charset } - var MulticastObservable = (function (__super__) { - inherits(MulticastObservable, __super__); - function MulticastObservable(source, fn1, fn2) { - this.source = source; - this._fn1 = fn1; - this._fn2 = fn2; - __super__.call(this); - } + // default text/* to utf-8 + if (match && textTypeRegExp.test(match[1])) { + return 'UTF-8' + } - MulticastObservable.prototype.subscribeCore = function (o) { - var connectable = this.source.multicast(this._fn1()); - return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect()); - }; + return false +} - return MulticastObservable; - }(ObservableBase)); +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ - /** - * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each - * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's - * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. - * - * @example - * 1 - res = source.multicast(observable); - * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); - * - * @param {Function|Subject} subjectOrSubjectSelector - * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. - * Or: - * Subject to push source elements into. - * - * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. - */ - observableProto.multicast = function (subjectOrSubjectSelector, selector) { - return isFunction(subjectOrSubjectSelector) ? - new MulticastObservable(this, subjectOrSubjectSelector, selector) : - new ConnectableObservable(this, subjectOrSubjectSelector); - }; +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } - /** - * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. - * This operator is a specialization of Multicast using a regular Subject. - * - * @example - * var resres = source.publish(); - * var res = source.publish(function (x) { return x; }); - * - * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. - */ - observableProto.publish = function (selector) { - return selector && isFunction(selector) ? - this.multicast(function () { return new Subject(); }, selector) : - this.multicast(new Subject()); - }; + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str - /** - * Returns an observable sequence that shares a single subscription to the underlying sequence. - * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. - */ - observableProto.share = function () { - return this.publish().refCount(); - }; + if (!mime) { + return false + } - /** - * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. - * This operator is a specialization of Multicast using a AsyncSubject. - * - * @example - * var res = source.publishLast(); - * var res = source.publishLast(function (x) { return x; }); - * - * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. - */ - observableProto.publishLast = function (selector) { - return selector && isFunction(selector) ? - this.multicast(function () { return new AsyncSubject(); }, selector) : - this.multicast(new AsyncSubject()); - }; + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } - /** - * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. - * This operator is a specialization of Multicast using a BehaviorSubject. - * - * @example - * var res = source.publishValue(42); - * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); - * - * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. - * @param {Mixed} initialValue Initial value received by observers upon subscription. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. - */ - observableProto.publishValue = function (initialValueOrSelector, initialValue) { - return arguments.length === 2 ? - this.multicast(function () { - return new BehaviorSubject(initialValue); - }, initialValueOrSelector) : - this.multicast(new BehaviorSubject(initialValueOrSelector)); - }; + return mime +} - /** - * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. - * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - * @param {Mixed} initialValue Initial value received by observers upon subscription. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. - */ - observableProto.shareValue = function (initialValue) { - return this.publishValue(initialValue).refCount(); - }; +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ - /** - * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. - * This operator is a specialization of Multicast using a ReplaySubject. - * - * @example - * var res = source.replay(null, 3); - * var res = source.replay(null, 3, 500); - * var res = source.replay(null, 3, 500, scheduler); - * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); - * - * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. - * @param bufferSize [Optional] Maximum element count of the replay buffer. - * @param windowSize [Optional] Maximum time length of the replay buffer. - * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. - */ - observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { - return selector && isFunction(selector) ? - this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : - this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); - }; +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } - /** - * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. - * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. - * - * @example - * var res = source.shareReplay(3); - * var res = source.shareReplay(3, 500); - * var res = source.shareReplay(3, 500, scheduler); - * + // TODO: use media-typer + var match = extractTypeRegExp.exec(type) - * @param bufferSize [Optional] Maximum element count of the replay buffer. - * @param window [Optional] Maximum time length of the replay buffer. - * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. - */ - observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { - return this.replay(null, bufferSize, windowSize, scheduler).refCount(); - }; + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] - var InnerSubscription = function (s, o) { - this._s = s; - this._o = o; - }; + if (!exts || !exts.length) { + return false + } - InnerSubscription.prototype.dispose = function () { - if (!this._s.isDisposed && this._o !== null) { - var idx = this._s.observers.indexOf(this._o); - this._s.observers.splice(idx, 1); - this._o = null; - } - }; + return exts[0] +} - /** - * Represents a value that changes over time. - * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. - */ - var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { - inherits(BehaviorSubject, __super__); - function BehaviorSubject(value) { - __super__.call(this); - this.value = value; - this.observers = []; - this.isDisposed = false; - this.isStopped = false; - this.hasError = false; - } +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ - addProperties(BehaviorSubject.prototype, Observer.prototype, { - _subscribe: function (o) { - checkDisposed(this); - if (!this.isStopped) { - this.observers.push(o); - o.onNext(this.value); - return new InnerSubscription(this, o); - } - if (this.hasError) { - o.onError(this.error); - } else { - o.onCompleted(); - } - return disposableEmpty; - }, - /** - * Gets the current value or throws an exception. - * Value is frozen after onCompleted is called. - * After onError is called always throws the specified exception. - * An exception is always thrown after dispose is called. - * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. - */ - getValue: function () { - checkDisposed(this); - if (this.hasError) { thrower(this.error); } - return this.value; - }, - /** - * Indicates whether the subject has observers subscribed to it. - * @returns {Boolean} Indicates whether the subject has observers subscribed to it. - */ - hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, - /** - * Notifies all subscribed observers about the end of the sequence. - */ - onCompleted: function () { - checkDisposed(this); - if (this.isStopped) { return; } - this.isStopped = true; - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - os[i].onCompleted(); - } +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } - this.observers.length = 0; - }, - /** - * Notifies all subscribed observers about the exception. - * @param {Mixed} error The exception to send to all observers. - */ - onError: function (error) { - checkDisposed(this); - if (this.isStopped) { return; } - this.isStopped = true; - this.hasError = true; - this.error = error; + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - os[i].onError(error); - } + if (!extension) { + return false + } - this.observers.length = 0; - }, - /** - * Notifies all subscribed observers about the arrival of the specified element in the sequence. - * @param {Mixed} value The value to send to all observers. - */ - onNext: function (value) { - checkDisposed(this); - if (this.isStopped) { return; } - this.value = value; - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - os[i].onNext(value); - } - }, - /** - * Unsubscribe all observers and release resources. - */ - dispose: function () { - this.isDisposed = true; - this.observers = null; - this.value = null; - this.error = null; - } - }); + return exports.types[extension] || false +} - return BehaviorSubject; - }(Observable)); +/** + * Populate the extensions and types maps. + * @private + */ - /** - * Represents an object that is both an observable sequence as well as an observer. - * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. - */ - var ReplaySubject = Rx.ReplaySubject = (function (__super__) { +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] - var maxSafeInteger = Math.pow(2, 53) - 1; + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions - function createRemovableDisposable(subject, observer) { - return disposableCreate(function () { - observer.dispose(); - !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); - }); + if (!exts || !exts.length) { + return } - inherits(ReplaySubject, __super__); + // mime -> extensions + extensions[type] = exts - /** - * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. - * @param {Number} [bufferSize] Maximum element count of the replay buffer. - * @param {Number} [windowSize] Maximum time length of the replay buffer. - * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. - */ - function ReplaySubject(bufferSize, windowSize, scheduler) { - this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; - this.windowSize = windowSize == null ? maxSafeInteger : windowSize; - this.scheduler = scheduler || currentThreadScheduler; - this.q = []; - this.observers = []; - this.isStopped = false; - this.isDisposed = false; - this.hasError = false; - this.error = null; - __super__.call(this); + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] + + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) + + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } + + // set the extension -> mime + types[extension] = type } + }) +} - addProperties(ReplaySubject.prototype, Observer.prototype, { - _subscribe: function (o) { - checkDisposed(this); - var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so); - this._trim(this.scheduler.now()); - this.observers.push(so); +/***/ }), +/* 297 */ +/***/ (function(module, exports, __webpack_require__) { - for (var i = 0, len = this.q.length; i < len; i++) { - so.onNext(this.q[i].value); - } +var Stream = __webpack_require__(26) - if (this.hasError) { - so.onError(this.error); - } else if (this.isStopped) { - so.onCompleted(); - } +module.exports = MuteStream - so.ensureActive(); - return subscription; - }, - /** - * Indicates whether the subject has observers subscribed to it. - * @returns {Boolean} Indicates whether the subject has observers subscribed to it. - */ - hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, - _trim: function (now) { - while (this.q.length > this.bufferSize) { - this.q.shift(); - } - while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { - this.q.shift(); - } - }, - /** - * Notifies all subscribed observers about the arrival of the specified element in the sequence. - * @param {Mixed} value The value to send to all observers. - */ - onNext: function (value) { - checkDisposed(this); - if (this.isStopped) { return; } - var now = this.scheduler.now(); - this.q.push({ interval: now, value: value }); - this._trim(now); +// var out = new MuteStream(process.stdout) +// argument auto-pipes +function MuteStream (opts) { + Stream.apply(this) + opts = opts || {} + this.writable = this.readable = true + this.muted = false + this.on('pipe', this._onpipe) + this.replace = opts.replace - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - var observer = os[i]; - observer.onNext(value); - observer.ensureActive(); - } - }, - /** - * Notifies all subscribed observers about the exception. - * @param {Mixed} error The exception to send to all observers. - */ - onError: function (error) { - checkDisposed(this); - if (this.isStopped) { return; } - this.isStopped = true; - this.error = error; - this.hasError = true; - var now = this.scheduler.now(); - this._trim(now); - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - var observer = os[i]; - observer.onError(error); - observer.ensureActive(); - } - this.observers.length = 0; - }, - /** - * Notifies all subscribed observers about the end of the sequence. - */ - onCompleted: function () { - checkDisposed(this); - if (this.isStopped) { return; } - this.isStopped = true; - var now = this.scheduler.now(); - this._trim(now); - for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { - var observer = os[i]; - observer.onCompleted(); - observer.ensureActive(); - } - this.observers.length = 0; - }, - /** - * Unsubscribe all observers and release resources. - */ - dispose: function () { - this.isDisposed = true; - this.observers = null; - } - }); + // For readline-type situations + // This much at the start of a line being redrawn after a ctrl char + // is seen (such as backspace) won't be redrawn as the replacement + this._prompt = opts.prompt || null + this._hadControl = false +} - return ReplaySubject; - }(Observable)); +MuteStream.prototype = Object.create(Stream.prototype) - var RefCountObservable = (function (__super__) { - inherits(RefCountObservable, __super__); - function RefCountObservable(source) { - this.source = source; - this._count = 0; - this._connectableSubscription = null; - __super__.call(this); - } +Object.defineProperty(MuteStream.prototype, 'constructor', { + value: MuteStream, + enumerable: false +}) - RefCountObservable.prototype.subscribeCore = function (o) { - var subscription = this.source.subscribe(o); - ++this._count === 1 && (this._connectableSubscription = this.source.connect()); - return new RefCountDisposable(this, subscription); - }; +MuteStream.prototype.mute = function () { + this.muted = true +} - function RefCountDisposable(p, s) { - this._p = p; - this._s = s; - this.isDisposed = false; - } +MuteStream.prototype.unmute = function () { + this.muted = false +} - RefCountDisposable.prototype.dispose = function () { - if (!this.isDisposed) { - this.isDisposed = true; - this._s.dispose(); - --this._p._count === 0 && this._p._connectableSubscription.dispose(); - } - }; +Object.defineProperty(MuteStream.prototype, '_onpipe', { + value: onPipe, + enumerable: false, + writable: true, + configurable: true +}) - return RefCountObservable; - }(ObservableBase)); +function onPipe (src) { + this._src = src +} - var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { - inherits(ConnectableObservable, __super__); - function ConnectableObservable(source, subject) { - this.source = source; - this._connection = null; - this._source = source.asObservable(); - this._subject = subject; - __super__.call(this); - } +Object.defineProperty(MuteStream.prototype, 'isTTY', { + get: getIsTTY, + set: setIsTTY, + enumerable: true, + configurable: true +}) - function ConnectDisposable(parent, subscription) { - this._p = parent; - this._s = subscription; - } +function getIsTTY () { + return( (this._dest) ? this._dest.isTTY + : (this._src) ? this._src.isTTY + : false + ) +} - ConnectDisposable.prototype.dispose = function () { - if (this._s) { - this._s.dispose(); - this._s = null; - this._p._connection = null; - } - }; +// basically just get replace the getter/setter with a regular value +function setIsTTY (isTTY) { + Object.defineProperty(this, 'isTTY', { + value: isTTY, + enumerable: true, + writable: true, + configurable: true + }) +} - ConnectableObservable.prototype.connect = function () { - if (!this._connection) { - if (this._subject.isStopped) { - return disposableEmpty; - } - var subscription = this._source.subscribe(this._subject); - this._connection = new ConnectDisposable(this, subscription); - } - return this._connection; - }; +Object.defineProperty(MuteStream.prototype, 'rows', { + get: function () { + return( this._dest ? this._dest.rows + : this._src ? this._src.rows + : undefined ) + }, enumerable: true, configurable: true }) - ConnectableObservable.prototype._subscribe = function (o) { - return this._subject.subscribe(o); - }; +Object.defineProperty(MuteStream.prototype, 'columns', { + get: function () { + return( this._dest ? this._dest.columns + : this._src ? this._src.columns + : undefined ) + }, enumerable: true, configurable: true }) - ConnectableObservable.prototype.refCount = function () { - return new RefCountObservable(this); - }; - return ConnectableObservable; - }(Observable)); +MuteStream.prototype.pipe = function (dest, options) { + this._dest = dest + return Stream.prototype.pipe.call(this, dest, options) +} - /** - * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence - * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) - * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. - */ - observableProto.singleInstance = function() { - var source = this, hasObservable = false, observable; +MuteStream.prototype.pause = function () { + if (this._src) return this._src.pause() +} - function getObservable() { - if (!hasObservable) { - hasObservable = true; - observable = source['finally'](function() { hasObservable = false; }).publish().refCount(); +MuteStream.prototype.resume = function () { + if (this._src) return this._src.resume() +} + +MuteStream.prototype.write = function (c) { + if (this.muted) { + if (!this.replace) return true + if (c.match(/^\u001b/)) { + if(c.indexOf(this._prompt) === 0) { + c = c.substr(this._prompt.length); + c = c.replace(/./g, this.replace); + c = this._prompt + c; } - return observable; + this._hadControl = true + return this.emit('data', c) + } else { + if (this._prompt && this._hadControl && + c.indexOf(this._prompt) === 0) { + this._hadControl = false + this.emit('data', this._prompt) + c = c.substr(this._prompt.length) + } + c = c.toString().replace(/./g, this.replace) } + } + this.emit('data', c) +} - return new AnonymousObservable(function(o) { - return getObservable().subscribe(o); - }); - }; +MuteStream.prototype.end = function (c) { + if (this.muted) { + if (c && this.replace) { + c = c.toString().replace(/./g, this.replace) + } else { + c = null + } + } + if (c) this.emit('data', c) + this.emit('end') +} - return Rx; -})); +function proxy (fn) { return function () { + var d = this._dest + var s = this._src + if (d && d[fn]) d[fn].apply(d, arguments) + if (s && s[fn]) s[fn].apply(s, arguments) +}} + +MuteStream.prototype.destroy = proxy('destroy') +MuteStream.prototype.destroySoon = proxy('destroySoon') +MuteStream.prototype.close = proxy('close') -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 260 */ +/* 298 */ /***/ (function(module, exports, __webpack_require__) { -/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. - -;(function (factory) { - var objectTypes = { - 'function': true, - 'object': true - }; - - function checkGlobal(value) { - return (value && value.Object === Object) ? value : null; - } +module.exports = __webpack_require__(574); - var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null; - var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null; - var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global); - var freeSelf = checkGlobal(objectTypes[typeof self] && self); - var freeWindow = checkGlobal(objectTypes[typeof window] && window); - var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null; - var thisGlobal = checkGlobal(objectTypes[typeof this] && this); - var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); +/***/ }), +/* 299 */ +/***/ (function(module, exports, __webpack_require__) { - // Because of build optimizers - if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { - return factory(root, exports, Rx); - }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), - __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); - } else if (typeof module === 'object' && module && module.exports === freeExports) { - module.exports = factory(root, module.exports, require('./rx')); - } else { - root.Rx = factory(root, {}, root.Rx); - } -}.call(this, function (root, exp, Rx, undefined) { +"use strict"; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ - // Aliases - var Scheduler = Rx.Scheduler, - ScheduledItem = Rx.internals.ScheduledItem, - SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive, - PriorityQueue = Rx.internals.PriorityQueue, - inherits = Rx.internals.inherits, - defaultSubComparer = Rx.helpers.defaultSubComparer, - notImplemented = Rx.helpers.notImplemented; - /** Provides a set of extension methods for virtual time scheduling. */ - var VirtualTimeScheduler = Rx.VirtualTimeScheduler = (function (__super__) { - inherits(VirtualTimeScheduler, __super__); +/* eslint-disable no-unused-vars */ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; - /** - * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. - * - * @constructor - * @param {Number} initialClock Initial value for the clock. - * @param {Function} comparer Comparer to determine causality of events based on absolute time. - */ - function VirtualTimeScheduler(initialClock, comparer) { - this.clock = initialClock; - this.comparer = comparer; - this.isEnabled = false; - this.queue = new PriorityQueue(1024); - __super__.call(this); - } +function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } - var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; + return Object(val); +} - VirtualTimeSchedulerPrototype.now = function () { - return this.toAbsoluteTime(this.clock); - }; +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } - VirtualTimeSchedulerPrototype.schedule = function (state, action) { - return this.scheduleAbsolute(state, this.clock, action); - }; + // Detect buggy property enumeration order in older V8 versions. - VirtualTimeSchedulerPrototype.scheduleFuture = function (state, dueTime, action) { - var dt = dueTime instanceof Date ? - this.toRelativeTime(dueTime - this.now()) : - this.toRelativeTime(dueTime); + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } - return this.scheduleRelative(state, dt, action); - }; + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } - /** - * Adds a relative time value to an absolute time value. - * @param {Number} absolute Absolute virtual time value. - * @param {Number} relative Relative virtual time value to add. - * @return {Number} Resulting absolute virtual time sum value. - */ - VirtualTimeSchedulerPrototype.add = notImplemented; + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } - /** - * Converts an absolute time to a number - * @param {Any} The absolute time. - * @returns {Number} The absolute time in ms - */ - VirtualTimeSchedulerPrototype.toAbsoluteTime = notImplemented; + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } +} - /** - * Converts the TimeSpan value to a relative virtual time value. - * @param {Number} timeSpan TimeSpan value to convert. - * @return {Number} Corresponding relative virtual time value. - */ - VirtualTimeSchedulerPrototype.toRelativeTime = notImplemented; +module.exports = shouldUseNative() ? Object.assign : function (target, source) { + var from; + var to = toObject(target); + var symbols; - /** - * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. - * @param {Mixed} state Initial state passed to the action upon the first iteration. - * @param {Number} period Period for running the work periodically. - * @param {Function} action Action to be executed, potentially updating the state. - * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). - */ - VirtualTimeSchedulerPrototype.schedulePeriodic = function (state, period, action) { - var s = new SchedulePeriodicRecursive(this, state, period, action); - return s.start(); - }; + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); - /** - * Schedules an action to be executed after dueTime. - * @param {Mixed} state State passed to the action to be executed. - * @param {Number} dueTime Relative time after which to execute the action. - * @param {Function} action Action to be executed. - * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). - */ - VirtualTimeSchedulerPrototype.scheduleRelative = function (state, dueTime, action) { - var runAt = this.add(this.clock, dueTime); - return this.scheduleAbsolute(state, runAt, action); - }; + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } - /** - * Starts the virtual time scheduler. - */ - VirtualTimeSchedulerPrototype.start = function () { - if (!this.isEnabled) { - this.isEnabled = true; - do { - var next = this.getNext(); - if (next !== null) { - this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); - next.invoke(); - } else { - this.isEnabled = false; - } - } while (this.isEnabled); - } - }; + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } - /** - * Stops the virtual time scheduler. - */ - VirtualTimeSchedulerPrototype.stop = function () { - this.isEnabled = false; - }; + return to; +}; - /** - * Advances the scheduler's clock to the specified time, running all work till that point. - * @param {Number} time Absolute time to advance the scheduler's clock to. - */ - VirtualTimeSchedulerPrototype.advanceTo = function (time) { - var dueToClock = this.comparer(this.clock, time); - if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } - if (dueToClock === 0) { return; } - if (!this.isEnabled) { - this.isEnabled = true; - do { - var next = this.getNext(); - if (next !== null && this.comparer(next.dueTime, time) <= 0) { - this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); - next.invoke(); - } else { - this.isEnabled = false; - } - } while (this.isEnabled); - this.clock = time; - } - }; - /** - * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. - * @param {Number} time Relative time to advance the scheduler's clock by. - */ - VirtualTimeSchedulerPrototype.advanceBy = function (time) { - var dt = this.add(this.clock, time), - dueToClock = this.comparer(this.clock, dt); - if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } - if (dueToClock === 0) { return; } +/***/ }), +/* 300 */ +/***/ (function(module, exports, __webpack_require__) { - this.advanceTo(dt); - }; +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory){ + 'use strict'; - /** - * Advances the scheduler's clock by the specified relative time. - * @param {Number} time Relative time to advance the scheduler's clock by. - */ - VirtualTimeSchedulerPrototype.sleep = function (time) { - var dt = this.add(this.clock, time); - if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } + /*istanbul ignore next:cant test*/ + if (typeof module === 'object' && typeof module.exports === 'object') { + module.exports = factory(); + } else if (true) { + // AMD. Register as an anonymous module. + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else { + // Browser globals + root.objectPath = factory(); + } +})(this, function(){ + 'use strict'; - this.clock = dt; - }; + var toStr = Object.prototype.toString; + function hasOwnProperty(obj, prop) { + if(obj == null) { + return false + } + //to handle objects with null prototypes (too edge case?) + return Object.prototype.hasOwnProperty.call(obj, prop) + } - /** - * Gets the next scheduled item to be executed. - * @returns {ScheduledItem} The next scheduled item. - */ - VirtualTimeSchedulerPrototype.getNext = function () { - while (this.queue.length > 0) { - var next = this.queue.peek(); - if (next.isCancelled()) { - this.queue.dequeue(); + function isEmpty(value){ + if (!value) { + return true; + } + if (isArray(value) && value.length === 0) { + return true; + } else if (typeof value !== 'string') { + for (var i in value) { + if (hasOwnProperty(value, i)) { + return false; + } + } + return true; + } + return false; + } + + function toString(type){ + return toStr.call(type); + } + + function isObject(obj){ + return typeof obj === 'object' && toString(obj) === "[object Object]"; + } + + var isArray = Array.isArray || function(obj){ + /*istanbul ignore next:cant test*/ + return toStr.call(obj) === '[object Array]'; + } + + function isBoolean(obj){ + return typeof obj === 'boolean' || toString(obj) === '[object Boolean]'; + } + + function getKey(key){ + var intKey = parseInt(key); + if (intKey.toString() === key) { + return intKey; + } + return key; + } + + function factory(options) { + options = options || {} + + var objectPath = function(obj) { + return Object.keys(objectPath).reduce(function(proxy, prop) { + if(prop === 'create') { + return proxy; + } + + /*istanbul ignore else*/ + if (typeof objectPath[prop] === 'function') { + proxy[prop] = objectPath[prop].bind(objectPath, obj); + } + + return proxy; + }, {}); + }; + + function hasShallowProperty(obj, prop) { + return (options.includeInheritedProps || (typeof prop === 'number' && Array.isArray(obj)) || hasOwnProperty(obj, prop)) + } + + function getShallowProperty(obj, prop) { + if (hasShallowProperty(obj, prop)) { + return obj[prop]; + } + } + + function set(obj, path, value, doNotReplace){ + if (typeof path === 'number') { + path = [path]; + } + if (!path || path.length === 0) { + return obj; + } + if (typeof path === 'string') { + return set(obj, path.split('.').map(getKey), value, doNotReplace); + } + var currentPath = path[0]; + var currentValue = getShallowProperty(obj, currentPath); + if (path.length === 1) { + if (currentValue === void 0 || !doNotReplace) { + obj[currentPath] = value; + } + return currentValue; + } + + if (currentValue === void 0) { + //check if we assume an array + if(typeof path[1] === 'number') { + obj[currentPath] = []; } else { - return next; + obj[currentPath] = {}; } } - return null; - }; - /** - * Schedules an action to be executed at dueTime. - * @param {Mixed} state State passed to the action to be executed. - * @param {Number} dueTime Absolute time at which to execute the action. - * @param {Function} action Action to be executed. - * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). - */ - VirtualTimeSchedulerPrototype.scheduleAbsolute = function (state, dueTime, action) { - var self = this; + return set(obj[currentPath], path.slice(1), value, doNotReplace); + } - function run(scheduler, state1) { - self.queue.remove(si); - return action(scheduler, state1); + objectPath.has = function (obj, path) { + if (typeof path === 'number') { + path = [path]; + } else if (typeof path === 'string') { + path = path.split('.'); } - var si = new ScheduledItem(this, state, run, dueTime, this.comparer); - this.queue.enqueue(si); + if (!path || path.length === 0) { + return !!obj; + } - return si.disposable; - }; + for (var i = 0; i < path.length; i++) { + var j = getKey(path[i]); - return VirtualTimeScheduler; - }(Scheduler)); + if((typeof j === 'number' && isArray(obj) && j < obj.length) || + (options.includeInheritedProps ? (j in Object(obj)) : hasOwnProperty(obj, j))) { + obj = obj[j]; + } else { + return false; + } + } - /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ - Rx.HistoricalScheduler = (function (__super__) { - inherits(HistoricalScheduler, __super__); + return true; + }; - /** - * Creates a new historical scheduler with the specified initial clock value. - * @constructor - * @param {Number} initialClock Initial value for the clock. - * @param {Function} comparer Comparer to determine causality of events based on absolute time. - */ - function HistoricalScheduler(initialClock, comparer) { - var clock = initialClock == null ? 0 : initialClock; - var cmp = comparer || defaultSubComparer; - __super__.call(this, clock, cmp); - } + objectPath.ensureExists = function (obj, path, value){ + return set(obj, path, value, true); + }; - var HistoricalSchedulerProto = HistoricalScheduler.prototype; + objectPath.set = function (obj, path, value, doNotReplace){ + return set(obj, path, value, doNotReplace); + }; - /** - * Adds a relative time value to an absolute time value. - * @param {Number} absolute Absolute virtual time value. - * @param {Number} relative Relative virtual time value to add. - * @return {Number} Resulting absolute virtual time sum value. - */ - HistoricalSchedulerProto.add = function (absolute, relative) { - return absolute + relative; + objectPath.insert = function (obj, path, value, at){ + var arr = objectPath.get(obj, path); + at = ~~at; + if (!isArray(arr)) { + arr = []; + objectPath.set(obj, path, arr); + } + arr.splice(at, 0, value); }; - HistoricalSchedulerProto.toAbsoluteTime = function (absolute) { - return new Date(absolute).getTime(); + objectPath.empty = function(obj, path) { + if (isEmpty(path)) { + return void 0; + } + if (obj == null) { + return void 0; + } + + var value, i; + if (!(value = objectPath.get(obj, path))) { + return void 0; + } + + if (typeof value === 'string') { + return objectPath.set(obj, path, ''); + } else if (isBoolean(value)) { + return objectPath.set(obj, path, false); + } else if (typeof value === 'number') { + return objectPath.set(obj, path, 0); + } else if (isArray(value)) { + value.length = 0; + } else if (isObject(value)) { + for (i in value) { + if (hasShallowProperty(value, i)) { + delete value[i]; + } + } + } else { + return objectPath.set(obj, path, null); + } }; - /** - * Converts the TimeSpan value to a relative virtual time value. - * @memberOf HistoricalScheduler - * @param {Number} timeSpan TimeSpan value to convert. - * @return {Number} Corresponding relative virtual time value. - */ - HistoricalSchedulerProto.toRelativeTime = function (timeSpan) { - return timeSpan; + objectPath.push = function (obj, path /*, values */){ + var arr = objectPath.get(obj, path); + if (!isArray(arr)) { + arr = []; + objectPath.set(obj, path, arr); + } + + arr.push.apply(arr, Array.prototype.slice.call(arguments, 2)); }; - return HistoricalScheduler; - }(Rx.VirtualTimeScheduler)); + objectPath.coalesce = function (obj, paths, defaultValue) { + var value; - return Rx; -})); + for (var i = 0, len = paths.length; i < len; i++) { + if ((value = objectPath.get(obj, paths[i])) !== void 0) { + return value; + } + } -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) + return defaultValue; + }; -/***/ }), -/* 261 */ -/***/ (function(module, exports, __webpack_require__) { + objectPath.get = function (obj, path, defaultValue){ + if (typeof path === 'number') { + path = [path]; + } + if (!path || path.length === 0) { + return obj; + } + if (obj == null) { + return defaultValue; + } + if (typeof path === 'string') { + return objectPath.get(obj, path.split('.'), defaultValue); + } -// Note: since nyc uses this module to output coverage, any lines -// that are in the direct sync flow of nyc's outputCoverage are -// ignored, since we can never get coverage for them. -var assert = __webpack_require__(22) -var signals = __webpack_require__(612) + var currentPath = getKey(path[0]); + var nextObj = getShallowProperty(obj, currentPath) + if (nextObj === void 0) { + return defaultValue; + } -var EE = __webpack_require__(49) -/* istanbul ignore if */ -if (typeof EE !== 'function') { - EE = EE.EventEmitter -} + if (path.length === 1) { + return nextObj; + } -var emitter -if (process.__signal_exit_emitter__) { - emitter = process.__signal_exit_emitter__ -} else { - emitter = process.__signal_exit_emitter__ = new EE() - emitter.count = 0 - emitter.emitted = {} -} + return objectPath.get(obj[currentPath], path.slice(1), defaultValue); + }; -// Because this emitter is a global, we have to check to see if a -// previous version of this library failed to enable infinite listeners. -// I know what you're about to say. But literally everything about -// signal-exit is a compromise with evil. Get used to it. -if (!emitter.infinite) { - emitter.setMaxListeners(Infinity) - emitter.infinite = true -} + objectPath.del = function del(obj, path) { + if (typeof path === 'number') { + path = [path]; + } -module.exports = function (cb, opts) { - assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') + if (obj == null) { + return obj; + } - if (loaded === false) { - load() - } + if (isEmpty(path)) { + return obj; + } + if(typeof path === 'string') { + return objectPath.del(obj, path.split('.')); + } - var ev = 'exit' - if (opts && opts.alwaysLast) { - ev = 'afterexit' - } + var currentPath = getKey(path[0]); + if (!hasShallowProperty(obj, currentPath)) { + return obj; + } - var remove = function () { - emitter.removeListener(ev, cb) - if (emitter.listeners('exit').length === 0 && - emitter.listeners('afterexit').length === 0) { - unload() + if(path.length === 1) { + if (isArray(obj)) { + obj.splice(currentPath, 1); + } else { + delete obj[currentPath]; + } + } else { + return objectPath.del(obj[currentPath], path.slice(1)); + } + + return obj; } + + return objectPath; } - emitter.on(ev, cb) - return remove -} + var mod = factory(); + mod.create = factory; + mod.withInheritedProps = factory({includeInheritedProps: true}) + return mod; +}); -module.exports.unload = unload -function unload () { - if (!loaded) { - return - } - loaded = false - signals.forEach(function (sig) { - try { - process.removeListener(sig, sigListeners[sig]) - } catch (er) {} - }) - process.emit = originalProcessEmit - process.reallyExit = originalProcessReallyExit - emitter.count -= 1 -} +/***/ }), +/* 301 */ +/***/ (function(module, exports, __webpack_require__) { -function emit (event, code, signal) { - if (emitter.emitted[event]) { - return - } - emitter.emitted[event] = true - emitter.emit(event, code, signal) -} +var once = __webpack_require__(72) +var eos = __webpack_require__(285) +var fs = __webpack_require__(5) // we only need fs to get the ReadStream and WriteStream prototypes -// { <signal>: <listener fn>, ... } -var sigListeners = {} -signals.forEach(function (sig) { - sigListeners[sig] = function listener () { - // If there are no other listeners, an exit is coming! - // Simplest way: remove us and then re-send the signal. - // We know that this will kill the process, so we can - // safely emit now. - var listeners = process.listeners(sig) - if (listeners.length === emitter.count) { - unload() - emit('exit', null, sig) - /* istanbul ignore next */ - emit('afterexit', null, sig) - /* istanbul ignore next */ - process.kill(process.pid, sig) - } - } -}) +var noop = function () {} -module.exports.signals = function () { - return signals +var isFn = function (fn) { + return typeof fn === 'function' } -module.exports.load = load +var isFS = function (stream) { + if (!fs) return false // browser + return (stream instanceof (fs.ReadStream || noop) || stream instanceof (fs.WriteStream || noop)) && isFn(stream.close) +} -var loaded = false +var isRequest = function (stream) { + return stream.setHeader && isFn(stream.abort) +} -function load () { - if (loaded) { - return - } - loaded = true +var destroyer = function (stream, reading, writing, callback) { + callback = once(callback) - // This is the number of onSignalExit's that are in play. - // It's important so that we can count the correct number of - // listeners on signals, and don't wait for the other one to - // handle it instead of us. - emitter.count += 1 + var closed = false + stream.on('close', function () { + closed = true + }) - signals = signals.filter(function (sig) { - try { - process.on(sig, sigListeners[sig]) - return true - } catch (er) { - return false - } + eos(stream, {readable: reading, writable: writing}, function (err) { + if (err) return callback(err) + closed = true + callback() }) - process.emit = processEmit - process.reallyExit = processReallyExit + var destroyed = false + return function (err) { + if (closed) return + if (destroyed) return + destroyed = true + + if (isFS(stream)) return stream.close() // use close for fs streams to avoid fd leaks + if (isRequest(stream)) return stream.abort() // request.destroy just do .end - .abort is what we want + + if (isFn(stream.destroy)) return stream.destroy() + + callback(err || new Error('stream was destroyed')) + } } -var originalProcessReallyExit = process.reallyExit -function processReallyExit (code) { - process.exitCode = code || 0 - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - /* istanbul ignore next */ - originalProcessReallyExit.call(process, process.exitCode) +var call = function (fn) { + fn() } -var originalProcessEmit = process.emit -function processEmit (ev, arg) { - if (ev === 'exit') { - if (arg !== undefined) { - process.exitCode = arg - } - var ret = originalProcessEmit.apply(this, arguments) - emit('exit', process.exitCode, null) - /* istanbul ignore next */ - emit('afterexit', process.exitCode, null) - return ret - } else { - return originalProcessEmit.apply(this, arguments) - } +var pipe = function (from, to) { + return from.pipe(to) } +var pump = function () { + var streams = Array.prototype.slice.call(arguments) + var callback = isFn(streams[streams.length - 1] || noop) && streams.pop() || noop -/***/ }), -/* 262 */ -/***/ (function(module, exports, __webpack_require__) { + if (Array.isArray(streams[0])) streams = streams[0] + if (streams.length < 2) throw new Error('pump requires two streams per minimum') -module.exports = __webpack_require__(613); + var error + var destroys = streams.map(function (stream, i) { + var reading = i < streams.length - 1 + var writing = i > 0 + return destroyer(stream, reading, writing, function (err) { + if (!error) error = err + if (err) destroys.forEach(call) + if (reading) return + destroys.forEach(call) + callback(error) + }) + }) -/***/ }), -/* 263 */ -/***/ (function(module, exports, __webpack_require__) { + return streams.reduce(pipe) +} -// Copyright 2017 Joyent, Inc. +module.exports = pump -module.exports = { - DiffieHellman: DiffieHellman, - generateECDSA: generateECDSA, - generateED25519: generateED25519 -}; -var assert = __webpack_require__(9); -var crypto = __webpack_require__(7); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); -var ed; -var nacl; +/***/ }), +/* 302 */ +/***/ (function(module, exports, __webpack_require__) { -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); +"use strict"; -var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined); -var ecdh, ec, jsbn; +var replace = String.prototype.replace; +var percentTwenties = /%20/g; -function DiffieHellman(key) { - utils.assertCompatible(key, Key, [1, 4], 'key'); - this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]); - this._algo = key.type; - this._curve = key.curve; - this._key = key; - if (key.type === 'dsa') { - if (!CRYPTO_HAVE_ECDH) { - throw (new Error('Due to bugs in the node 0.10 ' + - 'crypto API, node 0.12.x or later is required ' + - 'to use DH')); - } - this._dh = crypto.createDiffieHellman( - key.part.p.data, undefined, - key.part.g.data, undefined); - this._p = key.part.p; - this._g = key.part.g; - if (this._isPriv) - this._dh.setPrivateKey(key.part.x.data); - this._dh.setPublicKey(key.part.y.data); - - } else if (key.type === 'ecdsa') { - if (!CRYPTO_HAVE_ECDH) { - if (ecdh === undefined) - ecdh = __webpack_require__(229); - if (ec === undefined) - ec = __webpack_require__(93); - if (jsbn === undefined) - jsbn = __webpack_require__(40).BigInteger; - - this._ecParams = new X9ECParameters(this._curve); +module.exports = { + 'default': 'RFC3986', + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return value; + } + }, + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' +}; - if (this._isPriv) { - this._priv = new ECPrivate( - this._ecParams, key.part.d.data); - } - return; - } - var curve = { - 'nistp256': 'prime256v1', - 'nistp384': 'secp384r1', - 'nistp521': 'secp521r1' - }[key.curve]; - this._dh = crypto.createECDH(curve); - if (typeof (this._dh) !== 'object' || - typeof (this._dh.setPrivateKey) !== 'function') { - CRYPTO_HAVE_ECDH = false; - DiffieHellman.call(this, key); - return; - } - if (this._isPriv) - this._dh.setPrivateKey(key.part.d.data); - this._dh.setPublicKey(key.part.Q.data); +/***/ }), +/* 303 */ +/***/ (function(module, exports, __webpack_require__) { - } else if (key.type === 'curve25519') { - if (ed === undefined) - ed = __webpack_require__(154); +"use strict"; - if (this._isPriv) { - this._priv = key.part.r.data; - if (this._priv[0] === 0x00) - this._priv = this._priv.slice(1); - this._priv = this._priv.slice(0, 32); - } - } else { - throw (new Error('DH not supported for ' + key.type + ' keys')); - } -} +var stringify = __webpack_require__(590); +var parse = __webpack_require__(589); +var formats = __webpack_require__(302); -DiffieHellman.prototype.getPublicKey = function () { - if (this._isPriv) - return (this._key.toPublic()); - return (this._key); +module.exports = { + formats: formats, + parse: parse, + stringify: stringify }; -DiffieHellman.prototype.getPrivateKey = function () { - if (this._isPriv) - return (this._key); - else - return (undefined); -}; -DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey; -DiffieHellman.prototype._keyCheck = function (pk, isPub) { - assert.object(pk, 'key'); - if (!isPub) - utils.assertCompatible(pk, PrivateKey, [1, 3], 'key'); - utils.assertCompatible(pk, Key, [1, 4], 'key'); +/***/ }), +/* 304 */ +/***/ (function(module, exports, __webpack_require__) { - if (pk.type !== this._algo) { - throw (new Error('A ' + pk.type + ' key cannot be used in ' + - this._algo + ' Diffie-Hellman')); - } +"use strict"; - if (pk.curve !== this._curve) { - throw (new Error('A key from the ' + pk.curve + ' curve ' + - 'cannot be used with a ' + this._curve + - ' Diffie-Hellman')); - } - if (pk.type === 'dsa') { - assert.deepEqual(pk.part.p, this._p, - 'DSA key prime does not match'); - assert.deepEqual(pk.part.g, this._g, - 'DSA key generator does not match'); - } -}; +var has = Object.prototype.hasOwnProperty; -DiffieHellman.prototype.setKey = function (pk) { - this._keyCheck(pk); +var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } - if (pk.type === 'dsa') { - this._dh.setPrivateKey(pk.part.x.data); - this._dh.setPublicKey(pk.part.y.data); + return array; +}()); - } else if (pk.type === 'ecdsa') { - if (CRYPTO_HAVE_ECDH) { - this._dh.setPrivateKey(pk.part.d.data); - this._dh.setPublicKey(pk.part.Q.data); - } else { - this._priv = new ECPrivate( - this._ecParams, pk.part.d.data); - } +exports.arrayToObject = function (source, options) { + var obj = options && options.plainObjects ? Object.create(null) : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } - } else if (pk.type === 'curve25519') { - this._priv = pk.part.r.data; - if (this._priv[0] === 0x00) - this._priv = this._priv.slice(1); - this._priv = this._priv.slice(0, 32); - } - this._key = pk; - this._isPriv = true; + return obj; }; -DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey; -DiffieHellman.prototype.computeSecret = function (otherpk) { - this._keyCheck(otherpk, true); - if (!this._isPriv) - throw (new Error('DH exchange has not been initialized with ' + - 'a private key yet')); +exports.merge = function (target, source, options) { + if (!source) { + return target; + } - var pub; - if (this._algo === 'dsa') { - return (this._dh.computeSecret( - otherpk.part.y.data)); + if (typeof source !== 'object') { + if (Array.isArray(target)) { + target.push(source); + } else if (typeof target === 'object') { + if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { + target[source] = true; + } + } else { + return [target, source]; + } - } else if (this._algo === 'ecdsa') { - if (CRYPTO_HAVE_ECDH) { - return (this._dh.computeSecret( - otherpk.part.Q.data)); - } else { - pub = new ECPublic( - this._ecParams, otherpk.part.Q.data); - return (this._priv.deriveSharedSecret(pub)); - } + return target; + } - } else if (this._algo === 'curve25519') { - pub = otherpk.part.R.data; - if (pub[0] === 0x00) - pub = pub.slice(1); + if (typeof target !== 'object') { + return [target].concat(source); + } - var secret = ed.dh.computeKey( - this._priv.toString('binary'), - pub.toString('binary')); + var mergeTarget = target; + if (Array.isArray(target) && !Array.isArray(source)) { + mergeTarget = exports.arrayToObject(target, options); + } - return (new Buffer(secret, 'binary')); - } + if (Array.isArray(target) && Array.isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + if (target[i] && typeof target[i] === 'object') { + target[i] = exports.merge(target[i], item, options); + } else { + target.push(item); + } + } else { + target[i] = item; + } + }); + return target; + } - throw (new Error('Invalid algorithm: ' + this._algo)); + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (Object.prototype.hasOwnProperty.call(acc, key)) { + acc[key] = exports.merge(acc[key], value, options); + } else { + acc[key] = value; + } + return acc; + }, mergeTarget); }; -DiffieHellman.prototype.generateKey = function () { - var parts = []; - var priv, pub; - if (this._algo === 'dsa') { - this._dh.generateKeys(); +exports.decode = function (str) { + try { + return decodeURIComponent(str.replace(/\+/g, ' ')); + } catch (e) { + return str; + } +}; - parts.push({name: 'p', data: this._p.data}); - parts.push({name: 'q', data: this._key.part.q.data}); - parts.push({name: 'g', data: this._g.data}); - parts.push({name: 'y', data: this._dh.getPublicKey()}); - parts.push({name: 'x', data: this._dh.getPrivateKey()}); - this._key = new PrivateKey({ - type: 'dsa', - parts: parts - }); - this._isPriv = true; - return (this._key); +exports.encode = function (str) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } - } else if (this._algo === 'ecdsa') { - if (CRYPTO_HAVE_ECDH) { - this._dh.generateKeys(); + var string = typeof str === 'string' ? str : String(str); - parts.push({name: 'curve', - data: new Buffer(this._curve)}); - parts.push({name: 'Q', data: this._dh.getPublicKey()}); - parts.push({name: 'd', data: this._dh.getPrivateKey()}); - this._key = new PrivateKey({ - type: 'ecdsa', - curve: this._curve, - parts: parts - }); - this._isPriv = true; - return (this._key); + var out = ''; + for (var i = 0; i < string.length; ++i) { + var c = string.charCodeAt(i); - } else { - var n = this._ecParams.getN(); - var r = new jsbn(crypto.randomBytes(n.bitLength())); - var n1 = n.subtract(jsbn.ONE); - priv = r.mod(n1).add(jsbn.ONE); - pub = this._ecParams.getG().multiply(priv); + if ( + c === 0x2D || // - + c === 0x2E || // . + c === 0x5F || // _ + c === 0x7E || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5A) || // a-z + (c >= 0x61 && c <= 0x7A) // A-Z + ) { + out += string.charAt(i); + continue; + } - priv = new Buffer(priv.toByteArray()); - pub = new Buffer(this._ecParams.getCurve(). - encodePointHex(pub), 'hex'); + if (c < 0x80) { + out = out + hexTable[c]; + continue; + } - this._priv = new ECPrivate(this._ecParams, priv); + if (c < 0x800) { + out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } - parts.push({name: 'curve', - data: new Buffer(this._curve)}); - parts.push({name: 'Q', data: pub}); - parts.push({name: 'd', data: priv}); + if (c < 0xD800 || c >= 0xE000) { + out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); + continue; + } - this._key = new PrivateKey({ - type: 'ecdsa', - curve: this._curve, - parts: parts - }); - this._isPriv = true; - return (this._key); - } + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); + out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; // eslint-disable-line max-len + } - } else if (this._algo === 'curve25519') { - priv = ed.dh.generateKey(); - pub = ed.dh.publicKey(priv); - this._priv = priv = new Buffer(priv, 'binary'); - pub = new Buffer(pub, 'binary'); + return out; +}; - parts.push({name: 'R', data: pub}); - parts.push({name: 'r', data: Buffer.concat([priv, pub])}); - this._key = new PrivateKey({ - type: 'curve25519', - parts: parts - }); - this._isPriv = true; - return (this._key); - } +exports.compact = function (obj, references) { + if (typeof obj !== 'object' || obj === null) { + return obj; + } - throw (new Error('Invalid algorithm: ' + this._algo)); -}; -DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey; + var refs = references || []; + var lookup = refs.indexOf(obj); + if (lookup !== -1) { + return refs[lookup]; + } -/* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */ + refs.push(obj); -function X9ECParameters(name) { - var params = algs.curves[name]; - assert.object(params); + if (Array.isArray(obj)) { + var compacted = []; - var p = new jsbn(params.p); - var a = new jsbn(params.a); - var b = new jsbn(params.b); - var n = new jsbn(params.n); - var h = jsbn.ONE; - var curve = new ec.ECCurveFp(p, a, b); - var G = curve.decodePointHex(params.G.toString('hex')); + for (var i = 0; i < obj.length; ++i) { + if (obj[i] && typeof obj[i] === 'object') { + compacted.push(exports.compact(obj[i], refs)); + } else if (typeof obj[i] !== 'undefined') { + compacted.push(obj[i]); + } + } - this.curve = curve; - this.g = G; - this.n = n; - this.h = h; -} -X9ECParameters.prototype.getCurve = function () { return (this.curve); }; -X9ECParameters.prototype.getG = function () { return (this.g); }; -X9ECParameters.prototype.getN = function () { return (this.n); }; -X9ECParameters.prototype.getH = function () { return (this.h); }; + return compacted; + } -function ECPublic(params, buffer) { - this._params = params; - if (buffer[0] === 0x00) - buffer = buffer.slice(1); - this._pub = params.getCurve().decodePointHex(buffer.toString('hex')); -} + var keys = Object.keys(obj); + keys.forEach(function (key) { + obj[key] = exports.compact(obj[key], refs); + }); -function ECPrivate(params, buffer) { - this._params = params; - this._priv = new jsbn(utils.mpNormalize(buffer)); -} -ECPrivate.prototype.deriveSharedSecret = function (pubKey) { - assert.ok(pubKey instanceof ECPublic); - var S = pubKey._pub.multiply(this._priv); - return (new Buffer(S.getX().toBigInteger().toByteArray())); + return obj; }; -function generateED25519() { - if (nacl === undefined) - nacl = __webpack_require__(110); +exports.isRegExp = function (obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +}; - var pair = nacl.sign.keyPair(); - var priv = new Buffer(pair.secretKey); - var pub = new Buffer(pair.publicKey); - assert.strictEqual(priv.length, 64); - assert.strictEqual(pub.length, 32); +exports.isBuffer = function (obj) { + if (obj === null || typeof obj === 'undefined') { + return false; + } - var parts = []; - parts.push({name: 'R', data: pub}); - parts.push({name: 'r', data: priv}); - var key = new PrivateKey({ - type: 'ed25519', - parts: parts - }); - return (key); -} + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +}; -/* Generates a new ECDSA private key on a given curve. */ -function generateECDSA(curve) { - var parts = []; - var key; - if (CRYPTO_HAVE_ECDH) { - /* - * Node crypto doesn't expose key generation directly, but the - * ECDH instances can generate keys. It turns out this just - * calls into the OpenSSL generic key generator, and we can - * read its output happily without doing an actual DH. So we - * use that here. - */ - var osCurve = { - 'nistp256': 'prime256v1', - 'nistp384': 'secp384r1', - 'nistp521': 'secp521r1' - }[curve]; +/***/ }), +/* 305 */ +/***/ (function(module, exports, __webpack_require__) { - var dh = crypto.createECDH(osCurve); - dh.generateKeys(); +"use strict"; - parts.push({name: 'curve', - data: new Buffer(curve)}); - parts.push({name: 'Q', data: dh.getPublicKey()}); - parts.push({name: 'd', data: dh.getPrivateKey()}); - key = new PrivateKey({ - type: 'ecdsa', - curve: curve, - parts: parts - }); - return (key); +module.exports = Readable; - } else { - if (ecdh === undefined) - ecdh = __webpack_require__(229); - if (ec === undefined) - ec = __webpack_require__(93); - if (jsbn === undefined) - jsbn = __webpack_require__(40).BigInteger; +/*<replacement>*/ +var processNextTick = __webpack_require__(222); +/*</replacement>*/ - var ecParams = new X9ECParameters(curve); +/*<replacement>*/ +var isArray = __webpack_require__(294); +/*</replacement>*/ - /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */ - var n = ecParams.getN(); - /* - * The crypto.randomBytes() function can only give us whole - * bytes, so taking a nod from X9.62, we round up. - */ - var cByteLen = Math.ceil((n.bitLength() + 64) / 8); - var c = new jsbn(crypto.randomBytes(cByteLen)); +/*<replacement>*/ +var Duplex; +/*</replacement>*/ - var n1 = n.subtract(jsbn.ONE); - var priv = c.mod(n1).add(jsbn.ONE); - var pub = ecParams.getG().multiply(priv); +Readable.ReadableState = ReadableState; - priv = new Buffer(priv.toByteArray()); - pub = new Buffer(ecParams.getCurve(). - encodePointHex(pub), 'hex'); +/*<replacement>*/ +var EE = __webpack_require__(46).EventEmitter; - parts.push({name: 'curve', data: new Buffer(curve)}); - parts.push({name: 'Q', data: pub}); - parts.push({name: 'd', data: priv}); +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/*</replacement>*/ - key = new PrivateKey({ - type: 'ecdsa', - curve: curve, - parts: parts - }); - return (key); - } -} +/*<replacement>*/ +var Stream = __webpack_require__(308); +/*</replacement>*/ +var Buffer = __webpack_require__(120).Buffer; +/*<replacement>*/ +var bufferShim = __webpack_require__(174); +/*</replacement>*/ -/***/ }), -/* 264 */ -/***/ (function(module, exports, __webpack_require__) { - -// Copyright 2015 Joyent, Inc. - -module.exports = { - Verifier: Verifier, - Signer: Signer -}; +/*<replacement>*/ +var util = __webpack_require__(110); +util.inherits = __webpack_require__(39); +/*</replacement>*/ -var nacl; -var stream = __webpack_require__(20); -var util = __webpack_require__(2); -var assert = __webpack_require__(9); -var Signature = __webpack_require__(33); +/*<replacement>*/ +var debugUtil = __webpack_require__(2); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/*</replacement>*/ -function Verifier(key, hashAlgo) { - if (nacl === undefined) - nacl = __webpack_require__(110); +var BufferList = __webpack_require__(596); +var StringDecoder; - if (hashAlgo.toLowerCase() !== 'sha512') - throw (new Error('ED25519 only supports the use of ' + - 'SHA-512 hashes')); +util.inherits(Readable, Stream); - this.key = key; - this.chunks = []; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - stream.Writable.call(this, {}); +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } } -util.inherits(Verifier, stream.Writable); - -Verifier.prototype._write = function (chunk, enc, cb) { - this.chunks.push(chunk); - cb(); -}; - -Verifier.prototype.update = function (chunk) { - if (typeof (chunk) === 'string') - chunk = new Buffer(chunk, 'binary'); - this.chunks.push(chunk); -}; -Verifier.prototype.verify = function (signature, fmt) { - var sig; - if (Signature.isSignature(signature, [2, 0])) { - if (signature.type !== 'ed25519') - return (false); - sig = signature.toBuffer('raw'); - - } else if (typeof (signature) === 'string') { - sig = new Buffer(signature, 'base64'); +function ReadableState(options, stream) { + Duplex = Duplex || __webpack_require__(86); - } else if (Signature.isSignature(signature, [1, 0])) { - throw (new Error('signature was created by too old ' + - 'a version of sshpk and cannot be verified')); - } + options = options || {}; - assert.buffer(sig); - return (nacl.sign.detached.verify( - new Uint8Array(Buffer.concat(this.chunks)), - new Uint8Array(sig), - new Uint8Array(this.key.part.R.data))); -}; + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; -function Signer(key, hashAlgo) { - if (nacl === undefined) - nacl = __webpack_require__(110); + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - if (hashAlgo.toLowerCase() !== 'sha512') - throw (new Error('ED25519 only supports the use of ' + - 'SHA-512 hashes')); + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - this.key = key; - this.chunks = []; + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; - stream.Writable.call(this, {}); -} -util.inherits(Signer, stream.Writable); + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; -Signer.prototype._write = function (chunk, enc, cb) { - this.chunks.push(chunk); - cb(); -}; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; -Signer.prototype.update = function (chunk) { - if (typeof (chunk) === 'string') - chunk = new Buffer(chunk, 'binary'); - this.chunks.push(chunk); -}; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; -Signer.prototype.sign = function () { - var sig = nacl.sign.detached( - new Uint8Array(Buffer.concat(this.chunks)), - new Uint8Array(this.key.part.r.data)); - var sigBuf = new Buffer(sig); - var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw'); - sigObj.hashAlgorithm = 'sha512'; - return (sigObj); -}; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; -/***/ }), -/* 265 */ -/***/ (function(module, exports, __webpack_require__) { + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -// Copyright 2015 Joyent, Inc. + // if true, a maybeReadMore has been scheduled + this.readingMore = false; -module.exports = { - read: read, - write: write -}; + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = __webpack_require__(309).StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} -var assert = __webpack_require__(9); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); +function Readable(options) { + Duplex = Duplex || __webpack_require__(86); -var pem = __webpack_require__(41); -var ssh = __webpack_require__(266); -var rfc4253 = __webpack_require__(48); + if (!(this instanceof Readable)) return new Readable(options); -function read(buf, options) { - if (typeof (buf) === 'string') { - if (buf.trim().match(/^[-]+[ ]*BEGIN/)) - return (pem.read(buf, options)); - if (buf.match(/^\s*ssh-[a-z]/)) - return (ssh.read(buf, options)); - if (buf.match(/^\s*ecdsa-/)) - return (ssh.read(buf, options)); - buf = new Buffer(buf, 'binary'); - } else { - assert.buffer(buf); - if (findPEMHeader(buf)) - return (pem.read(buf, options)); - if (findSSHHeader(buf)) - return (ssh.read(buf, options)); - } - if (buf.readUInt32BE(0) < buf.length) - return (rfc4253.read(buf, options)); - throw (new Error('Failed to auto-detect format of key')); -} + this._readableState = new ReadableState(options, this); -function findSSHHeader(buf) { - var offset = 0; - while (offset < buf.length && - (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) - ++offset; - if (offset + 4 <= buf.length && - buf.slice(offset, offset + 4).toString('ascii') === 'ssh-') - return (true); - if (offset + 6 <= buf.length && - buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-') - return (true); - return (false); -} + // legacy + this.readable = true; -function findPEMHeader(buf) { - var offset = 0; - while (offset < buf.length && - (buf[offset] === 32 || buf[offset] === 10)) - ++offset; - if (buf[offset] !== 45) - return (false); - while (offset < buf.length && - (buf[offset] === 45)) - ++offset; - while (offset < buf.length && - (buf[offset] === 32)) - ++offset; - if (offset + 5 > buf.length || - buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN') - return (false); - return (true); -} + if (options && typeof options.read === 'function') this._read = options.read; -function write(key, options) { - throw (new Error('"auto" format cannot be used for writing')); + Stream.call(this); } +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; -/***/ }), -/* 266 */ -/***/ (function(module, exports, __webpack_require__) { + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = bufferShim.from(chunk, encoding); + encoding = ''; + } + } -// Copyright 2015 Joyent, Inc. + return readableAddChunk(this, state, chunk, encoding, false); +}; -module.exports = { - read: read, - write: write +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); }; -var assert = __webpack_require__(9); -var rfc4253 = __webpack_require__(48); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; -var sshpriv = __webpack_require__(107); +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } -/*JSSTYLED*/ -var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([\n \t]+([^\n]+))?$/; -/*JSSTYLED*/ -var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/ \t\n]+[=]*)(.*)$/; + if (!addToFront) state.reading = false; -function read(buf, options) { - if (typeof (buf) !== 'string') { - assert.buffer(buf, 'buf'); - buf = buf.toString('ascii'); - } + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - var trimmed = buf.trim().replace(/[\\\r]/g, ''); - var m = trimmed.match(SSHKEY_RE); - if (!m) - m = trimmed.match(SSHKEY_RE2); - assert.ok(m, 'key must match regex'); + if (state.needReadable) emitReadable(stream); + } + } - var type = rfc4253.algToKeyType(m[1]); - var kbuf = new Buffer(m[2], 'base64'); + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } - /* - * This is a bit tricky. If we managed to parse the key and locate the - * key comment with the regex, then do a non-partial read and assert - * that we have consumed all bytes. If we couldn't locate the key - * comment, though, there may be whitespace shenanigans going on that - * have conjoined the comment to the rest of the key. We do a partial - * read in this case to try to make the best out of a sorry situation. - */ - var key; - var ret = {}; - if (m[4]) { - try { - key = rfc4253.read(kbuf); + return needMoreData(state); +} - } catch (e) { - m = trimmed.match(SSHKEY_RE2); - assert.ok(m, 'key must match regex'); - kbuf = new Buffer(m[2], 'base64'); - key = rfc4253.readInternal(ret, 'public', kbuf); - } - } else { - key = rfc4253.readInternal(ret, 'public', kbuf); - } +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} - assert.strictEqual(type, key.type); +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = __webpack_require__(309).StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; - if (m[4] && m[4].length > 0) { - key.comment = m[4]; +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} - } else if (ret.consumed) { - /* - * Now the magic: trying to recover the key comment when it's - * gotten conjoined to the key or otherwise shenanigan'd. - * - * Work out how much base64 we used, then drop all non-base64 - * chars from the beginning up to this point in the the string. - * Then offset in this and try to make up for missing = chars. - */ - var data = m[2] + m[3]; - var realOffset = Math.ceil(ret.consumed / 3) * 4; - data = data.slice(0, realOffset - 2). /*JSSTYLED*/ - replace(/[^a-zA-Z0-9+\/=]/g, '') + - data.slice(realOffset - 2); +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} - var padding = ret.consumed % 3; - if (padding > 0 && - data.slice(realOffset - 1, realOffset) !== '=') - realOffset--; - while (data.slice(realOffset, realOffset + 1) === '=') - realOffset++; +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; - /* Finally, grab what we think is the comment & clean it up. */ - var trailer = data.slice(realOffset); - trailer = trailer.replace(/[\r\n]/g, ' '). - replace(/^\s+/, ''); - if (trailer.match(/^[a-zA-Z0-9]/)) - key.comment = trailer; - } + if (n !== 0) state.emittedReadable = false; - return (key); -} + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } -function write(key, options) { - assert.object(key); - if (!Key.isKey(key)) - throw (new Error('Must be a public key')); + n = howMuchToRead(n, state); - var parts = []; - var alg = rfc4253.keyTypeToAlg(key); - parts.push(alg); + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } - var buf = rfc4253.write(key); - parts.push(buf.toString('base64')); + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - if (key.comment) - parts.push(key.comment); + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - return (new Buffer(parts.join(' '))); -} + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } -/***/ }), -/* 267 */ -/***/ (function(module, exports, __webpack_require__) { + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; -// Copyright 2017 Joyent, Inc. + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } -module.exports = { - read: read, - verify: verify, - sign: sign, - signAsync: signAsync, - write: write -}; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; -var assert = __webpack_require__(9); -var asn1 = __webpack_require__(34); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var pem = __webpack_require__(41); -var Identity = __webpack_require__(75); -var Signature = __webpack_require__(33); -var Certificate = __webpack_require__(72); -var pkcs8 = __webpack_require__(74); + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } -/* - * This file is based on RFC5280 (X.509). - */ + if (ret !== null) this.emit('data', ret); -/* Helper to read in a single mpint */ -function readMPInt(der, nm) { - assert.strictEqual(der.peek(), asn1.Ber.Integer, - nm + ' is not an Integer'); - return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; } -function verify(cert, key) { - var sig = cert.signatures.x509; - assert.object(sig, 'x509 signature'); +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; - var algParts = sig.algo.split('-'); - if (algParts[0] !== key.type) - return (false); + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} - var blob = sig.cache; - if (blob === undefined) { - var der = new asn1.BerWriter(); - writeTBSCert(cert, der); - blob = der.buffer; - } +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} - var verifier = key.createVerify(algParts[1]); - verifier.write(blob); - return (verifier.verify(sig.signature)); +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); } -function Local(i) { - return (asn1.Ber.Context | asn1.Ber.Constructor | i); +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } } -function Context(i) { - return (asn1.Ber.Context | i); +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; } -var SIGN_ALGS = { - 'rsa-md5': '1.2.840.113549.1.1.4', - 'rsa-sha1': '1.2.840.113549.1.1.5', - 'rsa-sha256': '1.2.840.113549.1.1.11', - 'rsa-sha384': '1.2.840.113549.1.1.12', - 'rsa-sha512': '1.2.840.113549.1.1.13', - 'dsa-sha1': '1.2.840.10040.4.3', - 'dsa-sha256': '2.16.840.1.101.3.4.3.2', - 'ecdsa-sha1': '1.2.840.10045.4.1', - 'ecdsa-sha256': '1.2.840.10045.4.3.2', - 'ecdsa-sha384': '1.2.840.10045.4.3.3', - 'ecdsa-sha512': '1.2.840.10045.4.3.4' +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); }; -Object.keys(SIGN_ALGS).forEach(function (k) { - SIGN_ALGS[SIGN_ALGS[k]] = k; -}); -SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5'; -SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1'; -var EXTS = { - 'issuerKeyId': '2.5.29.35', - 'altName': '2.5.29.17', - 'basicConstraints': '2.5.29.19', - 'keyUsage': '2.5.29.15', - 'extKeyUsage': '2.5.29.37' -}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -function read(buf, options) { - if (typeof (buf) === 'string') { - buf = new Buffer(buf, 'binary'); - } - assert.buffer(buf, 'buf'); + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var der = new asn1.BerReader(buf); + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - der.readSequence(); - if (Math.abs(der.length - der.remain) > 1) { - throw (new Error('DER sequence does not contain whole byte ' + - 'stream')); - } + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); - var tbsStart = der.offset; - der.readSequence(); - var sigOffset = der.offset + der.length; - var tbsEnd = sigOffset; + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } - if (der.peek() === Local(0)) { - der.readSequence(Local(0)); - var version = der.readInt(); - assert.ok(version <= 3, - 'only x.509 versions up to v3 supported'); - } + function onend() { + debug('onend'); + dest.end(); + } - var cert = {}; - cert.signatures = {}; - var sig = (cert.signatures.x509 = {}); - sig.extras = {}; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); - cert.serial = readMPInt(der, 'serial'); + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); - der.readSequence(); - var after = der.offset + der.length; - var certAlgOid = der.readOID(); - var certAlg = SIGN_ALGS[certAlgOid]; - if (certAlg === undefined) - throw (new Error('unknown signature algorithm ' + certAlgOid)); + cleanedUp = true; - der._offset = after; - cert.issuer = Identity.parseAsn1(der); + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } - der.readSequence(); - cert.validFrom = readDate(der); - cert.validUntil = readDate(der); + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } - cert.subjects = [Identity.parseAsn1(der)]; + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } - der.readSequence(); - after = der.offset + der.length; - cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der); - der._offset = after; + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); - /* issuerUniqueID */ - if (der.peek() === Local(1)) { - der.readSequence(Local(1)); - sig.extras.issuerUniqueID = - buf.slice(der.offset, der.offset + der.length); - der._offset += der.length; - } + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - /* subjectUniqueID */ - if (der.peek() === Local(2)) { - der.readSequence(Local(2)); - sig.extras.subjectUniqueID = - buf.slice(der.offset, der.offset + der.length); - der._offset += der.length; - } + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } - /* extensions */ - if (der.peek() === Local(3)) { - der.readSequence(Local(3)); - var extEnd = der.offset + der.length; - der.readSequence(); + // tell the dest that it's being piped to + dest.emit('pipe', src); - while (der.offset < extEnd) - readExtension(cert, buf, der); + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } - assert.strictEqual(der.offset, extEnd); - } + return dest; +}; - assert.strictEqual(der.offset, sigOffset); +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} - der.readSequence(); - after = der.offset + der.length; - var sigAlgOid = der.readOID(); - var sigAlg = SIGN_ALGS[sigAlgOid]; - if (sigAlg === undefined) - throw (new Error('unknown signature algorithm ' + sigAlgOid)); - der._offset = after; +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; - var sigData = der.readString(asn1.Ber.BitString, true); - if (sigData[0] === 0) - sigData = sigData.slice(1); - var algParts = sigAlg.split('-'); + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; - sig.signature = Signature.parse(sigData, algParts[0], 'asn1'); - sig.signature.hashAlgorithm = algParts[1]; - sig.algo = sigAlg; - sig.cache = buf.slice(tbsStart, tbsEnd); + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - return (new Certificate(cert)); -} + if (!dest) dest = state.pipes; -function readDate(der) { - if (der.peek() === asn1.Ber.UTCTime) { - return (utcTimeToDate(der.readString(asn1.Ber.UTCTime))); - } else if (der.peek() === asn1.Ber.GeneralizedTime) { - return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime))); - } else { - throw (new Error('Unsupported date format')); - } + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); } -/* RFC5280, section 4.2.1.6 (GeneralName type) */ -var ALTNAME = { - OtherName: Local(0), - RFC822Name: Context(1), - DNSName: Context(2), - X400Address: Local(3), - DirectoryName: Local(4), - EDIPartyName: Local(5), - URI: Context(6), - IPAddress: Context(7), - OID: Context(8) +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; }; -/* RFC5280, section 4.2.1.12 (KeyPurposeId) */ -var EXTPURPOSE = { - 'serverAuth': '1.3.6.1.5.5.7.3.1', - 'clientAuth': '1.3.6.1.5.5.7.3.2', - 'codeSigning': '1.3.6.1.5.5.7.3.3', +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} - /* See https://github.com/joyent/oid-docs/blob/master/root.md */ - 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1', - 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2' +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; }; -var EXTPURPOSE_REV = {}; -Object.keys(EXTPURPOSE).forEach(function (k) { - EXTPURPOSE_REV[EXTPURPOSE[k]] = k; -}); -var KEYUSEBITS = [ - 'signature', 'identity', 'keyEncryption', - 'encryption', 'keyAgreement', 'ca', 'crl' -]; +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} -function readExtension(cert, buf, der) { - der.readSequence(); - var after = der.offset + der.length; - var extId = der.readOID(); - var id; - var sig = cert.signatures.x509; - sig.extras.exts = []; +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; - var critical; - if (der.peek() === asn1.Ber.Boolean) - critical = der.readBoolean(); + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } - switch (extId) { - case (EXTS.basicConstraints): - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - var bcEnd = der.offset + der.length; - var ca = false; - if (der.peek() === asn1.Ber.Boolean) - ca = der.readBoolean(); - if (cert.purposes === undefined) - cert.purposes = []; - if (ca === true) - cert.purposes.push('ca'); - var bc = { oid: extId, critical: critical }; - if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer) - bc.pathLen = der.readInt(); - sig.extras.exts.push(bc); - break; - case (EXTS.extKeyUsage): - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - if (cert.purposes === undefined) - cert.purposes = []; - var ekEnd = der.offset + der.length; - while (der.offset < ekEnd) { - var oid = der.readOID(); - cert.purposes.push(EXTPURPOSE_REV[oid] || oid); - } - /* - * This is a bit of a hack: in the case where we have a cert - * that's only allowed to do serverAuth or clientAuth (and not - * the other), we want to make sure all our Subjects are of - * the right type. But we already parsed our Subjects and - * decided if they were hosts or users earlier (since it appears - * first in the cert). - * - * So we go through and mutate them into the right kind here if - * it doesn't match. This might not be hugely beneficial, as it - * seems that single-purpose certs are not often seen in the - * wild. - */ - if (cert.purposes.indexOf('serverAuth') !== -1 && - cert.purposes.indexOf('clientAuth') === -1) { - cert.subjects.forEach(function (ide) { - if (ide.type !== 'host') { - ide.type = 'host'; - ide.hostname = ide.uid || - ide.email || - ide.components[0].value; - } - }); - } else if (cert.purposes.indexOf('clientAuth') !== -1 && - cert.purposes.indexOf('serverAuth') === -1) { - cert.subjects.forEach(function (ide) { - if (ide.type !== 'user') { - ide.type = 'user'; - ide.uid = ide.hostname || - ide.email || - ide.components[0].value; - } - }); - } - sig.extras.exts.push({ oid: extId, critical: critical }); - break; - case (EXTS.keyUsage): - der.readSequence(asn1.Ber.OctetString); - var bits = der.readString(asn1.Ber.BitString, true); - var setBits = readBitField(bits, KEYUSEBITS); - setBits.forEach(function (bit) { - if (cert.purposes === undefined) - cert.purposes = []; - if (cert.purposes.indexOf(bit) === -1) - cert.purposes.push(bit); - }); - sig.extras.exts.push({ oid: extId, critical: critical, - bits: bits }); - break; - case (EXTS.altName): - der.readSequence(asn1.Ber.OctetString); - der.readSequence(); - var aeEnd = der.offset + der.length; - while (der.offset < aeEnd) { - switch (der.peek()) { - case ALTNAME.OtherName: - case ALTNAME.EDIPartyName: - der.readSequence(); - der._offset += der.length; - break; - case ALTNAME.OID: - der.readOID(ALTNAME.OID); - break; - case ALTNAME.RFC822Name: - /* RFC822 specifies email addresses */ - var email = der.readString(ALTNAME.RFC822Name); - id = Identity.forEmail(email); - if (!cert.subjects[0].equals(id)) - cert.subjects.push(id); - break; - case ALTNAME.DirectoryName: - der.readSequence(ALTNAME.DirectoryName); - id = Identity.parseAsn1(der); - if (!cert.subjects[0].equals(id)) - cert.subjects.push(id); - break; - case ALTNAME.DNSName: - var host = der.readString( - ALTNAME.DNSName); - id = Identity.forHost(host); - if (!cert.subjects[0].equals(id)) - cert.subjects.push(id); - break; - default: - der.readString(der.peek()); - break; - } - } - sig.extras.exts.push({ oid: extId, critical: critical }); - break; - default: - sig.extras.exts.push({ - oid: extId, - critical: critical, - data: der.readString(asn1.Ber.OctetString, true) - }); - break; - } + self.push(null); + }); - der._offset = after; -} + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); -var UTCTIME_RE = - /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; -function utcTimeToDate(t) { - var m = t.match(UTCTIME_RE); - assert.ok(m, 'timestamps must be in UTC'); - var d = new Date(); + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var thisYear = d.getUTCFullYear(); - var century = Math.floor(thisYear / 100) * 100; + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); - var year = parseInt(m[1], 10); - if (thisYear % 100 < 50 && year >= 60) - year += (century - 1); - else - year += century; - d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10)); - d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); - if (m[6] && m[6].length > 0) - d.setUTCSeconds(parseInt(m[6], 10)); - return (d); -} + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } -var GTIME_RE = - /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; -function gTimeToDate(t) { - var m = t.match(GTIME_RE); - assert.ok(m); - var d = new Date(); + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + } - d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1, - parseInt(m[3], 10)); - d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); - if (m[6] && m[6].length > 0) - d.setUTCSeconds(parseInt(m[6], 10)); - return (d); -} + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; -function zeroPad(n) { - var s = '' + n; - while (s.length < 2) - s = '0' + s; - return (s); + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; } -function dateToUTCTime(d) { - var s = ''; - s += zeroPad(d.getUTCFullYear() % 100); - s += zeroPad(d.getUTCMonth() + 1); - s += zeroPad(d.getUTCDate()); - s += zeroPad(d.getUTCHours()); - s += zeroPad(d.getUTCMinutes()); - s += zeroPad(d.getUTCSeconds()); - s += 'Z'; - return (s); +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; } -function sign(cert, key) { - if (cert.signatures.x509 === undefined) - cert.signatures.x509 = {}; - var sig = cert.signatures.x509; +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - sig.algo = key.type + '-' + key.defaultHashAlgorithm(); - if (SIGN_ALGS[sig.algo] === undefined) - return (false); +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = bufferShim.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - var der = new asn1.BerWriter(); - writeTBSCert(cert, der); - var blob = der.buffer; - sig.cache = blob; +function endReadable(stream) { + var state = stream._readableState; - var signer = key.createSign(); - signer.write(blob); - cert.signatures.x509.signature = signer.sign(); + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - return (true); + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } } -function signAsync(cert, signer, done) { - if (cert.signatures.x509 === undefined) - cert.signatures.x509 = {}; - var sig = cert.signatures.x509; +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} - var der = new asn1.BerWriter(); - writeTBSCert(cert, der); - var blob = der.buffer; - sig.cache = blob; +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} - signer(blob, function (err, signature) { - if (err) { - done(err); - return; - } - sig.algo = signature.type + '-' + signature.hashAlgorithm; - if (SIGN_ALGS[sig.algo] === undefined) { - done(new Error('Invalid signing algorithm "' + - sig.algo + '"')); - return; - } - sig.signature = signature; - done(); - }); +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; } -function write(cert, options) { - var sig = cert.signatures.x509; - assert.object(sig, 'x509 signature'); +/***/ }), +/* 306 */ +/***/ (function(module, exports, __webpack_require__) { - var der = new asn1.BerWriter(); - der.startSequence(); - if (sig.cache) { - der._ensure(sig.cache.length); - sig.cache.copy(der._buf, der._offset); - der._offset += sig.cache.length; - } else { - writeTBSCert(cert, der); - } +"use strict"; +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - der.startSequence(); - der.writeOID(SIGN_ALGS[sig.algo]); - if (sig.algo.match(/^rsa-/)) - der.writeNull(); - der.endSequence(); - var sigData = sig.signature.toBuffer('asn1'); - var data = new Buffer(sigData.length + 1); - data[0] = 0; - sigData.copy(data, 1); - der.writeBuffer(data, asn1.Ber.BitString); - der.endSequence(); - return (der.buffer); -} +module.exports = Transform; -function writeTBSCert(cert, der) { - var sig = cert.signatures.x509; - assert.object(sig, 'x509 signature'); +var Duplex = __webpack_require__(86); - der.startSequence(); +/*<replacement>*/ +var util = __webpack_require__(110); +util.inherits = __webpack_require__(39); +/*</replacement>*/ - der.startSequence(Local(0)); - der.writeInt(2); - der.endSequence(); +util.inherits(Transform, Duplex); - der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer); +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; - der.startSequence(); - der.writeOID(SIGN_ALGS[sig.algo]); - der.endSequence(); + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} - cert.issuer.toAsn1(der); +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; - der.startSequence(); - der.writeString(dateToUTCTime(cert.validFrom), asn1.Ber.UTCTime); - der.writeString(dateToUTCTime(cert.validUntil), asn1.Ber.UTCTime); - der.endSequence(); + var cb = ts.writecb; - var subject = cert.subjects[0]; - var altNames = cert.subjects.slice(1); - subject.toAsn1(der); + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - pkcs8.writePkcs8(der, cert.subjectKey); + ts.writechunk = null; + ts.writecb = null; - if (sig.extras && sig.extras.issuerUniqueID) { - der.writeBuffer(sig.extras.issuerUniqueID, Local(1)); - } + if (data !== null && data !== undefined) stream.push(data); - if (sig.extras && sig.extras.subjectUniqueID) { - der.writeBuffer(sig.extras.subjectUniqueID, Local(2)); - } + cb(er); - if (altNames.length > 0 || subject.type === 'host' || - (cert.purposes !== undefined && cert.purposes.length > 0) || - (sig.extras && sig.extras.exts)) { - der.startSequence(Local(3)); - der.startSequence(); + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} - var exts = []; - if (cert.purposes !== undefined && cert.purposes.length > 0) { - exts.push({ - oid: EXTS.basicConstraints, - critical: true - }); - exts.push({ - oid: EXTS.keyUsage, - critical: true - }); - exts.push({ - oid: EXTS.extKeyUsage, - critical: true - }); - } - exts.push({ oid: EXTS.altName }); - if (sig.extras && sig.extras.exts) - exts = sig.extras.exts; +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - for (var i = 0; i < exts.length; ++i) { - der.startSequence(); - der.writeOID(exts[i].oid); + Duplex.call(this, options); - if (exts[i].critical !== undefined) - der.writeBoolean(exts[i].critical); + this._transformState = new TransformState(this); - if (exts[i].oid === EXTS.altName) { - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - if (subject.type === 'host') { - der.writeString(subject.hostname, - Context(2)); - } - for (var j = 0; j < altNames.length; ++j) { - if (altNames[j].type === 'host') { - der.writeString( - altNames[j].hostname, - ALTNAME.DNSName); - } else if (altNames[j].type === - 'email') { - der.writeString( - altNames[j].email, - ALTNAME.RFC822Name); - } else { - /* - * Encode anything else as a - * DN style name for now. - */ - der.startSequence( - ALTNAME.DirectoryName); - altNames[j].toAsn1(der); - der.endSequence(); - } - } - der.endSequence(); - der.endSequence(); - } else if (exts[i].oid === EXTS.basicConstraints) { - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - var ca = (cert.purposes.indexOf('ca') !== -1); - var pathLen = exts[i].pathLen; - der.writeBoolean(ca); - if (pathLen !== undefined) - der.writeInt(pathLen); - der.endSequence(); - der.endSequence(); - } else if (exts[i].oid === EXTS.extKeyUsage) { - der.startSequence(asn1.Ber.OctetString); - der.startSequence(); - cert.purposes.forEach(function (purpose) { - if (purpose === 'ca') - return; - if (KEYUSEBITS.indexOf(purpose) !== -1) - return; - var oid = purpose; - if (EXTPURPOSE[purpose] !== undefined) - oid = EXTPURPOSE[purpose]; - der.writeOID(oid); - }); - der.endSequence(); - der.endSequence(); - } else if (exts[i].oid === EXTS.keyUsage) { - der.startSequence(asn1.Ber.OctetString); - /* - * If we parsed this certificate from a byte - * stream (i.e. we didn't generate it in sshpk) - * then we'll have a ".bits" property on the - * ext with the original raw byte contents. - * - * If we have this, use it here instead of - * regenerating it. This guarantees we output - * the same data we parsed, so signatures still - * validate. - */ - if (exts[i].bits !== undefined) { - der.writeBuffer(exts[i].bits, - asn1.Ber.BitString); - } else { - var bits = writeBitField(cert.purposes, - KEYUSEBITS); - der.writeBuffer(bits, - asn1.Ber.BitString); - } - der.endSequence(); - } else { - der.writeBuffer(exts[i].data, - asn1.Ber.OctetString); - } + var stream = this; - der.endSequence(); - } + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - der.endSequence(); - der.endSequence(); - } + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; - der.endSequence(); -} + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; -/* - * Reads an ASN.1 BER bitfield out of the Buffer produced by doing - * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw - * contents of the BitString tag, which is a count of unused bits followed by - * the bits as a right-padded byte string. - * - * `bits` is the Buffer, `bitIndex` should contain an array of string names - * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec. - * - * Returns an array of Strings, the names of the bits that were set to 1. - */ -function readBitField(bits, bitIndex) { - var bitLen = 8 * (bits.length - 1) - bits[0]; - var setBits = {}; - for (var i = 0; i < bitLen; ++i) { - var byteN = 1 + Math.floor(i / 8); - var bit = 7 - (i % 8); - var mask = 1 << bit; - var bitVal = ((bits[byteN] & mask) !== 0); - var name = bitIndex[i]; - if (bitVal && typeof (name) === 'string') { - setBits[name] = true; - } - } - return (Object.keys(setBits)); -} + if (typeof options.flush === 'function') this._flush = options.flush; + } -/* - * `setBits` is an array of strings, containing the names for each bit that - * sould be set to 1. `bitIndex` is same as in `readBitField()`. - * - * Returns a Buffer, ready to be written out with `BerWriter#writeString()`. - */ -function writeBitField(setBits, bitIndex) { - var bitLen = bitIndex.length; - var blen = Math.ceil(bitLen / 8); - var unused = blen * 8 - bitLen; - var bits = new Buffer(1 + blen); - bits.fill(0); - bits[0] = unused; - for (var i = 0; i < bitLen; ++i) { - var byteN = 1 + Math.floor(i / 8); - var bit = 7 - (i % 8); - var mask = 1 << bit; - var name = bitIndex[i]; - if (name === undefined) - continue; - var bitVal = (setBits.indexOf(name) !== -1); - if (bitVal) { - bits[byteN] |= mask; - } - } - return (bits); + // When the writable side finishes, then flush out anything remaining. + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er, data) { + done(stream, er, data); + });else done(stream); + }); } +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; -/***/ }), -/* 268 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; -module.exports = x => { - if (typeof x !== 'string') { - throw new TypeError('Expected a string, got ' + typeof x); - } +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; - // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string - // conversion translates it to FEFF (UTF-16 BOM) - if (x.charCodeAt(0) === 0xFEFF) { - return x.slice(1); - } +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - return x; + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } }; +function done(stream, er, data) { + if (er) return stream.emit('error', er); -/***/ }), -/* 269 */ -/***/ (function(module, exports) { + if (data !== null && data !== undefined) stream.push(data); -var ZEROS = '0000000000000000000' -var SEVENS = '7777777777777777777' -var ZERO_OFFSET = '0'.charCodeAt(0) -var USTAR = 'ustar\x0000' -var MASK = parseInt('7777', 8) + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; -var clamp = function (index, len, defaultValue) { - if (typeof index !== 'number') return defaultValue - index = ~~index // Coerce to integer. - if (index >= len) return len - if (index >= 0) return index - index += len - if (index >= 0) return index - return 0 -} + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); -var toType = function (flag) { - switch (flag) { - case 0: - return 'file' - case 1: - return 'link' - case 2: - return 'symlink' - case 3: - return 'character-device' - case 4: - return 'block-device' - case 5: - return 'directory' - case 6: - return 'fifo' - case 7: - return 'contiguous-file' - case 72: - return 'pax-header' - case 55: - return 'pax-global-header' - case 27: - return 'gnu-long-link-path' - case 28: - case 30: - return 'gnu-long-path' - } + if (ts.transforming) throw new Error('Calling transform done when still transforming'); - return null + return stream.push(null); } -var toTypeflag = function (flag) { - switch (flag) { - case 'file': - return 0 - case 'link': - return 1 - case 'symlink': - return 2 - case 'character-device': - return 3 - case 'block-device': - return 4 - case 'directory': - return 5 - case 'fifo': - return 6 - case 'contiguous-file': - return 7 - case 'pax-header': - return 72 - } +/***/ }), +/* 307 */ +/***/ (function(module, exports, __webpack_require__) { - return 0 -} +"use strict"; +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. -var alloc = function (size) { - var buf = new Buffer(size) - buf.fill(0) - return buf -} -var indexOf = function (block, num, offset, end) { - for (; offset < end; offset++) { - if (block[offset] === num) return offset - } - return end -} -var cksum = function (block) { - var sum = 8 * 32 - for (var i = 0; i < 148; i++) sum += block[i] - for (var j = 156; j < 512; j++) sum += block[j] - return sum -} +module.exports = Writable; -var encodeOct = function (val, n) { - val = val.toString(8) - if (val.length > n) return SEVENS.slice(0, n) + ' ' - else return ZEROS.slice(0, n - val.length) + val + ' ' -} +/*<replacement>*/ +var processNextTick = __webpack_require__(222); +/*</replacement>*/ -/* Copied from the node-tar repo and modified to meet - * tar-stream coding standard. - * - * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 - */ -function parse256 (buf) { - // first byte MUST be either 80 or FF - // 80 for positive, FF for 2's comp - var positive - if (buf[0] === 0x80) positive = true - else if (buf[0] === 0xFF) positive = false - else return null +/*<replacement>*/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/*</replacement>*/ - // build up a base-256 tuple from the least sig to the highest - var zero = false - var tuple = [] - for (var i = buf.length - 1; i > 0; i--) { - var byte = buf[i] - if (positive) tuple.push(byte) - else if (zero && byte === 0) tuple.push(0) - else if (zero) { - zero = false - tuple.push(0x100 - byte) - } else tuple.push(0xFF - byte) - } +/*<replacement>*/ +var Duplex; +/*</replacement>*/ - var sum = 0 - var l = tuple.length - for (i = 0; i < l; i++) { - sum += tuple[i] * Math.pow(256, i) - } +Writable.WritableState = WritableState; - return positive ? sum : -1 * sum -} +/*<replacement>*/ +var util = __webpack_require__(110); +util.inherits = __webpack_require__(39); +/*</replacement>*/ -var decodeOct = function (val, offset, length) { - val = val.slice(offset, offset + length) - offset = 0 +/*<replacement>*/ +var internalUtil = { + deprecate: __webpack_require__(647) +}; +/*</replacement>*/ - // If prefixed with 0x80 then parse as a base-256 integer - if (val[offset] & 0x80) { - return parse256(val) - } else { - // Older versions of tar can prefix with spaces - while (offset < val.length && val[offset] === 32) offset++ - var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) - while (offset < end && val[offset] === 0) offset++ - if (end === offset) return 0 - return parseInt(val.slice(offset, end).toString(), 8) - } -} +/*<replacement>*/ +var Stream = __webpack_require__(308); +/*</replacement>*/ -var decodeStr = function (val, offset, length) { - return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString() -} +var Buffer = __webpack_require__(120).Buffer; +/*<replacement>*/ +var bufferShim = __webpack_require__(174); +/*</replacement>*/ -var addLength = function (str) { - var len = Buffer.byteLength(str) - var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 - if (len + digits > Math.pow(10, digits)) digits++ +util.inherits(Writable, Stream); - return (len + digits) + str -} +function nop() {} -exports.decodeLongPath = function (buf) { - return decodeStr(buf, 0, buf.length) +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; } -exports.encodePax = function (opts) { // TODO: encode more stuff in pax - var result = '' - if (opts.name) result += addLength(' path=' + opts.name + '\n') - if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') - var pax = opts.pax - if (pax) { - for (var key in pax) { - result += addLength(' ' + key + '=' + pax[key] + '\n') - } - } - return new Buffer(result) -} +function WritableState(options, stream) { + Duplex = Duplex || __webpack_require__(86); -exports.decodePax = function (buf) { - var result = {} + options = options || {}; - while (buf.length) { - var i = 0 - while (i < buf.length && buf[i] !== 32) i++ - var len = parseInt(buf.slice(0, i).toString(), 10) - if (!len) return result + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - var b = buf.slice(i + 1, len - 1).toString() - var keyIndex = b.indexOf('=') - if (keyIndex === -1) return result - result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - buf = buf.slice(len) - } + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; - return result -} + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; -exports.encode = function (opts) { - var buf = alloc(512) - var name = opts.name - var prefix = '' + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' - if (Buffer.byteLength(name) !== name.length) return null // utf-8 + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - while (Buffer.byteLength(name) > 100) { - var i = name.indexOf('/') - if (i === -1) return null - prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) - name = name.slice(i + 1) - } + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null - if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; - buf.write(name) - buf.write(encodeOct(opts.mode & MASK, 6), 100) - buf.write(encodeOct(opts.uid, 6), 108) - buf.write(encodeOct(opts.gid, 6), 116) - buf.write(encodeOct(opts.size, 11), 124) - buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) + // a flag to see when we're in the middle of a write. + this.writing = false; - buf[156] = ZERO_OFFSET + toTypeflag(opts.type) + // when true all writes will be buffered until .uncork() call + this.corked = 0; - if (opts.linkname) buf.write(opts.linkname, 157) - - buf.write(USTAR, 257) - if (opts.uname) buf.write(opts.uname, 265) - if (opts.gname) buf.write(opts.gname, 297) - buf.write(encodeOct(opts.devmajor || 0, 6), 329) - buf.write(encodeOct(opts.devminor || 0, 6), 337) + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; - if (prefix) buf.write(prefix, 345) + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; - buf.write(encodeOct(cksum(buf), 6), 148) + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; - return buf -} + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; -exports.decode = function (buf) { - var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET + // the amount that is being written when _write is called. + this.writelen = 0; - var name = decodeStr(buf, 0, 100) - var mode = decodeOct(buf, 100, 8) - var uid = decodeOct(buf, 108, 8) - var gid = decodeOct(buf, 116, 8) - var size = decodeOct(buf, 124, 12) - var mtime = decodeOct(buf, 136, 12) - var type = toType(typeflag) - var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100) - var uname = decodeStr(buf, 265, 32) - var gname = decodeStr(buf, 297, 32) - var devmajor = decodeOct(buf, 329, 8) - var devminor = decodeOct(buf, 337, 8) + this.bufferedRequest = null; + this.lastBufferedRequest = null; - if (buf[345]) name = decodeStr(buf, 345, 155) + '/' + name + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; - // to support old tar versions that use trailing / to indicate dirs - if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; - var c = cksum(buf) + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; - // checksum is still initial value if header was null. - if (c === 8 * 32) return null + // count buffered requests + this.bufferedRequestCount = 0; - // valid checksum - if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} - return { - name: name, - mode: mode, - uid: uid, - gid: gid, - size: size, - mtime: new Date(1000 * mtime), - type: type, - linkname: linkname, - uname: uname, - gname: gname, - devmajor: devmajor, - devminor: devminor +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; } +function Writable(options) { + Duplex = Duplex || __webpack_require__(86); -/***/ }), -/* 270 */ -/***/ (function(module, exports, __webpack_require__) { + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. -exports.extract = __webpack_require__(623) -exports.pack = __webpack_require__(624) + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + this._writableState = new WritableState(options, this); -/***/ }), -/* 271 */ -/***/ (function(module, exports, __webpack_require__) { + // legacy. + this.writable = true; -var Transform = __webpack_require__(582) - , inherits = __webpack_require__(2).inherits - , xtend = __webpack_require__(278) + if (options) { + if (typeof options.write === 'function') this._write = options.write; -function DestroyableTransform(opts) { - Transform.call(this, opts) - this._destroyed = false + if (typeof options.writev === 'function') this._writev = options.writev; + } + + Stream.call(this); } -inherits(DestroyableTransform, Transform) +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; -DestroyableTransform.prototype.destroy = function(err) { - if (this._destroyed) return - this._destroyed = true - - var self = this - process.nextTick(function() { - if (err) - self.emit('error', err) - self.emit('close') - }) +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); } -// a noop _transform function -function noop (chunk, enc, callback) { - callback(null, chunk) +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; } +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = Buffer.isBuffer(chunk); -// create a new export function, used by both the main export and -// the .ctor export, contains common logic for dealing with arguments -function through2 (construct) { - return function (options, transform, flush) { - if (typeof options == 'function') { - flush = transform - transform = options - options = {} - } + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } - if (typeof transform != 'function') - transform = noop + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof flush != 'function') - flush = null + if (typeof cb !== 'function') cb = nop; - return construct(options, transform, flush) + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } -} - -// main export, just make me a transform stream! -module.exports = through2(function (options, transform, flush) { - var t2 = new DestroyableTransform(options) + return ret; +}; - t2._transform = transform +Writable.prototype.cork = function () { + var state = this._writableState; - if (flush) - t2._flush = flush + state.corked++; +}; - return t2 -}) +Writable.prototype.uncork = function () { + var state = this._writableState; + if (state.corked) { + state.corked--; -// make me a reusable prototype that I can `new`, or implicitly `new` -// with a constructor call -module.exports.ctor = through2(function (options, transform, flush) { - function Through2 (override) { - if (!(this instanceof Through2)) - return new Through2(override) + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; - this.options = xtend(options, override) +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; - DestroyableTransform.call(this, this.options) +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = bufferShim.from(chunk, encoding); } + return chunk; +} - inherits(Through2, DestroyableTransform) - - Through2.prototype._transform = transform +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + } + var len = state.objectMode ? 1 : chunk.length; - if (flush) - Through2.prototype._flush = flush + state.length += len; - return Through2 -}) + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } -module.exports.obj = through2(function (options, transform, flush) { - var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options)) + return ret; +} - t2._transform = transform +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} - if (flush) - t2._flush = flush +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); - return t2 -}) + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -/***/ }), -/* 272 */ -/***/ (function(module, exports, __webpack_require__) { +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ + onwriteStateUpdate(state); -/* - * "A request-path path-matches a given cookie-path if at least one of the - * following conditions holds:" - */ -function pathMatch (reqPath, cookiePath) { - // "o The cookie-path and the request-path are identical." - if (cookiePath === reqPath) { - return true; - } + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - var idx = reqPath.indexOf(cookiePath); - if (idx === 0) { - // "o The cookie-path is a prefix of the request-path, and the last - // character of the cookie-path is %x2F ("/")." - if (cookiePath.substr(-1) === "/") { - return true; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - // " o The cookie-path is a prefix of the request-path, and the first - // character of the request-path that is not included in the cookie- path - // is a %x2F ("/") character." - if (reqPath.substr(cookiePath.length, 1) === "/") { - return true; + if (sync) { + /*<replacement>*/ + asyncWrite(afterWrite, stream, state, finished, cb); + /*</replacement>*/ + } else { + afterWrite(stream, state, finished, cb); } } +} - return false; +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); } -exports.pathMatch = pathMatch; +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; -/***/ }), -/* 273 */ -/***/ (function(module, exports, __webpack_require__) { + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; -"use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } -var pubsuffix = __webpack_require__(274); + doWrite(stream, state, true, state.length, buffer, '', holder.finish); -// Gives the permutation of all possible domainMatch()es of a given domain. The -// array is in shortest-to-longest order. Handy for indexing. -function permuteDomain (domain) { - var pubSuf = pubsuffix.getPublicSuffix(domain); - if (!pubSuf) { - return null; - } - if (pubSuf == domain) { - return [domain]; - } + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; - var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" - var parts = prefix.split('.').reverse(); - var cur = pubSuf; - var permutations = [cur]; - while (parts.length) { - cur = parts.shift() + '.' + cur; - permutations.push(cur); + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; } - return permutations; -} -exports.permuteDomain = permuteDomain; + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; -/***/ }), -/* 274 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/**************************************************** - * AUTOMATICALLY GENERATED by generate-pubsuffix.js * - * DO NOT EDIT! * - ****************************************************/ +Writable.prototype._writev = null; +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -var punycode = __webpack_require__(281); + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); -module.exports.getPublicSuffix = function getPublicSuffix(domain) { - /*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - if (!domain) { - return null; - } - if (domain.match(/^\./)) { - return null; - } - var asciiDomain = punycode.toASCII(domain); - var converted = false; - if (asciiDomain !== domain) { - domain = asciiDomain; - converted = true; - } - if (index[domain]) { - return null; + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } - domain = domain.toLowerCase(); - var parts = domain.split('.').reverse(); - - var suffix = ''; - var suffixLen = 0; - for (var i=0; i<parts.length; i++) { - var part = parts[i]; - var starstr = '*'+suffix; - var partstr = part+suffix; + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; - if (index[starstr]) { // star rule matches - suffixLen = i+1; - if (index[partstr] === false) { // exception rule matches (NB: false, not undefined) - suffixLen--; - } - } else if (index[partstr]) { // exact match, not exception - suffixLen = i+1; - } +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} - suffix = '.'+partstr; +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); } +} - if (index['*'+suffix]) { // *.domain exists (e.g. *.kyoto.jp for domain='kyoto.jp'); - return null; +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } } + return need; +} - suffixLen = suffixLen || 1; - if (parts.length > suffixLen) { - var publicSuffix = parts.slice(0,suffixLen+1).reverse().join('.'); - return converted ? punycode.toUnicode(publicSuffix) : publicSuffix; +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); } + state.ended = true; + stream.writable = false; +} - return null; -}; +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; -// The following generated structure is used under the MPL version 2.0 -// See public-suffix.txt for more information + this.next = null; + this.entry = null; + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} -var index = module.exports.index = Object.freeze( -{"ac":true,"com.ac":true,"edu.ac":true,"gov.ac":true,"net.ac":true,"mil.ac":true,"org.ac":true,"ad":true,"nom.ad":true,"ae":true,"co.ae":true,"net.ae":true,"org.ae":true,"sch.ae":true,"ac.ae":true,"gov.ae":true,"mil.ae":true,"aero":true,"accident-investigation.aero":true,"accident-prevention.aero":true,"aerobatic.aero":true,"aeroclub.aero":true,"aerodrome.aero":true,"agents.aero":true,"aircraft.aero":true,"airline.aero":true,"airport.aero":true,"air-surveillance.aero":true,"airtraffic.aero":true,"air-traffic-control.aero":true,"ambulance.aero":true,"amusement.aero":true,"association.aero":true,"author.aero":true,"ballooning.aero":true,"broker.aero":true,"caa.aero":true,"cargo.aero":true,"catering.aero":true,"certification.aero":true,"championship.aero":true,"charter.aero":true,"civilaviation.aero":true,"club.aero":true,"conference.aero":true,"consultant.aero":true,"consulting.aero":true,"control.aero":true,"council.aero":true,"crew.aero":true,"design.aero":true,"dgca.aero":true,"educator.aero":true,"emergency.aero":true,"engine.aero":true,"engineer.aero":true,"entertainment.aero":true,"equipment.aero":true,"exchange.aero":true,"express.aero":true,"federation.aero":true,"flight.aero":true,"freight.aero":true,"fuel.aero":true,"gliding.aero":true,"government.aero":true,"groundhandling.aero":true,"group.aero":true,"hanggliding.aero":true,"homebuilt.aero":true,"insurance.aero":true,"journal.aero":true,"journalist.aero":true,"leasing.aero":true,"logistics.aero":true,"magazine.aero":true,"maintenance.aero":true,"marketplace.aero":true,"media.aero":true,"microlight.aero":true,"modelling.aero":true,"navigation.aero":true,"parachuting.aero":true,"paragliding.aero":true,"passenger-association.aero":true,"pilot.aero":true,"press.aero":true,"production.aero":true,"recreation.aero":true,"repbody.aero":true,"res.aero":true,"research.aero":true,"rotorcraft.aero":true,"safety.aero":true,"scientist.aero":true,"services.aero":true,"show.aero":true,"skydiving.aero":true,"software.aero":true,"student.aero":true,"taxi.aero":true,"trader.aero":true,"trading.aero":true,"trainer.aero":true,"union.aero":true,"workinggroup.aero":true,"works.aero":true,"af":true,"gov.af":true,"com.af":true,"org.af":true,"net.af":true,"edu.af":true,"ag":true,"com.ag":true,"org.ag":true,"net.ag":true,"co.ag":true,"nom.ag":true,"ai":true,"off.ai":true,"com.ai":true,"net.ai":true,"org.ai":true,"al":true,"com.al":true,"edu.al":true,"gov.al":true,"mil.al":true,"net.al":true,"org.al":true,"am":true,"an":true,"com.an":true,"net.an":true,"org.an":true,"edu.an":true,"ao":true,"ed.ao":true,"gv.ao":true,"og.ao":true,"co.ao":true,"pb.ao":true,"it.ao":true,"aq":true,"ar":true,"com.ar":true,"edu.ar":true,"gob.ar":true,"gov.ar":true,"int.ar":true,"mil.ar":true,"net.ar":true,"org.ar":true,"tur.ar":true,"arpa":true,"e164.arpa":true,"in-addr.arpa":true,"ip6.arpa":true,"iris.arpa":true,"uri.arpa":true,"urn.arpa":true,"as":true,"gov.as":true,"asia":true,"at":true,"ac.at":true,"co.at":true,"gv.at":true,"or.at":true,"au":true,"com.au":true,"net.au":true,"org.au":true,"edu.au":true,"gov.au":true,"asn.au":true,"id.au":true,"info.au":true,"conf.au":true,"oz.au":true,"act.au":true,"nsw.au":true,"nt.au":true,"qld.au":true,"sa.au":true,"tas.au":true,"vic.au":true,"wa.au":true,"act.edu.au":true,"nsw.edu.au":true,"nt.edu.au":true,"qld.edu.au":true,"sa.edu.au":true,"tas.edu.au":true,"vic.edu.au":true,"wa.edu.au":true,"qld.gov.au":true,"sa.gov.au":true,"tas.gov.au":true,"vic.gov.au":true,"wa.gov.au":true,"aw":true,"com.aw":true,"ax":true,"az":true,"com.az":true,"net.az":true,"int.az":true,"gov.az":true,"org.az":true,"edu.az":true,"info.az":true,"pp.az":true,"mil.az":true,"name.az":true,"pro.az":true,"biz.az":true,"ba":true,"org.ba":true,"net.ba":true,"edu.ba":true,"gov.ba":true,"mil.ba":true,"unsa.ba":true,"unbi.ba":true,"co.ba":true,"com.ba":true,"rs.ba":true,"bb":true,"biz.bb":true,"co.bb":true,"com.bb":true,"edu.bb":true,"gov.bb":true,"info.bb":true,"net.bb":true,"org.bb":true,"store.bb":true,"tv.bb":true,"*.bd":true,"be":true,"ac.be":true,"bf":true,"gov.bf":true,"bg":true,"a.bg":true,"b.bg":true,"c.bg":true,"d.bg":true,"e.bg":true,"f.bg":true,"g.bg":true,"h.bg":true,"i.bg":true,"j.bg":true,"k.bg":true,"l.bg":true,"m.bg":true,"n.bg":true,"o.bg":true,"p.bg":true,"q.bg":true,"r.bg":true,"s.bg":true,"t.bg":true,"u.bg":true,"v.bg":true,"w.bg":true,"x.bg":true,"y.bg":true,"z.bg":true,"0.bg":true,"1.bg":true,"2.bg":true,"3.bg":true,"4.bg":true,"5.bg":true,"6.bg":true,"7.bg":true,"8.bg":true,"9.bg":true,"bh":true,"com.bh":true,"edu.bh":true,"net.bh":true,"org.bh":true,"gov.bh":true,"bi":true,"co.bi":true,"com.bi":true,"edu.bi":true,"or.bi":true,"org.bi":true,"biz":true,"bj":true,"asso.bj":true,"barreau.bj":true,"gouv.bj":true,"bm":true,"com.bm":true,"edu.bm":true,"gov.bm":true,"net.bm":true,"org.bm":true,"*.bn":true,"bo":true,"com.bo":true,"edu.bo":true,"gov.bo":true,"gob.bo":true,"int.bo":true,"org.bo":true,"net.bo":true,"mil.bo":true,"tv.bo":true,"br":true,"adm.br":true,"adv.br":true,"agr.br":true,"am.br":true,"arq.br":true,"art.br":true,"ato.br":true,"b.br":true,"bio.br":true,"blog.br":true,"bmd.br":true,"cim.br":true,"cng.br":true,"cnt.br":true,"com.br":true,"coop.br":true,"ecn.br":true,"eco.br":true,"edu.br":true,"emp.br":true,"eng.br":true,"esp.br":true,"etc.br":true,"eti.br":true,"far.br":true,"flog.br":true,"fm.br":true,"fnd.br":true,"fot.br":true,"fst.br":true,"g12.br":true,"ggf.br":true,"gov.br":true,"imb.br":true,"ind.br":true,"inf.br":true,"jor.br":true,"jus.br":true,"leg.br":true,"lel.br":true,"mat.br":true,"med.br":true,"mil.br":true,"mp.br":true,"mus.br":true,"net.br":true,"*.nom.br":true,"not.br":true,"ntr.br":true,"odo.br":true,"org.br":true,"ppg.br":true,"pro.br":true,"psc.br":true,"psi.br":true,"qsl.br":true,"radio.br":true,"rec.br":true,"slg.br":true,"srv.br":true,"taxi.br":true,"teo.br":true,"tmp.br":true,"trd.br":true,"tur.br":true,"tv.br":true,"vet.br":true,"vlog.br":true,"wiki.br":true,"zlg.br":true,"bs":true,"com.bs":true,"net.bs":true,"org.bs":true,"edu.bs":true,"gov.bs":true,"bt":true,"com.bt":true,"edu.bt":true,"gov.bt":true,"net.bt":true,"org.bt":true,"bv":true,"bw":true,"co.bw":true,"org.bw":true,"by":true,"gov.by":true,"mil.by":true,"com.by":true,"of.by":true,"bz":true,"com.bz":true,"net.bz":true,"org.bz":true,"edu.bz":true,"gov.bz":true,"ca":true,"ab.ca":true,"bc.ca":true,"mb.ca":true,"nb.ca":true,"nf.ca":true,"nl.ca":true,"ns.ca":true,"nt.ca":true,"nu.ca":true,"on.ca":true,"pe.ca":true,"qc.ca":true,"sk.ca":true,"yk.ca":true,"gc.ca":true,"cat":true,"cc":true,"cd":true,"gov.cd":true,"cf":true,"cg":true,"ch":true,"ci":true,"org.ci":true,"or.ci":true,"com.ci":true,"co.ci":true,"edu.ci":true,"ed.ci":true,"ac.ci":true,"net.ci":true,"go.ci":true,"asso.ci":true,"xn--aroport-bya.ci":true,"int.ci":true,"presse.ci":true,"md.ci":true,"gouv.ci":true,"*.ck":true,"www.ck":false,"cl":true,"gov.cl":true,"gob.cl":true,"co.cl":true,"mil.cl":true,"cm":true,"co.cm":true,"com.cm":true,"gov.cm":true,"net.cm":true,"cn":true,"ac.cn":true,"com.cn":true,"edu.cn":true,"gov.cn":true,"net.cn":true,"org.cn":true,"mil.cn":true,"xn--55qx5d.cn":true,"xn--io0a7i.cn":true,"xn--od0alg.cn":true,"ah.cn":true,"bj.cn":true,"cq.cn":true,"fj.cn":true,"gd.cn":true,"gs.cn":true,"gz.cn":true,"gx.cn":true,"ha.cn":true,"hb.cn":true,"he.cn":true,"hi.cn":true,"hl.cn":true,"hn.cn":true,"jl.cn":true,"js.cn":true,"jx.cn":true,"ln.cn":true,"nm.cn":true,"nx.cn":true,"qh.cn":true,"sc.cn":true,"sd.cn":true,"sh.cn":true,"sn.cn":true,"sx.cn":true,"tj.cn":true,"xj.cn":true,"xz.cn":true,"yn.cn":true,"zj.cn":true,"hk.cn":true,"mo.cn":true,"tw.cn":true,"co":true,"arts.co":true,"com.co":true,"edu.co":true,"firm.co":true,"gov.co":true,"info.co":true,"int.co":true,"mil.co":true,"net.co":true,"nom.co":true,"org.co":true,"rec.co":true,"web.co":true,"com":true,"coop":true,"cr":true,"ac.cr":true,"co.cr":true,"ed.cr":true,"fi.cr":true,"go.cr":true,"or.cr":true,"sa.cr":true,"cu":true,"com.cu":true,"edu.cu":true,"org.cu":true,"net.cu":true,"gov.cu":true,"inf.cu":true,"cv":true,"cw":true,"com.cw":true,"edu.cw":true,"net.cw":true,"org.cw":true,"cx":true,"gov.cx":true,"ac.cy":true,"biz.cy":true,"com.cy":true,"ekloges.cy":true,"gov.cy":true,"ltd.cy":true,"name.cy":true,"net.cy":true,"org.cy":true,"parliament.cy":true,"press.cy":true,"pro.cy":true,"tm.cy":true,"cz":true,"de":true,"dj":true,"dk":true,"dm":true,"com.dm":true,"net.dm":true,"org.dm":true,"edu.dm":true,"gov.dm":true,"do":true,"art.do":true,"com.do":true,"edu.do":true,"gob.do":true,"gov.do":true,"mil.do":true,"net.do":true,"org.do":true,"sld.do":true,"web.do":true,"dz":true,"com.dz":true,"org.dz":true,"net.dz":true,"gov.dz":true,"edu.dz":true,"asso.dz":true,"pol.dz":true,"art.dz":true,"ec":true,"com.ec":true,"info.ec":true,"net.ec":true,"fin.ec":true,"k12.ec":true,"med.ec":true,"pro.ec":true,"org.ec":true,"edu.ec":true,"gov.ec":true,"gob.ec":true,"mil.ec":true,"edu":true,"ee":true,"edu.ee":true,"gov.ee":true,"riik.ee":true,"lib.ee":true,"med.ee":true,"com.ee":true,"pri.ee":true,"aip.ee":true,"org.ee":true,"fie.ee":true,"eg":true,"com.eg":true,"edu.eg":true,"eun.eg":true,"gov.eg":true,"mil.eg":true,"name.eg":true,"net.eg":true,"org.eg":true,"sci.eg":true,"*.er":true,"es":true,"com.es":true,"nom.es":true,"org.es":true,"gob.es":true,"edu.es":true,"et":true,"com.et":true,"gov.et":true,"org.et":true,"edu.et":true,"biz.et":true,"name.et":true,"info.et":true,"net.et":true,"eu":true,"fi":true,"aland.fi":true,"*.fj":true,"*.fk":true,"fm":true,"fo":true,"fr":true,"com.fr":true,"asso.fr":true,"nom.fr":true,"prd.fr":true,"presse.fr":true,"tm.fr":true,"aeroport.fr":true,"assedic.fr":true,"avocat.fr":true,"avoues.fr":true,"cci.fr":true,"chambagri.fr":true,"chirurgiens-dentistes.fr":true,"experts-comptables.fr":true,"geometre-expert.fr":true,"gouv.fr":true,"greta.fr":true,"huissier-justice.fr":true,"medecin.fr":true,"notaires.fr":true,"pharmacien.fr":true,"port.fr":true,"veterinaire.fr":true,"ga":true,"gb":true,"gd":true,"ge":true,"com.ge":true,"edu.ge":true,"gov.ge":true,"org.ge":true,"mil.ge":true,"net.ge":true,"pvt.ge":true,"gf":true,"gg":true,"co.gg":true,"net.gg":true,"org.gg":true,"gh":true,"com.gh":true,"edu.gh":true,"gov.gh":true,"org.gh":true,"mil.gh":true,"gi":true,"com.gi":true,"ltd.gi":true,"gov.gi":true,"mod.gi":true,"edu.gi":true,"org.gi":true,"gl":true,"co.gl":true,"com.gl":true,"edu.gl":true,"net.gl":true,"org.gl":true,"gm":true,"gn":true,"ac.gn":true,"com.gn":true,"edu.gn":true,"gov.gn":true,"org.gn":true,"net.gn":true,"gov":true,"gp":true,"com.gp":true,"net.gp":true,"mobi.gp":true,"edu.gp":true,"org.gp":true,"asso.gp":true,"gq":true,"gr":true,"com.gr":true,"edu.gr":true,"net.gr":true,"org.gr":true,"gov.gr":true,"gs":true,"gt":true,"com.gt":true,"edu.gt":true,"gob.gt":true,"ind.gt":true,"mil.gt":true,"net.gt":true,"org.gt":true,"*.gu":true,"gw":true,"gy":true,"co.gy":true,"com.gy":true,"net.gy":true,"hk":true,"com.hk":true,"edu.hk":true,"gov.hk":true,"idv.hk":true,"net.hk":true,"org.hk":true,"xn--55qx5d.hk":true,"xn--wcvs22d.hk":true,"xn--lcvr32d.hk":true,"xn--mxtq1m.hk":true,"xn--gmqw5a.hk":true,"xn--ciqpn.hk":true,"xn--gmq050i.hk":true,"xn--zf0avx.hk":true,"xn--io0a7i.hk":true,"xn--mk0axi.hk":true,"xn--od0alg.hk":true,"xn--od0aq3b.hk":true,"xn--tn0ag.hk":true,"xn--uc0atv.hk":true,"xn--uc0ay4a.hk":true,"hm":true,"hn":true,"com.hn":true,"edu.hn":true,"org.hn":true,"net.hn":true,"mil.hn":true,"gob.hn":true,"hr":true,"iz.hr":true,"from.hr":true,"name.hr":true,"com.hr":true,"ht":true,"com.ht":true,"shop.ht":true,"firm.ht":true,"info.ht":true,"adult.ht":true,"net.ht":true,"pro.ht":true,"org.ht":true,"med.ht":true,"art.ht":true,"coop.ht":true,"pol.ht":true,"asso.ht":true,"edu.ht":true,"rel.ht":true,"gouv.ht":true,"perso.ht":true,"hu":true,"co.hu":true,"info.hu":true,"org.hu":true,"priv.hu":true,"sport.hu":true,"tm.hu":true,"2000.hu":true,"agrar.hu":true,"bolt.hu":true,"casino.hu":true,"city.hu":true,"erotica.hu":true,"erotika.hu":true,"film.hu":true,"forum.hu":true,"games.hu":true,"hotel.hu":true,"ingatlan.hu":true,"jogasz.hu":true,"konyvelo.hu":true,"lakas.hu":true,"media.hu":true,"news.hu":true,"reklam.hu":true,"sex.hu":true,"shop.hu":true,"suli.hu":true,"szex.hu":true,"tozsde.hu":true,"utazas.hu":true,"video.hu":true,"id":true,"ac.id":true,"biz.id":true,"co.id":true,"desa.id":true,"go.id":true,"mil.id":true,"my.id":true,"net.id":true,"or.id":true,"sch.id":true,"web.id":true,"ie":true,"gov.ie":true,"il":true,"ac.il":true,"co.il":true,"gov.il":true,"idf.il":true,"k12.il":true,"muni.il":true,"net.il":true,"org.il":true,"im":true,"ac.im":true,"co.im":true,"com.im":true,"ltd.co.im":true,"net.im":true,"org.im":true,"plc.co.im":true,"tt.im":true,"tv.im":true,"in":true,"co.in":true,"firm.in":true,"net.in":true,"org.in":true,"gen.in":true,"ind.in":true,"nic.in":true,"ac.in":true,"edu.in":true,"res.in":true,"gov.in":true,"mil.in":true,"info":true,"int":true,"eu.int":true,"io":true,"com.io":true,"iq":true,"gov.iq":true,"edu.iq":true,"mil.iq":true,"com.iq":true,"org.iq":true,"net.iq":true,"ir":true,"ac.ir":true,"co.ir":true,"gov.ir":true,"id.ir":true,"net.ir":true,"org.ir":true,"sch.ir":true,"xn--mgba3a4f16a.ir":true,"xn--mgba3a4fra.ir":true,"is":true,"net.is":true,"com.is":true,"edu.is":true,"gov.is":true,"org.is":true,"int.is":true,"it":true,"gov.it":true,"edu.it":true,"abr.it":true,"abruzzo.it":true,"aosta-valley.it":true,"aostavalley.it":true,"bas.it":true,"basilicata.it":true,"cal.it":true,"calabria.it":true,"cam.it":true,"campania.it":true,"emilia-romagna.it":true,"emiliaromagna.it":true,"emr.it":true,"friuli-v-giulia.it":true,"friuli-ve-giulia.it":true,"friuli-vegiulia.it":true,"friuli-venezia-giulia.it":true,"friuli-veneziagiulia.it":true,"friuli-vgiulia.it":true,"friuliv-giulia.it":true,"friulive-giulia.it":true,"friulivegiulia.it":true,"friulivenezia-giulia.it":true,"friuliveneziagiulia.it":true,"friulivgiulia.it":true,"fvg.it":true,"laz.it":true,"lazio.it":true,"lig.it":true,"liguria.it":true,"lom.it":true,"lombardia.it":true,"lombardy.it":true,"lucania.it":true,"mar.it":true,"marche.it":true,"mol.it":true,"molise.it":true,"piedmont.it":true,"piemonte.it":true,"pmn.it":true,"pug.it":true,"puglia.it":true,"sar.it":true,"sardegna.it":true,"sardinia.it":true,"sic.it":true,"sicilia.it":true,"sicily.it":true,"taa.it":true,"tos.it":true,"toscana.it":true,"trentino-a-adige.it":true,"trentino-aadige.it":true,"trentino-alto-adige.it":true,"trentino-altoadige.it":true,"trentino-s-tirol.it":true,"trentino-stirol.it":true,"trentino-sud-tirol.it":true,"trentino-sudtirol.it":true,"trentino-sued-tirol.it":true,"trentino-suedtirol.it":true,"trentinoa-adige.it":true,"trentinoaadige.it":true,"trentinoalto-adige.it":true,"trentinoaltoadige.it":true,"trentinos-tirol.it":true,"trentinostirol.it":true,"trentinosud-tirol.it":true,"trentinosudtirol.it":true,"trentinosued-tirol.it":true,"trentinosuedtirol.it":true,"tuscany.it":true,"umb.it":true,"umbria.it":true,"val-d-aosta.it":true,"val-daosta.it":true,"vald-aosta.it":true,"valdaosta.it":true,"valle-aosta.it":true,"valle-d-aosta.it":true,"valle-daosta.it":true,"valleaosta.it":true,"valled-aosta.it":true,"valledaosta.it":true,"vallee-aoste.it":true,"valleeaoste.it":true,"vao.it":true,"vda.it":true,"ven.it":true,"veneto.it":true,"ag.it":true,"agrigento.it":true,"al.it":true,"alessandria.it":true,"alto-adige.it":true,"altoadige.it":true,"an.it":true,"ancona.it":true,"andria-barletta-trani.it":true,"andria-trani-barletta.it":true,"andriabarlettatrani.it":true,"andriatranibarletta.it":true,"ao.it":true,"aosta.it":true,"aoste.it":true,"ap.it":true,"aq.it":true,"aquila.it":true,"ar.it":true,"arezzo.it":true,"ascoli-piceno.it":true,"ascolipiceno.it":true,"asti.it":true,"at.it":true,"av.it":true,"avellino.it":true,"ba.it":true,"balsan.it":true,"bari.it":true,"barletta-trani-andria.it":true,"barlettatraniandria.it":true,"belluno.it":true,"benevento.it":true,"bergamo.it":true,"bg.it":true,"bi.it":true,"biella.it":true,"bl.it":true,"bn.it":true,"bo.it":true,"bologna.it":true,"bolzano.it":true,"bozen.it":true,"br.it":true,"brescia.it":true,"brindisi.it":true,"bs.it":true,"bt.it":true,"bz.it":true,"ca.it":true,"cagliari.it":true,"caltanissetta.it":true,"campidano-medio.it":true,"campidanomedio.it":true,"campobasso.it":true,"carbonia-iglesias.it":true,"carboniaiglesias.it":true,"carrara-massa.it":true,"carraramassa.it":true,"caserta.it":true,"catania.it":true,"catanzaro.it":true,"cb.it":true,"ce.it":true,"cesena-forli.it":true,"cesenaforli.it":true,"ch.it":true,"chieti.it":true,"ci.it":true,"cl.it":true,"cn.it":true,"co.it":true,"como.it":true,"cosenza.it":true,"cr.it":true,"cremona.it":true,"crotone.it":true,"cs.it":true,"ct.it":true,"cuneo.it":true,"cz.it":true,"dell-ogliastra.it":true,"dellogliastra.it":true,"en.it":true,"enna.it":true,"fc.it":true,"fe.it":true,"fermo.it":true,"ferrara.it":true,"fg.it":true,"fi.it":true,"firenze.it":true,"florence.it":true,"fm.it":true,"foggia.it":true,"forli-cesena.it":true,"forlicesena.it":true,"fr.it":true,"frosinone.it":true,"ge.it":true,"genoa.it":true,"genova.it":true,"go.it":true,"gorizia.it":true,"gr.it":true,"grosseto.it":true,"iglesias-carbonia.it":true,"iglesiascarbonia.it":true,"im.it":true,"imperia.it":true,"is.it":true,"isernia.it":true,"kr.it":true,"la-spezia.it":true,"laquila.it":true,"laspezia.it":true,"latina.it":true,"lc.it":true,"le.it":true,"lecce.it":true,"lecco.it":true,"li.it":true,"livorno.it":true,"lo.it":true,"lodi.it":true,"lt.it":true,"lu.it":true,"lucca.it":true,"macerata.it":true,"mantova.it":true,"massa-carrara.it":true,"massacarrara.it":true,"matera.it":true,"mb.it":true,"mc.it":true,"me.it":true,"medio-campidano.it":true,"mediocampidano.it":true,"messina.it":true,"mi.it":true,"milan.it":true,"milano.it":true,"mn.it":true,"mo.it":true,"modena.it":true,"monza-brianza.it":true,"monza-e-della-brianza.it":true,"monza.it":true,"monzabrianza.it":true,"monzaebrianza.it":true,"monzaedellabrianza.it":true,"ms.it":true,"mt.it":true,"na.it":true,"naples.it":true,"napoli.it":true,"no.it":true,"novara.it":true,"nu.it":true,"nuoro.it":true,"og.it":true,"ogliastra.it":true,"olbia-tempio.it":true,"olbiatempio.it":true,"or.it":true,"oristano.it":true,"ot.it":true,"pa.it":true,"padova.it":true,"padua.it":true,"palermo.it":true,"parma.it":true,"pavia.it":true,"pc.it":true,"pd.it":true,"pe.it":true,"perugia.it":true,"pesaro-urbino.it":true,"pesarourbino.it":true,"pescara.it":true,"pg.it":true,"pi.it":true,"piacenza.it":true,"pisa.it":true,"pistoia.it":true,"pn.it":true,"po.it":true,"pordenone.it":true,"potenza.it":true,"pr.it":true,"prato.it":true,"pt.it":true,"pu.it":true,"pv.it":true,"pz.it":true,"ra.it":true,"ragusa.it":true,"ravenna.it":true,"rc.it":true,"re.it":true,"reggio-calabria.it":true,"reggio-emilia.it":true,"reggiocalabria.it":true,"reggioemilia.it":true,"rg.it":true,"ri.it":true,"rieti.it":true,"rimini.it":true,"rm.it":true,"rn.it":true,"ro.it":true,"roma.it":true,"rome.it":true,"rovigo.it":true,"sa.it":true,"salerno.it":true,"sassari.it":true,"savona.it":true,"si.it":true,"siena.it":true,"siracusa.it":true,"so.it":true,"sondrio.it":true,"sp.it":true,"sr.it":true,"ss.it":true,"suedtirol.it":true,"sv.it":true,"ta.it":true,"taranto.it":true,"te.it":true,"tempio-olbia.it":true,"tempioolbia.it":true,"teramo.it":true,"terni.it":true,"tn.it":true,"to.it":true,"torino.it":true,"tp.it":true,"tr.it":true,"trani-andria-barletta.it":true,"trani-barletta-andria.it":true,"traniandriabarletta.it":true,"tranibarlettaandria.it":true,"trapani.it":true,"trentino.it":true,"trento.it":true,"treviso.it":true,"trieste.it":true,"ts.it":true,"turin.it":true,"tv.it":true,"ud.it":true,"udine.it":true,"urbino-pesaro.it":true,"urbinopesaro.it":true,"va.it":true,"varese.it":true,"vb.it":true,"vc.it":true,"ve.it":true,"venezia.it":true,"venice.it":true,"verbania.it":true,"vercelli.it":true,"verona.it":true,"vi.it":true,"vibo-valentia.it":true,"vibovalentia.it":true,"vicenza.it":true,"viterbo.it":true,"vr.it":true,"vs.it":true,"vt.it":true,"vv.it":true,"je":true,"co.je":true,"net.je":true,"org.je":true,"*.jm":true,"jo":true,"com.jo":true,"org.jo":true,"net.jo":true,"edu.jo":true,"sch.jo":true,"gov.jo":true,"mil.jo":true,"name.jo":true,"jobs":true,"jp":true,"ac.jp":true,"ad.jp":true,"co.jp":true,"ed.jp":true,"go.jp":true,"gr.jp":true,"lg.jp":true,"ne.jp":true,"or.jp":true,"aichi.jp":true,"akita.jp":true,"aomori.jp":true,"chiba.jp":true,"ehime.jp":true,"fukui.jp":true,"fukuoka.jp":true,"fukushima.jp":true,"gifu.jp":true,"gunma.jp":true,"hiroshima.jp":true,"hokkaido.jp":true,"hyogo.jp":true,"ibaraki.jp":true,"ishikawa.jp":true,"iwate.jp":true,"kagawa.jp":true,"kagoshima.jp":true,"kanagawa.jp":true,"kochi.jp":true,"kumamoto.jp":true,"kyoto.jp":true,"mie.jp":true,"miyagi.jp":true,"miyazaki.jp":true,"nagano.jp":true,"nagasaki.jp":true,"nara.jp":true,"niigata.jp":true,"oita.jp":true,"okayama.jp":true,"okinawa.jp":true,"osaka.jp":true,"saga.jp":true,"saitama.jp":true,"shiga.jp":true,"shimane.jp":true,"shizuoka.jp":true,"tochigi.jp":true,"tokushima.jp":true,"tokyo.jp":true,"tottori.jp":true,"toyama.jp":true,"wakayama.jp":true,"yamagata.jp":true,"yamaguchi.jp":true,"yamanashi.jp":true,"xn--4pvxs.jp":true,"xn--vgu402c.jp":true,"xn--c3s14m.jp":true,"xn--f6qx53a.jp":true,"xn--8pvr4u.jp":true,"xn--uist22h.jp":true,"xn--djrs72d6uy.jp":true,"xn--mkru45i.jp":true,"xn--0trq7p7nn.jp":true,"xn--8ltr62k.jp":true,"xn--2m4a15e.jp":true,"xn--efvn9s.jp":true,"xn--32vp30h.jp":true,"xn--4it797k.jp":true,"xn--1lqs71d.jp":true,"xn--5rtp49c.jp":true,"xn--5js045d.jp":true,"xn--ehqz56n.jp":true,"xn--1lqs03n.jp":true,"xn--qqqt11m.jp":true,"xn--kbrq7o.jp":true,"xn--pssu33l.jp":true,"xn--ntsq17g.jp":true,"xn--uisz3g.jp":true,"xn--6btw5a.jp":true,"xn--1ctwo.jp":true,"xn--6orx2r.jp":true,"xn--rht61e.jp":true,"xn--rht27z.jp":true,"xn--djty4k.jp":true,"xn--nit225k.jp":true,"xn--rht3d.jp":true,"xn--klty5x.jp":true,"xn--kltx9a.jp":true,"xn--kltp7d.jp":true,"xn--uuwu58a.jp":true,"xn--zbx025d.jp":true,"xn--ntso0iqx3a.jp":true,"xn--elqq16h.jp":true,"xn--4it168d.jp":true,"xn--klt787d.jp":true,"xn--rny31h.jp":true,"xn--7t0a264c.jp":true,"xn--5rtq34k.jp":true,"xn--k7yn95e.jp":true,"xn--tor131o.jp":true,"xn--d5qv7z876c.jp":true,"*.kawasaki.jp":true,"*.kitakyushu.jp":true,"*.kobe.jp":true,"*.nagoya.jp":true,"*.sapporo.jp":true,"*.sendai.jp":true,"*.yokohama.jp":true,"city.kawasaki.jp":false,"city.kitakyushu.jp":false,"city.kobe.jp":false,"city.nagoya.jp":false,"city.sapporo.jp":false,"city.sendai.jp":false,"city.yokohama.jp":false,"aisai.aichi.jp":true,"ama.aichi.jp":true,"anjo.aichi.jp":true,"asuke.aichi.jp":true,"chiryu.aichi.jp":true,"chita.aichi.jp":true,"fuso.aichi.jp":true,"gamagori.aichi.jp":true,"handa.aichi.jp":true,"hazu.aichi.jp":true,"hekinan.aichi.jp":true,"higashiura.aichi.jp":true,"ichinomiya.aichi.jp":true,"inazawa.aichi.jp":true,"inuyama.aichi.jp":true,"isshiki.aichi.jp":true,"iwakura.aichi.jp":true,"kanie.aichi.jp":true,"kariya.aichi.jp":true,"kasugai.aichi.jp":true,"kira.aichi.jp":true,"kiyosu.aichi.jp":true,"komaki.aichi.jp":true,"konan.aichi.jp":true,"kota.aichi.jp":true,"mihama.aichi.jp":true,"miyoshi.aichi.jp":true,"nishio.aichi.jp":true,"nisshin.aichi.jp":true,"obu.aichi.jp":true,"oguchi.aichi.jp":true,"oharu.aichi.jp":true,"okazaki.aichi.jp":true,"owariasahi.aichi.jp":true,"seto.aichi.jp":true,"shikatsu.aichi.jp":true,"shinshiro.aichi.jp":true,"shitara.aichi.jp":true,"tahara.aichi.jp":true,"takahama.aichi.jp":true,"tobishima.aichi.jp":true,"toei.aichi.jp":true,"togo.aichi.jp":true,"tokai.aichi.jp":true,"tokoname.aichi.jp":true,"toyoake.aichi.jp":true,"toyohashi.aichi.jp":true,"toyokawa.aichi.jp":true,"toyone.aichi.jp":true,"toyota.aichi.jp":true,"tsushima.aichi.jp":true,"yatomi.aichi.jp":true,"akita.akita.jp":true,"daisen.akita.jp":true,"fujisato.akita.jp":true,"gojome.akita.jp":true,"hachirogata.akita.jp":true,"happou.akita.jp":true,"higashinaruse.akita.jp":true,"honjo.akita.jp":true,"honjyo.akita.jp":true,"ikawa.akita.jp":true,"kamikoani.akita.jp":true,"kamioka.akita.jp":true,"katagami.akita.jp":true,"kazuno.akita.jp":true,"kitaakita.akita.jp":true,"kosaka.akita.jp":true,"kyowa.akita.jp":true,"misato.akita.jp":true,"mitane.akita.jp":true,"moriyoshi.akita.jp":true,"nikaho.akita.jp":true,"noshiro.akita.jp":true,"odate.akita.jp":true,"oga.akita.jp":true,"ogata.akita.jp":true,"semboku.akita.jp":true,"yokote.akita.jp":true,"yurihonjo.akita.jp":true,"aomori.aomori.jp":true,"gonohe.aomori.jp":true,"hachinohe.aomori.jp":true,"hashikami.aomori.jp":true,"hiranai.aomori.jp":true,"hirosaki.aomori.jp":true,"itayanagi.aomori.jp":true,"kuroishi.aomori.jp":true,"misawa.aomori.jp":true,"mutsu.aomori.jp":true,"nakadomari.aomori.jp":true,"noheji.aomori.jp":true,"oirase.aomori.jp":true,"owani.aomori.jp":true,"rokunohe.aomori.jp":true,"sannohe.aomori.jp":true,"shichinohe.aomori.jp":true,"shingo.aomori.jp":true,"takko.aomori.jp":true,"towada.aomori.jp":true,"tsugaru.aomori.jp":true,"tsuruta.aomori.jp":true,"abiko.chiba.jp":true,"asahi.chiba.jp":true,"chonan.chiba.jp":true,"chosei.chiba.jp":true,"choshi.chiba.jp":true,"chuo.chiba.jp":true,"funabashi.chiba.jp":true,"futtsu.chiba.jp":true,"hanamigawa.chiba.jp":true,"ichihara.chiba.jp":true,"ichikawa.chiba.jp":true,"ichinomiya.chiba.jp":true,"inzai.chiba.jp":true,"isumi.chiba.jp":true,"kamagaya.chiba.jp":true,"kamogawa.chiba.jp":true,"kashiwa.chiba.jp":true,"katori.chiba.jp":true,"katsuura.chiba.jp":true,"kimitsu.chiba.jp":true,"kisarazu.chiba.jp":true,"kozaki.chiba.jp":true,"kujukuri.chiba.jp":true,"kyonan.chiba.jp":true,"matsudo.chiba.jp":true,"midori.chiba.jp":true,"mihama.chiba.jp":true,"minamiboso.chiba.jp":true,"mobara.chiba.jp":true,"mutsuzawa.chiba.jp":true,"nagara.chiba.jp":true,"nagareyama.chiba.jp":true,"narashino.chiba.jp":true,"narita.chiba.jp":true,"noda.chiba.jp":true,"oamishirasato.chiba.jp":true,"omigawa.chiba.jp":true,"onjuku.chiba.jp":true,"otaki.chiba.jp":true,"sakae.chiba.jp":true,"sakura.chiba.jp":true,"shimofusa.chiba.jp":true,"shirako.chiba.jp":true,"shiroi.chiba.jp":true,"shisui.chiba.jp":true,"sodegaura.chiba.jp":true,"sosa.chiba.jp":true,"tako.chiba.jp":true,"tateyama.chiba.jp":true,"togane.chiba.jp":true,"tohnosho.chiba.jp":true,"tomisato.chiba.jp":true,"urayasu.chiba.jp":true,"yachimata.chiba.jp":true,"yachiyo.chiba.jp":true,"yokaichiba.chiba.jp":true,"yokoshibahikari.chiba.jp":true,"yotsukaido.chiba.jp":true,"ainan.ehime.jp":true,"honai.ehime.jp":true,"ikata.ehime.jp":true,"imabari.ehime.jp":true,"iyo.ehime.jp":true,"kamijima.ehime.jp":true,"kihoku.ehime.jp":true,"kumakogen.ehime.jp":true,"masaki.ehime.jp":true,"matsuno.ehime.jp":true,"matsuyama.ehime.jp":true,"namikata.ehime.jp":true,"niihama.ehime.jp":true,"ozu.ehime.jp":true,"saijo.ehime.jp":true,"seiyo.ehime.jp":true,"shikokuchuo.ehime.jp":true,"tobe.ehime.jp":true,"toon.ehime.jp":true,"uchiko.ehime.jp":true,"uwajima.ehime.jp":true,"yawatahama.ehime.jp":true,"echizen.fukui.jp":true,"eiheiji.fukui.jp":true,"fukui.fukui.jp":true,"ikeda.fukui.jp":true,"katsuyama.fukui.jp":true,"mihama.fukui.jp":true,"minamiechizen.fukui.jp":true,"obama.fukui.jp":true,"ohi.fukui.jp":true,"ono.fukui.jp":true,"sabae.fukui.jp":true,"sakai.fukui.jp":true,"takahama.fukui.jp":true,"tsuruga.fukui.jp":true,"wakasa.fukui.jp":true,"ashiya.fukuoka.jp":true,"buzen.fukuoka.jp":true,"chikugo.fukuoka.jp":true,"chikuho.fukuoka.jp":true,"chikujo.fukuoka.jp":true,"chikushino.fukuoka.jp":true,"chikuzen.fukuoka.jp":true,"chuo.fukuoka.jp":true,"dazaifu.fukuoka.jp":true,"fukuchi.fukuoka.jp":true,"hakata.fukuoka.jp":true,"higashi.fukuoka.jp":true,"hirokawa.fukuoka.jp":true,"hisayama.fukuoka.jp":true,"iizuka.fukuoka.jp":true,"inatsuki.fukuoka.jp":true,"kaho.fukuoka.jp":true,"kasuga.fukuoka.jp":true,"kasuya.fukuoka.jp":true,"kawara.fukuoka.jp":true,"keisen.fukuoka.jp":true,"koga.fukuoka.jp":true,"kurate.fukuoka.jp":true,"kurogi.fukuoka.jp":true,"kurume.fukuoka.jp":true,"minami.fukuoka.jp":true,"miyako.fukuoka.jp":true,"miyama.fukuoka.jp":true,"miyawaka.fukuoka.jp":true,"mizumaki.fukuoka.jp":true,"munakata.fukuoka.jp":true,"nakagawa.fukuoka.jp":true,"nakama.fukuoka.jp":true,"nishi.fukuoka.jp":true,"nogata.fukuoka.jp":true,"ogori.fukuoka.jp":true,"okagaki.fukuoka.jp":true,"okawa.fukuoka.jp":true,"oki.fukuoka.jp":true,"omuta.fukuoka.jp":true,"onga.fukuoka.jp":true,"onojo.fukuoka.jp":true,"oto.fukuoka.jp":true,"saigawa.fukuoka.jp":true,"sasaguri.fukuoka.jp":true,"shingu.fukuoka.jp":true,"shinyoshitomi.fukuoka.jp":true,"shonai.fukuoka.jp":true,"soeda.fukuoka.jp":true,"sue.fukuoka.jp":true,"tachiarai.fukuoka.jp":true,"tagawa.fukuoka.jp":true,"takata.fukuoka.jp":true,"toho.fukuoka.jp":true,"toyotsu.fukuoka.jp":true,"tsuiki.fukuoka.jp":true,"ukiha.fukuoka.jp":true,"umi.fukuoka.jp":true,"usui.fukuoka.jp":true,"yamada.fukuoka.jp":true,"yame.fukuoka.jp":true,"yanagawa.fukuoka.jp":true,"yukuhashi.fukuoka.jp":true,"aizubange.fukushima.jp":true,"aizumisato.fukushima.jp":true,"aizuwakamatsu.fukushima.jp":true,"asakawa.fukushima.jp":true,"bandai.fukushima.jp":true,"date.fukushima.jp":true,"fukushima.fukushima.jp":true,"furudono.fukushima.jp":true,"futaba.fukushima.jp":true,"hanawa.fukushima.jp":true,"higashi.fukushima.jp":true,"hirata.fukushima.jp":true,"hirono.fukushima.jp":true,"iitate.fukushima.jp":true,"inawashiro.fukushima.jp":true,"ishikawa.fukushima.jp":true,"iwaki.fukushima.jp":true,"izumizaki.fukushima.jp":true,"kagamiishi.fukushima.jp":true,"kaneyama.fukushima.jp":true,"kawamata.fukushima.jp":true,"kitakata.fukushima.jp":true,"kitashiobara.fukushima.jp":true,"koori.fukushima.jp":true,"koriyama.fukushima.jp":true,"kunimi.fukushima.jp":true,"miharu.fukushima.jp":true,"mishima.fukushima.jp":true,"namie.fukushima.jp":true,"nango.fukushima.jp":true,"nishiaizu.fukushima.jp":true,"nishigo.fukushima.jp":true,"okuma.fukushima.jp":true,"omotego.fukushima.jp":true,"ono.fukushima.jp":true,"otama.fukushima.jp":true,"samegawa.fukushima.jp":true,"shimogo.fukushima.jp":true,"shirakawa.fukushima.jp":true,"showa.fukushima.jp":true,"soma.fukushima.jp":true,"sukagawa.fukushima.jp":true,"taishin.fukushima.jp":true,"tamakawa.fukushima.jp":true,"tanagura.fukushima.jp":true,"tenei.fukushima.jp":true,"yabuki.fukushima.jp":true,"yamato.fukushima.jp":true,"yamatsuri.fukushima.jp":true,"yanaizu.fukushima.jp":true,"yugawa.fukushima.jp":true,"anpachi.gifu.jp":true,"ena.gifu.jp":true,"gifu.gifu.jp":true,"ginan.gifu.jp":true,"godo.gifu.jp":true,"gujo.gifu.jp":true,"hashima.gifu.jp":true,"hichiso.gifu.jp":true,"hida.gifu.jp":true,"higashishirakawa.gifu.jp":true,"ibigawa.gifu.jp":true,"ikeda.gifu.jp":true,"kakamigahara.gifu.jp":true,"kani.gifu.jp":true,"kasahara.gifu.jp":true,"kasamatsu.gifu.jp":true,"kawaue.gifu.jp":true,"kitagata.gifu.jp":true,"mino.gifu.jp":true,"minokamo.gifu.jp":true,"mitake.gifu.jp":true,"mizunami.gifu.jp":true,"motosu.gifu.jp":true,"nakatsugawa.gifu.jp":true,"ogaki.gifu.jp":true,"sakahogi.gifu.jp":true,"seki.gifu.jp":true,"sekigahara.gifu.jp":true,"shirakawa.gifu.jp":true,"tajimi.gifu.jp":true,"takayama.gifu.jp":true,"tarui.gifu.jp":true,"toki.gifu.jp":true,"tomika.gifu.jp":true,"wanouchi.gifu.jp":true,"yamagata.gifu.jp":true,"yaotsu.gifu.jp":true,"yoro.gifu.jp":true,"annaka.gunma.jp":true,"chiyoda.gunma.jp":true,"fujioka.gunma.jp":true,"higashiagatsuma.gunma.jp":true,"isesaki.gunma.jp":true,"itakura.gunma.jp":true,"kanna.gunma.jp":true,"kanra.gunma.jp":true,"katashina.gunma.jp":true,"kawaba.gunma.jp":true,"kiryu.gunma.jp":true,"kusatsu.gunma.jp":true,"maebashi.gunma.jp":true,"meiwa.gunma.jp":true,"midori.gunma.jp":true,"minakami.gunma.jp":true,"naganohara.gunma.jp":true,"nakanojo.gunma.jp":true,"nanmoku.gunma.jp":true,"numata.gunma.jp":true,"oizumi.gunma.jp":true,"ora.gunma.jp":true,"ota.gunma.jp":true,"shibukawa.gunma.jp":true,"shimonita.gunma.jp":true,"shinto.gunma.jp":true,"showa.gunma.jp":true,"takasaki.gunma.jp":true,"takayama.gunma.jp":true,"tamamura.gunma.jp":true,"tatebayashi.gunma.jp":true,"tomioka.gunma.jp":true,"tsukiyono.gunma.jp":true,"tsumagoi.gunma.jp":true,"ueno.gunma.jp":true,"yoshioka.gunma.jp":true,"asaminami.hiroshima.jp":true,"daiwa.hiroshima.jp":true,"etajima.hiroshima.jp":true,"fuchu.hiroshima.jp":true,"fukuyama.hiroshima.jp":true,"hatsukaichi.hiroshima.jp":true,"higashihiroshima.hiroshima.jp":true,"hongo.hiroshima.jp":true,"jinsekikogen.hiroshima.jp":true,"kaita.hiroshima.jp":true,"kui.hiroshima.jp":true,"kumano.hiroshima.jp":true,"kure.hiroshima.jp":true,"mihara.hiroshima.jp":true,"miyoshi.hiroshima.jp":true,"naka.hiroshima.jp":true,"onomichi.hiroshima.jp":true,"osakikamijima.hiroshima.jp":true,"otake.hiroshima.jp":true,"saka.hiroshima.jp":true,"sera.hiroshima.jp":true,"seranishi.hiroshima.jp":true,"shinichi.hiroshima.jp":true,"shobara.hiroshima.jp":true,"takehara.hiroshima.jp":true,"abashiri.hokkaido.jp":true,"abira.hokkaido.jp":true,"aibetsu.hokkaido.jp":true,"akabira.hokkaido.jp":true,"akkeshi.hokkaido.jp":true,"asahikawa.hokkaido.jp":true,"ashibetsu.hokkaido.jp":true,"ashoro.hokkaido.jp":true,"assabu.hokkaido.jp":true,"atsuma.hokkaido.jp":true,"bibai.hokkaido.jp":true,"biei.hokkaido.jp":true,"bifuka.hokkaido.jp":true,"bihoro.hokkaido.jp":true,"biratori.hokkaido.jp":true,"chippubetsu.hokkaido.jp":true,"chitose.hokkaido.jp":true,"date.hokkaido.jp":true,"ebetsu.hokkaido.jp":true,"embetsu.hokkaido.jp":true,"eniwa.hokkaido.jp":true,"erimo.hokkaido.jp":true,"esan.hokkaido.jp":true,"esashi.hokkaido.jp":true,"fukagawa.hokkaido.jp":true,"fukushima.hokkaido.jp":true,"furano.hokkaido.jp":true,"furubira.hokkaido.jp":true,"haboro.hokkaido.jp":true,"hakodate.hokkaido.jp":true,"hamatonbetsu.hokkaido.jp":true,"hidaka.hokkaido.jp":true,"higashikagura.hokkaido.jp":true,"higashikawa.hokkaido.jp":true,"hiroo.hokkaido.jp":true,"hokuryu.hokkaido.jp":true,"hokuto.hokkaido.jp":true,"honbetsu.hokkaido.jp":true,"horokanai.hokkaido.jp":true,"horonobe.hokkaido.jp":true,"ikeda.hokkaido.jp":true,"imakane.hokkaido.jp":true,"ishikari.hokkaido.jp":true,"iwamizawa.hokkaido.jp":true,"iwanai.hokkaido.jp":true,"kamifurano.hokkaido.jp":true,"kamikawa.hokkaido.jp":true,"kamishihoro.hokkaido.jp":true,"kamisunagawa.hokkaido.jp":true,"kamoenai.hokkaido.jp":true,"kayabe.hokkaido.jp":true,"kembuchi.hokkaido.jp":true,"kikonai.hokkaido.jp":true,"kimobetsu.hokkaido.jp":true,"kitahiroshima.hokkaido.jp":true,"kitami.hokkaido.jp":true,"kiyosato.hokkaido.jp":true,"koshimizu.hokkaido.jp":true,"kunneppu.hokkaido.jp":true,"kuriyama.hokkaido.jp":true,"kuromatsunai.hokkaido.jp":true,"kushiro.hokkaido.jp":true,"kutchan.hokkaido.jp":true,"kyowa.hokkaido.jp":true,"mashike.hokkaido.jp":true,"matsumae.hokkaido.jp":true,"mikasa.hokkaido.jp":true,"minamifurano.hokkaido.jp":true,"mombetsu.hokkaido.jp":true,"moseushi.hokkaido.jp":true,"mukawa.hokkaido.jp":true,"muroran.hokkaido.jp":true,"naie.hokkaido.jp":true,"nakagawa.hokkaido.jp":true,"nakasatsunai.hokkaido.jp":true,"nakatombetsu.hokkaido.jp":true,"nanae.hokkaido.jp":true,"nanporo.hokkaido.jp":true,"nayoro.hokkaido.jp":true,"nemuro.hokkaido.jp":true,"niikappu.hokkaido.jp":true,"niki.hokkaido.jp":true,"nishiokoppe.hokkaido.jp":true,"noboribetsu.hokkaido.jp":true,"numata.hokkaido.jp":true,"obihiro.hokkaido.jp":true,"obira.hokkaido.jp":true,"oketo.hokkaido.jp":true,"okoppe.hokkaido.jp":true,"otaru.hokkaido.jp":true,"otobe.hokkaido.jp":true,"otofuke.hokkaido.jp":true,"otoineppu.hokkaido.jp":true,"oumu.hokkaido.jp":true,"ozora.hokkaido.jp":true,"pippu.hokkaido.jp":true,"rankoshi.hokkaido.jp":true,"rebun.hokkaido.jp":true,"rikubetsu.hokkaido.jp":true,"rishiri.hokkaido.jp":true,"rishirifuji.hokkaido.jp":true,"saroma.hokkaido.jp":true,"sarufutsu.hokkaido.jp":true,"shakotan.hokkaido.jp":true,"shari.hokkaido.jp":true,"shibecha.hokkaido.jp":true,"shibetsu.hokkaido.jp":true,"shikabe.hokkaido.jp":true,"shikaoi.hokkaido.jp":true,"shimamaki.hokkaido.jp":true,"shimizu.hokkaido.jp":true,"shimokawa.hokkaido.jp":true,"shinshinotsu.hokkaido.jp":true,"shintoku.hokkaido.jp":true,"shiranuka.hokkaido.jp":true,"shiraoi.hokkaido.jp":true,"shiriuchi.hokkaido.jp":true,"sobetsu.hokkaido.jp":true,"sunagawa.hokkaido.jp":true,"taiki.hokkaido.jp":true,"takasu.hokkaido.jp":true,"takikawa.hokkaido.jp":true,"takinoue.hokkaido.jp":true,"teshikaga.hokkaido.jp":true,"tobetsu.hokkaido.jp":true,"tohma.hokkaido.jp":true,"tomakomai.hokkaido.jp":true,"tomari.hokkaido.jp":true,"toya.hokkaido.jp":true,"toyako.hokkaido.jp":true,"toyotomi.hokkaido.jp":true,"toyoura.hokkaido.jp":true,"tsubetsu.hokkaido.jp":true,"tsukigata.hokkaido.jp":true,"urakawa.hokkaido.jp":true,"urausu.hokkaido.jp":true,"uryu.hokkaido.jp":true,"utashinai.hokkaido.jp":true,"wakkanai.hokkaido.jp":true,"wassamu.hokkaido.jp":true,"yakumo.hokkaido.jp":true,"yoichi.hokkaido.jp":true,"aioi.hyogo.jp":true,"akashi.hyogo.jp":true,"ako.hyogo.jp":true,"amagasaki.hyogo.jp":true,"aogaki.hyogo.jp":true,"asago.hyogo.jp":true,"ashiya.hyogo.jp":true,"awaji.hyogo.jp":true,"fukusaki.hyogo.jp":true,"goshiki.hyogo.jp":true,"harima.hyogo.jp":true,"himeji.hyogo.jp":true,"ichikawa.hyogo.jp":true,"inagawa.hyogo.jp":true,"itami.hyogo.jp":true,"kakogawa.hyogo.jp":true,"kamigori.hyogo.jp":true,"kamikawa.hyogo.jp":true,"kasai.hyogo.jp":true,"kasuga.hyogo.jp":true,"kawanishi.hyogo.jp":true,"miki.hyogo.jp":true,"minamiawaji.hyogo.jp":true,"nishinomiya.hyogo.jp":true,"nishiwaki.hyogo.jp":true,"ono.hyogo.jp":true,"sanda.hyogo.jp":true,"sannan.hyogo.jp":true,"sasayama.hyogo.jp":true,"sayo.hyogo.jp":true,"shingu.hyogo.jp":true,"shinonsen.hyogo.jp":true,"shiso.hyogo.jp":true,"sumoto.hyogo.jp":true,"taishi.hyogo.jp":true,"taka.hyogo.jp":true,"takarazuka.hyogo.jp":true,"takasago.hyogo.jp":true,"takino.hyogo.jp":true,"tamba.hyogo.jp":true,"tatsuno.hyogo.jp":true,"toyooka.hyogo.jp":true,"yabu.hyogo.jp":true,"yashiro.hyogo.jp":true,"yoka.hyogo.jp":true,"yokawa.hyogo.jp":true,"ami.ibaraki.jp":true,"asahi.ibaraki.jp":true,"bando.ibaraki.jp":true,"chikusei.ibaraki.jp":true,"daigo.ibaraki.jp":true,"fujishiro.ibaraki.jp":true,"hitachi.ibaraki.jp":true,"hitachinaka.ibaraki.jp":true,"hitachiomiya.ibaraki.jp":true,"hitachiota.ibaraki.jp":true,"ibaraki.ibaraki.jp":true,"ina.ibaraki.jp":true,"inashiki.ibaraki.jp":true,"itako.ibaraki.jp":true,"iwama.ibaraki.jp":true,"joso.ibaraki.jp":true,"kamisu.ibaraki.jp":true,"kasama.ibaraki.jp":true,"kashima.ibaraki.jp":true,"kasumigaura.ibaraki.jp":true,"koga.ibaraki.jp":true,"miho.ibaraki.jp":true,"mito.ibaraki.jp":true,"moriya.ibaraki.jp":true,"naka.ibaraki.jp":true,"namegata.ibaraki.jp":true,"oarai.ibaraki.jp":true,"ogawa.ibaraki.jp":true,"omitama.ibaraki.jp":true,"ryugasaki.ibaraki.jp":true,"sakai.ibaraki.jp":true,"sakuragawa.ibaraki.jp":true,"shimodate.ibaraki.jp":true,"shimotsuma.ibaraki.jp":true,"shirosato.ibaraki.jp":true,"sowa.ibaraki.jp":true,"suifu.ibaraki.jp":true,"takahagi.ibaraki.jp":true,"tamatsukuri.ibaraki.jp":true,"tokai.ibaraki.jp":true,"tomobe.ibaraki.jp":true,"tone.ibaraki.jp":true,"toride.ibaraki.jp":true,"tsuchiura.ibaraki.jp":true,"tsukuba.ibaraki.jp":true,"uchihara.ibaraki.jp":true,"ushiku.ibaraki.jp":true,"yachiyo.ibaraki.jp":true,"yamagata.ibaraki.jp":true,"yawara.ibaraki.jp":true,"yuki.ibaraki.jp":true,"anamizu.ishikawa.jp":true,"hakui.ishikawa.jp":true,"hakusan.ishikawa.jp":true,"kaga.ishikawa.jp":true,"kahoku.ishikawa.jp":true,"kanazawa.ishikawa.jp":true,"kawakita.ishikawa.jp":true,"komatsu.ishikawa.jp":true,"nakanoto.ishikawa.jp":true,"nanao.ishikawa.jp":true,"nomi.ishikawa.jp":true,"nonoichi.ishikawa.jp":true,"noto.ishikawa.jp":true,"shika.ishikawa.jp":true,"suzu.ishikawa.jp":true,"tsubata.ishikawa.jp":true,"tsurugi.ishikawa.jp":true,"uchinada.ishikawa.jp":true,"wajima.ishikawa.jp":true,"fudai.iwate.jp":true,"fujisawa.iwate.jp":true,"hanamaki.iwate.jp":true,"hiraizumi.iwate.jp":true,"hirono.iwate.jp":true,"ichinohe.iwate.jp":true,"ichinoseki.iwate.jp":true,"iwaizumi.iwate.jp":true,"iwate.iwate.jp":true,"joboji.iwate.jp":true,"kamaishi.iwate.jp":true,"kanegasaki.iwate.jp":true,"karumai.iwate.jp":true,"kawai.iwate.jp":true,"kitakami.iwate.jp":true,"kuji.iwate.jp":true,"kunohe.iwate.jp":true,"kuzumaki.iwate.jp":true,"miyako.iwate.jp":true,"mizusawa.iwate.jp":true,"morioka.iwate.jp":true,"ninohe.iwate.jp":true,"noda.iwate.jp":true,"ofunato.iwate.jp":true,"oshu.iwate.jp":true,"otsuchi.iwate.jp":true,"rikuzentakata.iwate.jp":true,"shiwa.iwate.jp":true,"shizukuishi.iwate.jp":true,"sumita.iwate.jp":true,"tanohata.iwate.jp":true,"tono.iwate.jp":true,"yahaba.iwate.jp":true,"yamada.iwate.jp":true,"ayagawa.kagawa.jp":true,"higashikagawa.kagawa.jp":true,"kanonji.kagawa.jp":true,"kotohira.kagawa.jp":true,"manno.kagawa.jp":true,"marugame.kagawa.jp":true,"mitoyo.kagawa.jp":true,"naoshima.kagawa.jp":true,"sanuki.kagawa.jp":true,"tadotsu.kagawa.jp":true,"takamatsu.kagawa.jp":true,"tonosho.kagawa.jp":true,"uchinomi.kagawa.jp":true,"utazu.kagawa.jp":true,"zentsuji.kagawa.jp":true,"akune.kagoshima.jp":true,"amami.kagoshima.jp":true,"hioki.kagoshima.jp":true,"isa.kagoshima.jp":true,"isen.kagoshima.jp":true,"izumi.kagoshima.jp":true,"kagoshima.kagoshima.jp":true,"kanoya.kagoshima.jp":true,"kawanabe.kagoshima.jp":true,"kinko.kagoshima.jp":true,"kouyama.kagoshima.jp":true,"makurazaki.kagoshima.jp":true,"matsumoto.kagoshima.jp":true,"minamitane.kagoshima.jp":true,"nakatane.kagoshima.jp":true,"nishinoomote.kagoshima.jp":true,"satsumasendai.kagoshima.jp":true,"soo.kagoshima.jp":true,"tarumizu.kagoshima.jp":true,"yusui.kagoshima.jp":true,"aikawa.kanagawa.jp":true,"atsugi.kanagawa.jp":true,"ayase.kanagawa.jp":true,"chigasaki.kanagawa.jp":true,"ebina.kanagawa.jp":true,"fujisawa.kanagawa.jp":true,"hadano.kanagawa.jp":true,"hakone.kanagawa.jp":true,"hiratsuka.kanagawa.jp":true,"isehara.kanagawa.jp":true,"kaisei.kanagawa.jp":true,"kamakura.kanagawa.jp":true,"kiyokawa.kanagawa.jp":true,"matsuda.kanagawa.jp":true,"minamiashigara.kanagawa.jp":true,"miura.kanagawa.jp":true,"nakai.kanagawa.jp":true,"ninomiya.kanagawa.jp":true,"odawara.kanagawa.jp":true,"oi.kanagawa.jp":true,"oiso.kanagawa.jp":true,"sagamihara.kanagawa.jp":true,"samukawa.kanagawa.jp":true,"tsukui.kanagawa.jp":true,"yamakita.kanagawa.jp":true,"yamato.kanagawa.jp":true,"yokosuka.kanagawa.jp":true,"yugawara.kanagawa.jp":true,"zama.kanagawa.jp":true,"zushi.kanagawa.jp":true,"aki.kochi.jp":true,"geisei.kochi.jp":true,"hidaka.kochi.jp":true,"higashitsuno.kochi.jp":true,"ino.kochi.jp":true,"kagami.kochi.jp":true,"kami.kochi.jp":true,"kitagawa.kochi.jp":true,"kochi.kochi.jp":true,"mihara.kochi.jp":true,"motoyama.kochi.jp":true,"muroto.kochi.jp":true,"nahari.kochi.jp":true,"nakamura.kochi.jp":true,"nankoku.kochi.jp":true,"nishitosa.kochi.jp":true,"niyodogawa.kochi.jp":true,"ochi.kochi.jp":true,"okawa.kochi.jp":true,"otoyo.kochi.jp":true,"otsuki.kochi.jp":true,"sakawa.kochi.jp":true,"sukumo.kochi.jp":true,"susaki.kochi.jp":true,"tosa.kochi.jp":true,"tosashimizu.kochi.jp":true,"toyo.kochi.jp":true,"tsuno.kochi.jp":true,"umaji.kochi.jp":true,"yasuda.kochi.jp":true,"yusuhara.kochi.jp":true,"amakusa.kumamoto.jp":true,"arao.kumamoto.jp":true,"aso.kumamoto.jp":true,"choyo.kumamoto.jp":true,"gyokuto.kumamoto.jp":true,"hitoyoshi.kumamoto.jp":true,"kamiamakusa.kumamoto.jp":true,"kashima.kumamoto.jp":true,"kikuchi.kumamoto.jp":true,"kosa.kumamoto.jp":true,"kumamoto.kumamoto.jp":true,"mashiki.kumamoto.jp":true,"mifune.kumamoto.jp":true,"minamata.kumamoto.jp":true,"minamioguni.kumamoto.jp":true,"nagasu.kumamoto.jp":true,"nishihara.kumamoto.jp":true,"oguni.kumamoto.jp":true,"ozu.kumamoto.jp":true,"sumoto.kumamoto.jp":true,"takamori.kumamoto.jp":true,"uki.kumamoto.jp":true,"uto.kumamoto.jp":true,"yamaga.kumamoto.jp":true,"yamato.kumamoto.jp":true,"yatsushiro.kumamoto.jp":true,"ayabe.kyoto.jp":true,"fukuchiyama.kyoto.jp":true,"higashiyama.kyoto.jp":true,"ide.kyoto.jp":true,"ine.kyoto.jp":true,"joyo.kyoto.jp":true,"kameoka.kyoto.jp":true,"kamo.kyoto.jp":true,"kita.kyoto.jp":true,"kizu.kyoto.jp":true,"kumiyama.kyoto.jp":true,"kyotamba.kyoto.jp":true,"kyotanabe.kyoto.jp":true,"kyotango.kyoto.jp":true,"maizuru.kyoto.jp":true,"minami.kyoto.jp":true,"minamiyamashiro.kyoto.jp":true,"miyazu.kyoto.jp":true,"muko.kyoto.jp":true,"nagaokakyo.kyoto.jp":true,"nakagyo.kyoto.jp":true,"nantan.kyoto.jp":true,"oyamazaki.kyoto.jp":true,"sakyo.kyoto.jp":true,"seika.kyoto.jp":true,"tanabe.kyoto.jp":true,"uji.kyoto.jp":true,"ujitawara.kyoto.jp":true,"wazuka.kyoto.jp":true,"yamashina.kyoto.jp":true,"yawata.kyoto.jp":true,"asahi.mie.jp":true,"inabe.mie.jp":true,"ise.mie.jp":true,"kameyama.mie.jp":true,"kawagoe.mie.jp":true,"kiho.mie.jp":true,"kisosaki.mie.jp":true,"kiwa.mie.jp":true,"komono.mie.jp":true,"kumano.mie.jp":true,"kuwana.mie.jp":true,"matsusaka.mie.jp":true,"meiwa.mie.jp":true,"mihama.mie.jp":true,"minamiise.mie.jp":true,"misugi.mie.jp":true,"miyama.mie.jp":true,"nabari.mie.jp":true,"shima.mie.jp":true,"suzuka.mie.jp":true,"tado.mie.jp":true,"taiki.mie.jp":true,"taki.mie.jp":true,"tamaki.mie.jp":true,"toba.mie.jp":true,"tsu.mie.jp":true,"udono.mie.jp":true,"ureshino.mie.jp":true,"watarai.mie.jp":true,"yokkaichi.mie.jp":true,"furukawa.miyagi.jp":true,"higashimatsushima.miyagi.jp":true,"ishinomaki.miyagi.jp":true,"iwanuma.miyagi.jp":true,"kakuda.miyagi.jp":true,"kami.miyagi.jp":true,"kawasaki.miyagi.jp":true,"kesennuma.miyagi.jp":true,"marumori.miyagi.jp":true,"matsushima.miyagi.jp":true,"minamisanriku.miyagi.jp":true,"misato.miyagi.jp":true,"murata.miyagi.jp":true,"natori.miyagi.jp":true,"ogawara.miyagi.jp":true,"ohira.miyagi.jp":true,"onagawa.miyagi.jp":true,"osaki.miyagi.jp":true,"rifu.miyagi.jp":true,"semine.miyagi.jp":true,"shibata.miyagi.jp":true,"shichikashuku.miyagi.jp":true,"shikama.miyagi.jp":true,"shiogama.miyagi.jp":true,"shiroishi.miyagi.jp":true,"tagajo.miyagi.jp":true,"taiwa.miyagi.jp":true,"tome.miyagi.jp":true,"tomiya.miyagi.jp":true,"wakuya.miyagi.jp":true,"watari.miyagi.jp":true,"yamamoto.miyagi.jp":true,"zao.miyagi.jp":true,"aya.miyazaki.jp":true,"ebino.miyazaki.jp":true,"gokase.miyazaki.jp":true,"hyuga.miyazaki.jp":true,"kadogawa.miyazaki.jp":true,"kawaminami.miyazaki.jp":true,"kijo.miyazaki.jp":true,"kitagawa.miyazaki.jp":true,"kitakata.miyazaki.jp":true,"kitaura.miyazaki.jp":true,"kobayashi.miyazaki.jp":true,"kunitomi.miyazaki.jp":true,"kushima.miyazaki.jp":true,"mimata.miyazaki.jp":true,"miyakonojo.miyazaki.jp":true,"miyazaki.miyazaki.jp":true,"morotsuka.miyazaki.jp":true,"nichinan.miyazaki.jp":true,"nishimera.miyazaki.jp":true,"nobeoka.miyazaki.jp":true,"saito.miyazaki.jp":true,"shiiba.miyazaki.jp":true,"shintomi.miyazaki.jp":true,"takaharu.miyazaki.jp":true,"takanabe.miyazaki.jp":true,"takazaki.miyazaki.jp":true,"tsuno.miyazaki.jp":true,"achi.nagano.jp":true,"agematsu.nagano.jp":true,"anan.nagano.jp":true,"aoki.nagano.jp":true,"asahi.nagano.jp":true,"azumino.nagano.jp":true,"chikuhoku.nagano.jp":true,"chikuma.nagano.jp":true,"chino.nagano.jp":true,"fujimi.nagano.jp":true,"hakuba.nagano.jp":true,"hara.nagano.jp":true,"hiraya.nagano.jp":true,"iida.nagano.jp":true,"iijima.nagano.jp":true,"iiyama.nagano.jp":true,"iizuna.nagano.jp":true,"ikeda.nagano.jp":true,"ikusaka.nagano.jp":true,"ina.nagano.jp":true,"karuizawa.nagano.jp":true,"kawakami.nagano.jp":true,"kiso.nagano.jp":true,"kisofukushima.nagano.jp":true,"kitaaiki.nagano.jp":true,"komagane.nagano.jp":true,"komoro.nagano.jp":true,"matsukawa.nagano.jp":true,"matsumoto.nagano.jp":true,"miasa.nagano.jp":true,"minamiaiki.nagano.jp":true,"minamimaki.nagano.jp":true,"minamiminowa.nagano.jp":true,"minowa.nagano.jp":true,"miyada.nagano.jp":true,"miyota.nagano.jp":true,"mochizuki.nagano.jp":true,"nagano.nagano.jp":true,"nagawa.nagano.jp":true,"nagiso.nagano.jp":true,"nakagawa.nagano.jp":true,"nakano.nagano.jp":true,"nozawaonsen.nagano.jp":true,"obuse.nagano.jp":true,"ogawa.nagano.jp":true,"okaya.nagano.jp":true,"omachi.nagano.jp":true,"omi.nagano.jp":true,"ookuwa.nagano.jp":true,"ooshika.nagano.jp":true,"otaki.nagano.jp":true,"otari.nagano.jp":true,"sakae.nagano.jp":true,"sakaki.nagano.jp":true,"saku.nagano.jp":true,"sakuho.nagano.jp":true,"shimosuwa.nagano.jp":true,"shinanomachi.nagano.jp":true,"shiojiri.nagano.jp":true,"suwa.nagano.jp":true,"suzaka.nagano.jp":true,"takagi.nagano.jp":true,"takamori.nagano.jp":true,"takayama.nagano.jp":true,"tateshina.nagano.jp":true,"tatsuno.nagano.jp":true,"togakushi.nagano.jp":true,"togura.nagano.jp":true,"tomi.nagano.jp":true,"ueda.nagano.jp":true,"wada.nagano.jp":true,"yamagata.nagano.jp":true,"yamanouchi.nagano.jp":true,"yasaka.nagano.jp":true,"yasuoka.nagano.jp":true,"chijiwa.nagasaki.jp":true,"futsu.nagasaki.jp":true,"goto.nagasaki.jp":true,"hasami.nagasaki.jp":true,"hirado.nagasaki.jp":true,"iki.nagasaki.jp":true,"isahaya.nagasaki.jp":true,"kawatana.nagasaki.jp":true,"kuchinotsu.nagasaki.jp":true,"matsuura.nagasaki.jp":true,"nagasaki.nagasaki.jp":true,"obama.nagasaki.jp":true,"omura.nagasaki.jp":true,"oseto.nagasaki.jp":true,"saikai.nagasaki.jp":true,"sasebo.nagasaki.jp":true,"seihi.nagasaki.jp":true,"shimabara.nagasaki.jp":true,"shinkamigoto.nagasaki.jp":true,"togitsu.nagasaki.jp":true,"tsushima.nagasaki.jp":true,"unzen.nagasaki.jp":true,"ando.nara.jp":true,"gose.nara.jp":true,"heguri.nara.jp":true,"higashiyoshino.nara.jp":true,"ikaruga.nara.jp":true,"ikoma.nara.jp":true,"kamikitayama.nara.jp":true,"kanmaki.nara.jp":true,"kashiba.nara.jp":true,"kashihara.nara.jp":true,"katsuragi.nara.jp":true,"kawai.nara.jp":true,"kawakami.nara.jp":true,"kawanishi.nara.jp":true,"koryo.nara.jp":true,"kurotaki.nara.jp":true,"mitsue.nara.jp":true,"miyake.nara.jp":true,"nara.nara.jp":true,"nosegawa.nara.jp":true,"oji.nara.jp":true,"ouda.nara.jp":true,"oyodo.nara.jp":true,"sakurai.nara.jp":true,"sango.nara.jp":true,"shimoichi.nara.jp":true,"shimokitayama.nara.jp":true,"shinjo.nara.jp":true,"soni.nara.jp":true,"takatori.nara.jp":true,"tawaramoto.nara.jp":true,"tenkawa.nara.jp":true,"tenri.nara.jp":true,"uda.nara.jp":true,"yamatokoriyama.nara.jp":true,"yamatotakada.nara.jp":true,"yamazoe.nara.jp":true,"yoshino.nara.jp":true,"aga.niigata.jp":true,"agano.niigata.jp":true,"gosen.niigata.jp":true,"itoigawa.niigata.jp":true,"izumozaki.niigata.jp":true,"joetsu.niigata.jp":true,"kamo.niigata.jp":true,"kariwa.niigata.jp":true,"kashiwazaki.niigata.jp":true,"minamiuonuma.niigata.jp":true,"mitsuke.niigata.jp":true,"muika.niigata.jp":true,"murakami.niigata.jp":true,"myoko.niigata.jp":true,"nagaoka.niigata.jp":true,"niigata.niigata.jp":true,"ojiya.niigata.jp":true,"omi.niigata.jp":true,"sado.niigata.jp":true,"sanjo.niigata.jp":true,"seiro.niigata.jp":true,"seirou.niigata.jp":true,"sekikawa.niigata.jp":true,"shibata.niigata.jp":true,"tagami.niigata.jp":true,"tainai.niigata.jp":true,"tochio.niigata.jp":true,"tokamachi.niigata.jp":true,"tsubame.niigata.jp":true,"tsunan.niigata.jp":true,"uonuma.niigata.jp":true,"yahiko.niigata.jp":true,"yoita.niigata.jp":true,"yuzawa.niigata.jp":true,"beppu.oita.jp":true,"bungoono.oita.jp":true,"bungotakada.oita.jp":true,"hasama.oita.jp":true,"hiji.oita.jp":true,"himeshima.oita.jp":true,"hita.oita.jp":true,"kamitsue.oita.jp":true,"kokonoe.oita.jp":true,"kuju.oita.jp":true,"kunisaki.oita.jp":true,"kusu.oita.jp":true,"oita.oita.jp":true,"saiki.oita.jp":true,"taketa.oita.jp":true,"tsukumi.oita.jp":true,"usa.oita.jp":true,"usuki.oita.jp":true,"yufu.oita.jp":true,"akaiwa.okayama.jp":true,"asakuchi.okayama.jp":true,"bizen.okayama.jp":true,"hayashima.okayama.jp":true,"ibara.okayama.jp":true,"kagamino.okayama.jp":true,"kasaoka.okayama.jp":true,"kibichuo.okayama.jp":true,"kumenan.okayama.jp":true,"kurashiki.okayama.jp":true,"maniwa.okayama.jp":true,"misaki.okayama.jp":true,"nagi.okayama.jp":true,"niimi.okayama.jp":true,"nishiawakura.okayama.jp":true,"okayama.okayama.jp":true,"satosho.okayama.jp":true,"setouchi.okayama.jp":true,"shinjo.okayama.jp":true,"shoo.okayama.jp":true,"soja.okayama.jp":true,"takahashi.okayama.jp":true,"tamano.okayama.jp":true,"tsuyama.okayama.jp":true,"wake.okayama.jp":true,"yakage.okayama.jp":true,"aguni.okinawa.jp":true,"ginowan.okinawa.jp":true,"ginoza.okinawa.jp":true,"gushikami.okinawa.jp":true,"haebaru.okinawa.jp":true,"higashi.okinawa.jp":true,"hirara.okinawa.jp":true,"iheya.okinawa.jp":true,"ishigaki.okinawa.jp":true,"ishikawa.okinawa.jp":true,"itoman.okinawa.jp":true,"izena.okinawa.jp":true,"kadena.okinawa.jp":true,"kin.okinawa.jp":true,"kitadaito.okinawa.jp":true,"kitanakagusuku.okinawa.jp":true,"kumejima.okinawa.jp":true,"kunigami.okinawa.jp":true,"minamidaito.okinawa.jp":true,"motobu.okinawa.jp":true,"nago.okinawa.jp":true,"naha.okinawa.jp":true,"nakagusuku.okinawa.jp":true,"nakijin.okinawa.jp":true,"nanjo.okinawa.jp":true,"nishihara.okinawa.jp":true,"ogimi.okinawa.jp":true,"okinawa.okinawa.jp":true,"onna.okinawa.jp":true,"shimoji.okinawa.jp":true,"taketomi.okinawa.jp":true,"tarama.okinawa.jp":true,"tokashiki.okinawa.jp":true,"tomigusuku.okinawa.jp":true,"tonaki.okinawa.jp":true,"urasoe.okinawa.jp":true,"uruma.okinawa.jp":true,"yaese.okinawa.jp":true,"yomitan.okinawa.jp":true,"yonabaru.okinawa.jp":true,"yonaguni.okinawa.jp":true,"zamami.okinawa.jp":true,"abeno.osaka.jp":true,"chihayaakasaka.osaka.jp":true,"chuo.osaka.jp":true,"daito.osaka.jp":true,"fujiidera.osaka.jp":true,"habikino.osaka.jp":true,"hannan.osaka.jp":true,"higashiosaka.osaka.jp":true,"higashisumiyoshi.osaka.jp":true,"higashiyodogawa.osaka.jp":true,"hirakata.osaka.jp":true,"ibaraki.osaka.jp":true,"ikeda.osaka.jp":true,"izumi.osaka.jp":true,"izumiotsu.osaka.jp":true,"izumisano.osaka.jp":true,"kadoma.osaka.jp":true,"kaizuka.osaka.jp":true,"kanan.osaka.jp":true,"kashiwara.osaka.jp":true,"katano.osaka.jp":true,"kawachinagano.osaka.jp":true,"kishiwada.osaka.jp":true,"kita.osaka.jp":true,"kumatori.osaka.jp":true,"matsubara.osaka.jp":true,"minato.osaka.jp":true,"minoh.osaka.jp":true,"misaki.osaka.jp":true,"moriguchi.osaka.jp":true,"neyagawa.osaka.jp":true,"nishi.osaka.jp":true,"nose.osaka.jp":true,"osakasayama.osaka.jp":true,"sakai.osaka.jp":true,"sayama.osaka.jp":true,"sennan.osaka.jp":true,"settsu.osaka.jp":true,"shijonawate.osaka.jp":true,"shimamoto.osaka.jp":true,"suita.osaka.jp":true,"tadaoka.osaka.jp":true,"taishi.osaka.jp":true,"tajiri.osaka.jp":true,"takaishi.osaka.jp":true,"takatsuki.osaka.jp":true,"tondabayashi.osaka.jp":true,"toyonaka.osaka.jp":true,"toyono.osaka.jp":true,"yao.osaka.jp":true,"ariake.saga.jp":true,"arita.saga.jp":true,"fukudomi.saga.jp":true,"genkai.saga.jp":true,"hamatama.saga.jp":true,"hizen.saga.jp":true,"imari.saga.jp":true,"kamimine.saga.jp":true,"kanzaki.saga.jp":true,"karatsu.saga.jp":true,"kashima.saga.jp":true,"kitagata.saga.jp":true,"kitahata.saga.jp":true,"kiyama.saga.jp":true,"kouhoku.saga.jp":true,"kyuragi.saga.jp":true,"nishiarita.saga.jp":true,"ogi.saga.jp":true,"omachi.saga.jp":true,"ouchi.saga.jp":true,"saga.saga.jp":true,"shiroishi.saga.jp":true,"taku.saga.jp":true,"tara.saga.jp":true,"tosu.saga.jp":true,"yoshinogari.saga.jp":true,"arakawa.saitama.jp":true,"asaka.saitama.jp":true,"chichibu.saitama.jp":true,"fujimi.saitama.jp":true,"fujimino.saitama.jp":true,"fukaya.saitama.jp":true,"hanno.saitama.jp":true,"hanyu.saitama.jp":true,"hasuda.saitama.jp":true,"hatogaya.saitama.jp":true,"hatoyama.saitama.jp":true,"hidaka.saitama.jp":true,"higashichichibu.saitama.jp":true,"higashimatsuyama.saitama.jp":true,"honjo.saitama.jp":true,"ina.saitama.jp":true,"iruma.saitama.jp":true,"iwatsuki.saitama.jp":true,"kamiizumi.saitama.jp":true,"kamikawa.saitama.jp":true,"kamisato.saitama.jp":true,"kasukabe.saitama.jp":true,"kawagoe.saitama.jp":true,"kawaguchi.saitama.jp":true,"kawajima.saitama.jp":true,"kazo.saitama.jp":true,"kitamoto.saitama.jp":true,"koshigaya.saitama.jp":true,"kounosu.saitama.jp":true,"kuki.saitama.jp":true,"kumagaya.saitama.jp":true,"matsubushi.saitama.jp":true,"minano.saitama.jp":true,"misato.saitama.jp":true,"miyashiro.saitama.jp":true,"miyoshi.saitama.jp":true,"moroyama.saitama.jp":true,"nagatoro.saitama.jp":true,"namegawa.saitama.jp":true,"niiza.saitama.jp":true,"ogano.saitama.jp":true,"ogawa.saitama.jp":true,"ogose.saitama.jp":true,"okegawa.saitama.jp":true,"omiya.saitama.jp":true,"otaki.saitama.jp":true,"ranzan.saitama.jp":true,"ryokami.saitama.jp":true,"saitama.saitama.jp":true,"sakado.saitama.jp":true,"satte.saitama.jp":true,"sayama.saitama.jp":true,"shiki.saitama.jp":true,"shiraoka.saitama.jp":true,"soka.saitama.jp":true,"sugito.saitama.jp":true,"toda.saitama.jp":true,"tokigawa.saitama.jp":true,"tokorozawa.saitama.jp":true,"tsurugashima.saitama.jp":true,"urawa.saitama.jp":true,"warabi.saitama.jp":true,"yashio.saitama.jp":true,"yokoze.saitama.jp":true,"yono.saitama.jp":true,"yorii.saitama.jp":true,"yoshida.saitama.jp":true,"yoshikawa.saitama.jp":true,"yoshimi.saitama.jp":true,"aisho.shiga.jp":true,"gamo.shiga.jp":true,"higashiomi.shiga.jp":true,"hikone.shiga.jp":true,"koka.shiga.jp":true,"konan.shiga.jp":true,"kosei.shiga.jp":true,"koto.shiga.jp":true,"kusatsu.shiga.jp":true,"maibara.shiga.jp":true,"moriyama.shiga.jp":true,"nagahama.shiga.jp":true,"nishiazai.shiga.jp":true,"notogawa.shiga.jp":true,"omihachiman.shiga.jp":true,"otsu.shiga.jp":true,"ritto.shiga.jp":true,"ryuoh.shiga.jp":true,"takashima.shiga.jp":true,"takatsuki.shiga.jp":true,"torahime.shiga.jp":true,"toyosato.shiga.jp":true,"yasu.shiga.jp":true,"akagi.shimane.jp":true,"ama.shimane.jp":true,"gotsu.shimane.jp":true,"hamada.shimane.jp":true,"higashiizumo.shimane.jp":true,"hikawa.shimane.jp":true,"hikimi.shimane.jp":true,"izumo.shimane.jp":true,"kakinoki.shimane.jp":true,"masuda.shimane.jp":true,"matsue.shimane.jp":true,"misato.shimane.jp":true,"nishinoshima.shimane.jp":true,"ohda.shimane.jp":true,"okinoshima.shimane.jp":true,"okuizumo.shimane.jp":true,"shimane.shimane.jp":true,"tamayu.shimane.jp":true,"tsuwano.shimane.jp":true,"unnan.shimane.jp":true,"yakumo.shimane.jp":true,"yasugi.shimane.jp":true,"yatsuka.shimane.jp":true,"arai.shizuoka.jp":true,"atami.shizuoka.jp":true,"fuji.shizuoka.jp":true,"fujieda.shizuoka.jp":true,"fujikawa.shizuoka.jp":true,"fujinomiya.shizuoka.jp":true,"fukuroi.shizuoka.jp":true,"gotemba.shizuoka.jp":true,"haibara.shizuoka.jp":true,"hamamatsu.shizuoka.jp":true,"higashiizu.shizuoka.jp":true,"ito.shizuoka.jp":true,"iwata.shizuoka.jp":true,"izu.shizuoka.jp":true,"izunokuni.shizuoka.jp":true,"kakegawa.shizuoka.jp":true,"kannami.shizuoka.jp":true,"kawanehon.shizuoka.jp":true,"kawazu.shizuoka.jp":true,"kikugawa.shizuoka.jp":true,"kosai.shizuoka.jp":true,"makinohara.shizuoka.jp":true,"matsuzaki.shizuoka.jp":true,"minamiizu.shizuoka.jp":true,"mishima.shizuoka.jp":true,"morimachi.shizuoka.jp":true,"nishiizu.shizuoka.jp":true,"numazu.shizuoka.jp":true,"omaezaki.shizuoka.jp":true,"shimada.shizuoka.jp":true,"shimizu.shizuoka.jp":true,"shimoda.shizuoka.jp":true,"shizuoka.shizuoka.jp":true,"susono.shizuoka.jp":true,"yaizu.shizuoka.jp":true,"yoshida.shizuoka.jp":true,"ashikaga.tochigi.jp":true,"bato.tochigi.jp":true,"haga.tochigi.jp":true,"ichikai.tochigi.jp":true,"iwafune.tochigi.jp":true,"kaminokawa.tochigi.jp":true,"kanuma.tochigi.jp":true,"karasuyama.tochigi.jp":true,"kuroiso.tochigi.jp":true,"mashiko.tochigi.jp":true,"mibu.tochigi.jp":true,"moka.tochigi.jp":true,"motegi.tochigi.jp":true,"nasu.tochigi.jp":true,"nasushiobara.tochigi.jp":true,"nikko.tochigi.jp":true,"nishikata.tochigi.jp":true,"nogi.tochigi.jp":true,"ohira.tochigi.jp":true,"ohtawara.tochigi.jp":true,"oyama.tochigi.jp":true,"sakura.tochigi.jp":true,"sano.tochigi.jp":true,"shimotsuke.tochigi.jp":true,"shioya.tochigi.jp":true,"takanezawa.tochigi.jp":true,"tochigi.tochigi.jp":true,"tsuga.tochigi.jp":true,"ujiie.tochigi.jp":true,"utsunomiya.tochigi.jp":true,"yaita.tochigi.jp":true,"aizumi.tokushima.jp":true,"anan.tokushima.jp":true,"ichiba.tokushima.jp":true,"itano.tokushima.jp":true,"kainan.tokushima.jp":true,"komatsushima.tokushima.jp":true,"matsushige.tokushima.jp":true,"mima.tokushima.jp":true,"minami.tokushima.jp":true,"miyoshi.tokushima.jp":true,"mugi.tokushima.jp":true,"nakagawa.tokushima.jp":true,"naruto.tokushima.jp":true,"sanagochi.tokushima.jp":true,"shishikui.tokushima.jp":true,"tokushima.tokushima.jp":true,"wajiki.tokushima.jp":true,"adachi.tokyo.jp":true,"akiruno.tokyo.jp":true,"akishima.tokyo.jp":true,"aogashima.tokyo.jp":true,"arakawa.tokyo.jp":true,"bunkyo.tokyo.jp":true,"chiyoda.tokyo.jp":true,"chofu.tokyo.jp":true,"chuo.tokyo.jp":true,"edogawa.tokyo.jp":true,"fuchu.tokyo.jp":true,"fussa.tokyo.jp":true,"hachijo.tokyo.jp":true,"hachioji.tokyo.jp":true,"hamura.tokyo.jp":true,"higashikurume.tokyo.jp":true,"higashimurayama.tokyo.jp":true,"higashiyamato.tokyo.jp":true,"hino.tokyo.jp":true,"hinode.tokyo.jp":true,"hinohara.tokyo.jp":true,"inagi.tokyo.jp":true,"itabashi.tokyo.jp":true,"katsushika.tokyo.jp":true,"kita.tokyo.jp":true,"kiyose.tokyo.jp":true,"kodaira.tokyo.jp":true,"koganei.tokyo.jp":true,"kokubunji.tokyo.jp":true,"komae.tokyo.jp":true,"koto.tokyo.jp":true,"kouzushima.tokyo.jp":true,"kunitachi.tokyo.jp":true,"machida.tokyo.jp":true,"meguro.tokyo.jp":true,"minato.tokyo.jp":true,"mitaka.tokyo.jp":true,"mizuho.tokyo.jp":true,"musashimurayama.tokyo.jp":true,"musashino.tokyo.jp":true,"nakano.tokyo.jp":true,"nerima.tokyo.jp":true,"ogasawara.tokyo.jp":true,"okutama.tokyo.jp":true,"ome.tokyo.jp":true,"oshima.tokyo.jp":true,"ota.tokyo.jp":true,"setagaya.tokyo.jp":true,"shibuya.tokyo.jp":true,"shinagawa.tokyo.jp":true,"shinjuku.tokyo.jp":true,"suginami.tokyo.jp":true,"sumida.tokyo.jp":true,"tachikawa.tokyo.jp":true,"taito.tokyo.jp":true,"tama.tokyo.jp":true,"toshima.tokyo.jp":true,"chizu.tottori.jp":true,"hino.tottori.jp":true,"kawahara.tottori.jp":true,"koge.tottori.jp":true,"kotoura.tottori.jp":true,"misasa.tottori.jp":true,"nanbu.tottori.jp":true,"nichinan.tottori.jp":true,"sakaiminato.tottori.jp":true,"tottori.tottori.jp":true,"wakasa.tottori.jp":true,"yazu.tottori.jp":true,"yonago.tottori.jp":true,"asahi.toyama.jp":true,"fuchu.toyama.jp":true,"fukumitsu.toyama.jp":true,"funahashi.toyama.jp":true,"himi.toyama.jp":true,"imizu.toyama.jp":true,"inami.toyama.jp":true,"johana.toyama.jp":true,"kamiichi.toyama.jp":true,"kurobe.toyama.jp":true,"nakaniikawa.toyama.jp":true,"namerikawa.toyama.jp":true,"nanto.toyama.jp":true,"nyuzen.toyama.jp":true,"oyabe.toyama.jp":true,"taira.toyama.jp":true,"takaoka.toyama.jp":true,"tateyama.toyama.jp":true,"toga.toyama.jp":true,"tonami.toyama.jp":true,"toyama.toyama.jp":true,"unazuki.toyama.jp":true,"uozu.toyama.jp":true,"yamada.toyama.jp":true,"arida.wakayama.jp":true,"aridagawa.wakayama.jp":true,"gobo.wakayama.jp":true,"hashimoto.wakayama.jp":true,"hidaka.wakayama.jp":true,"hirogawa.wakayama.jp":true,"inami.wakayama.jp":true,"iwade.wakayama.jp":true,"kainan.wakayama.jp":true,"kamitonda.wakayama.jp":true,"katsuragi.wakayama.jp":true,"kimino.wakayama.jp":true,"kinokawa.wakayama.jp":true,"kitayama.wakayama.jp":true,"koya.wakayama.jp":true,"koza.wakayama.jp":true,"kozagawa.wakayama.jp":true,"kudoyama.wakayama.jp":true,"kushimoto.wakayama.jp":true,"mihama.wakayama.jp":true,"misato.wakayama.jp":true,"nachikatsuura.wakayama.jp":true,"shingu.wakayama.jp":true,"shirahama.wakayama.jp":true,"taiji.wakayama.jp":true,"tanabe.wakayama.jp":true,"wakayama.wakayama.jp":true,"yuasa.wakayama.jp":true,"yura.wakayama.jp":true,"asahi.yamagata.jp":true,"funagata.yamagata.jp":true,"higashine.yamagata.jp":true,"iide.yamagata.jp":true,"kahoku.yamagata.jp":true,"kaminoyama.yamagata.jp":true,"kaneyama.yamagata.jp":true,"kawanishi.yamagata.jp":true,"mamurogawa.yamagata.jp":true,"mikawa.yamagata.jp":true,"murayama.yamagata.jp":true,"nagai.yamagata.jp":true,"nakayama.yamagata.jp":true,"nanyo.yamagata.jp":true,"nishikawa.yamagata.jp":true,"obanazawa.yamagata.jp":true,"oe.yamagata.jp":true,"oguni.yamagata.jp":true,"ohkura.yamagata.jp":true,"oishida.yamagata.jp":true,"sagae.yamagata.jp":true,"sakata.yamagata.jp":true,"sakegawa.yamagata.jp":true,"shinjo.yamagata.jp":true,"shirataka.yamagata.jp":true,"shonai.yamagata.jp":true,"takahata.yamagata.jp":true,"tendo.yamagata.jp":true,"tozawa.yamagata.jp":true,"tsuruoka.yamagata.jp":true,"yamagata.yamagata.jp":true,"yamanobe.yamagata.jp":true,"yonezawa.yamagata.jp":true,"yuza.yamagata.jp":true,"abu.yamaguchi.jp":true,"hagi.yamaguchi.jp":true,"hikari.yamaguchi.jp":true,"hofu.yamaguchi.jp":true,"iwakuni.yamaguchi.jp":true,"kudamatsu.yamaguchi.jp":true,"mitou.yamaguchi.jp":true,"nagato.yamaguchi.jp":true,"oshima.yamaguchi.jp":true,"shimonoseki.yamaguchi.jp":true,"shunan.yamaguchi.jp":true,"tabuse.yamaguchi.jp":true,"tokuyama.yamaguchi.jp":true,"toyota.yamaguchi.jp":true,"ube.yamaguchi.jp":true,"yuu.yamaguchi.jp":true,"chuo.yamanashi.jp":true,"doshi.yamanashi.jp":true,"fuefuki.yamanashi.jp":true,"fujikawa.yamanashi.jp":true,"fujikawaguchiko.yamanashi.jp":true,"fujiyoshida.yamanashi.jp":true,"hayakawa.yamanashi.jp":true,"hokuto.yamanashi.jp":true,"ichikawamisato.yamanashi.jp":true,"kai.yamanashi.jp":true,"kofu.yamanashi.jp":true,"koshu.yamanashi.jp":true,"kosuge.yamanashi.jp":true,"minami-alps.yamanashi.jp":true,"minobu.yamanashi.jp":true,"nakamichi.yamanashi.jp":true,"nanbu.yamanashi.jp":true,"narusawa.yamanashi.jp":true,"nirasaki.yamanashi.jp":true,"nishikatsura.yamanashi.jp":true,"oshino.yamanashi.jp":true,"otsuki.yamanashi.jp":true,"showa.yamanashi.jp":true,"tabayama.yamanashi.jp":true,"tsuru.yamanashi.jp":true,"uenohara.yamanashi.jp":true,"yamanakako.yamanashi.jp":true,"yamanashi.yamanashi.jp":true,"*.ke":true,"kg":true,"org.kg":true,"net.kg":true,"com.kg":true,"edu.kg":true,"gov.kg":true,"mil.kg":true,"*.kh":true,"ki":true,"edu.ki":true,"biz.ki":true,"net.ki":true,"org.ki":true,"gov.ki":true,"info.ki":true,"com.ki":true,"km":true,"org.km":true,"nom.km":true,"gov.km":true,"prd.km":true,"tm.km":true,"edu.km":true,"mil.km":true,"ass.km":true,"com.km":true,"coop.km":true,"asso.km":true,"presse.km":true,"medecin.km":true,"notaires.km":true,"pharmaciens.km":true,"veterinaire.km":true,"gouv.km":true,"kn":true,"net.kn":true,"org.kn":true,"edu.kn":true,"gov.kn":true,"kp":true,"com.kp":true,"edu.kp":true,"gov.kp":true,"org.kp":true,"rep.kp":true,"tra.kp":true,"kr":true,"ac.kr":true,"co.kr":true,"es.kr":true,"go.kr":true,"hs.kr":true,"kg.kr":true,"mil.kr":true,"ms.kr":true,"ne.kr":true,"or.kr":true,"pe.kr":true,"re.kr":true,"sc.kr":true,"busan.kr":true,"chungbuk.kr":true,"chungnam.kr":true,"daegu.kr":true,"daejeon.kr":true,"gangwon.kr":true,"gwangju.kr":true,"gyeongbuk.kr":true,"gyeonggi.kr":true,"gyeongnam.kr":true,"incheon.kr":true,"jeju.kr":true,"jeonbuk.kr":true,"jeonnam.kr":true,"seoul.kr":true,"ulsan.kr":true,"*.kw":true,"ky":true,"edu.ky":true,"gov.ky":true,"com.ky":true,"org.ky":true,"net.ky":true,"kz":true,"org.kz":true,"edu.kz":true,"net.kz":true,"gov.kz":true,"mil.kz":true,"com.kz":true,"la":true,"int.la":true,"net.la":true,"info.la":true,"edu.la":true,"gov.la":true,"per.la":true,"com.la":true,"org.la":true,"lb":true,"com.lb":true,"edu.lb":true,"gov.lb":true,"net.lb":true,"org.lb":true,"lc":true,"com.lc":true,"net.lc":true,"co.lc":true,"org.lc":true,"edu.lc":true,"gov.lc":true,"li":true,"lk":true,"gov.lk":true,"sch.lk":true,"net.lk":true,"int.lk":true,"com.lk":true,"org.lk":true,"edu.lk":true,"ngo.lk":true,"soc.lk":true,"web.lk":true,"ltd.lk":true,"assn.lk":true,"grp.lk":true,"hotel.lk":true,"ac.lk":true,"lr":true,"com.lr":true,"edu.lr":true,"gov.lr":true,"org.lr":true,"net.lr":true,"ls":true,"co.ls":true,"org.ls":true,"lt":true,"gov.lt":true,"lu":true,"lv":true,"com.lv":true,"edu.lv":true,"gov.lv":true,"org.lv":true,"mil.lv":true,"id.lv":true,"net.lv":true,"asn.lv":true,"conf.lv":true,"ly":true,"com.ly":true,"net.ly":true,"gov.ly":true,"plc.ly":true,"edu.ly":true,"sch.ly":true,"med.ly":true,"org.ly":true,"id.ly":true,"ma":true,"co.ma":true,"net.ma":true,"gov.ma":true,"org.ma":true,"ac.ma":true,"press.ma":true,"mc":true,"tm.mc":true,"asso.mc":true,"md":true,"me":true,"co.me":true,"net.me":true,"org.me":true,"edu.me":true,"ac.me":true,"gov.me":true,"its.me":true,"priv.me":true,"mg":true,"org.mg":true,"nom.mg":true,"gov.mg":true,"prd.mg":true,"tm.mg":true,"edu.mg":true,"mil.mg":true,"com.mg":true,"co.mg":true,"mh":true,"mil":true,"mk":true,"com.mk":true,"org.mk":true,"net.mk":true,"edu.mk":true,"gov.mk":true,"inf.mk":true,"name.mk":true,"ml":true,"com.ml":true,"edu.ml":true,"gouv.ml":true,"gov.ml":true,"net.ml":true,"org.ml":true,"presse.ml":true,"*.mm":true,"mn":true,"gov.mn":true,"edu.mn":true,"org.mn":true,"mo":true,"com.mo":true,"net.mo":true,"org.mo":true,"edu.mo":true,"gov.mo":true,"mobi":true,"mp":true,"mq":true,"mr":true,"gov.mr":true,"ms":true,"com.ms":true,"edu.ms":true,"gov.ms":true,"net.ms":true,"org.ms":true,"mt":true,"com.mt":true,"edu.mt":true,"net.mt":true,"org.mt":true,"mu":true,"com.mu":true,"net.mu":true,"org.mu":true,"gov.mu":true,"ac.mu":true,"co.mu":true,"or.mu":true,"museum":true,"academy.museum":true,"agriculture.museum":true,"air.museum":true,"airguard.museum":true,"alabama.museum":true,"alaska.museum":true,"amber.museum":true,"ambulance.museum":true,"american.museum":true,"americana.museum":true,"americanantiques.museum":true,"americanart.museum":true,"amsterdam.museum":true,"and.museum":true,"annefrank.museum":true,"anthro.museum":true,"anthropology.museum":true,"antiques.museum":true,"aquarium.museum":true,"arboretum.museum":true,"archaeological.museum":true,"archaeology.museum":true,"architecture.museum":true,"art.museum":true,"artanddesign.museum":true,"artcenter.museum":true,"artdeco.museum":true,"arteducation.museum":true,"artgallery.museum":true,"arts.museum":true,"artsandcrafts.museum":true,"asmatart.museum":true,"assassination.museum":true,"assisi.museum":true,"association.museum":true,"astronomy.museum":true,"atlanta.museum":true,"austin.museum":true,"australia.museum":true,"automotive.museum":true,"aviation.museum":true,"axis.museum":true,"badajoz.museum":true,"baghdad.museum":true,"bahn.museum":true,"bale.museum":true,"baltimore.museum":true,"barcelona.museum":true,"baseball.museum":true,"basel.museum":true,"baths.museum":true,"bauern.museum":true,"beauxarts.museum":true,"beeldengeluid.museum":true,"bellevue.museum":true,"bergbau.museum":true,"berkeley.museum":true,"berlin.museum":true,"bern.museum":true,"bible.museum":true,"bilbao.museum":true,"bill.museum":true,"birdart.museum":true,"birthplace.museum":true,"bonn.museum":true,"boston.museum":true,"botanical.museum":true,"botanicalgarden.museum":true,"botanicgarden.museum":true,"botany.museum":true,"brandywinevalley.museum":true,"brasil.museum":true,"bristol.museum":true,"british.museum":true,"britishcolumbia.museum":true,"broadcast.museum":true,"brunel.museum":true,"brussel.museum":true,"brussels.museum":true,"bruxelles.museum":true,"building.museum":true,"burghof.museum":true,"bus.museum":true,"bushey.museum":true,"cadaques.museum":true,"california.museum":true,"cambridge.museum":true,"can.museum":true,"canada.museum":true,"capebreton.museum":true,"carrier.museum":true,"cartoonart.museum":true,"casadelamoneda.museum":true,"castle.museum":true,"castres.museum":true,"celtic.museum":true,"center.museum":true,"chattanooga.museum":true,"cheltenham.museum":true,"chesapeakebay.museum":true,"chicago.museum":true,"children.museum":true,"childrens.museum":true,"childrensgarden.museum":true,"chiropractic.museum":true,"chocolate.museum":true,"christiansburg.museum":true,"cincinnati.museum":true,"cinema.museum":true,"circus.museum":true,"civilisation.museum":true,"civilization.museum":true,"civilwar.museum":true,"clinton.museum":true,"clock.museum":true,"coal.museum":true,"coastaldefence.museum":true,"cody.museum":true,"coldwar.museum":true,"collection.museum":true,"colonialwilliamsburg.museum":true,"coloradoplateau.museum":true,"columbia.museum":true,"columbus.museum":true,"communication.museum":true,"communications.museum":true,"community.museum":true,"computer.museum":true,"computerhistory.museum":true,"xn--comunicaes-v6a2o.museum":true,"contemporary.museum":true,"contemporaryart.museum":true,"convent.museum":true,"copenhagen.museum":true,"corporation.museum":true,"xn--correios-e-telecomunicaes-ghc29a.museum":true,"corvette.museum":true,"costume.museum":true,"countryestate.museum":true,"county.museum":true,"crafts.museum":true,"cranbrook.museum":true,"creation.museum":true,"cultural.museum":true,"culturalcenter.museum":true,"culture.museum":true,"cyber.museum":true,"cymru.museum":true,"dali.museum":true,"dallas.museum":true,"database.museum":true,"ddr.museum":true,"decorativearts.museum":true,"delaware.museum":true,"delmenhorst.museum":true,"denmark.museum":true,"depot.museum":true,"design.museum":true,"detroit.museum":true,"dinosaur.museum":true,"discovery.museum":true,"dolls.museum":true,"donostia.museum":true,"durham.museum":true,"eastafrica.museum":true,"eastcoast.museum":true,"education.museum":true,"educational.museum":true,"egyptian.museum":true,"eisenbahn.museum":true,"elburg.museum":true,"elvendrell.museum":true,"embroidery.museum":true,"encyclopedic.museum":true,"england.museum":true,"entomology.museum":true,"environment.museum":true,"environmentalconservation.museum":true,"epilepsy.museum":true,"essex.museum":true,"estate.museum":true,"ethnology.museum":true,"exeter.museum":true,"exhibition.museum":true,"family.museum":true,"farm.museum":true,"farmequipment.museum":true,"farmers.museum":true,"farmstead.museum":true,"field.museum":true,"figueres.museum":true,"filatelia.museum":true,"film.museum":true,"fineart.museum":true,"finearts.museum":true,"finland.museum":true,"flanders.museum":true,"florida.museum":true,"force.museum":true,"fortmissoula.museum":true,"fortworth.museum":true,"foundation.museum":true,"francaise.museum":true,"frankfurt.museum":true,"franziskaner.museum":true,"freemasonry.museum":true,"freiburg.museum":true,"fribourg.museum":true,"frog.museum":true,"fundacio.museum":true,"furniture.museum":true,"gallery.museum":true,"garden.museum":true,"gateway.museum":true,"geelvinck.museum":true,"gemological.museum":true,"geology.museum":true,"georgia.museum":true,"giessen.museum":true,"glas.museum":true,"glass.museum":true,"gorge.museum":true,"grandrapids.museum":true,"graz.museum":true,"guernsey.museum":true,"halloffame.museum":true,"hamburg.museum":true,"handson.museum":true,"harvestcelebration.museum":true,"hawaii.museum":true,"health.museum":true,"heimatunduhren.museum":true,"hellas.museum":true,"helsinki.museum":true,"hembygdsforbund.museum":true,"heritage.museum":true,"histoire.museum":true,"historical.museum":true,"historicalsociety.museum":true,"historichouses.museum":true,"historisch.museum":true,"historisches.museum":true,"history.museum":true,"historyofscience.museum":true,"horology.museum":true,"house.museum":true,"humanities.museum":true,"illustration.museum":true,"imageandsound.museum":true,"indian.museum":true,"indiana.museum":true,"indianapolis.museum":true,"indianmarket.museum":true,"intelligence.museum":true,"interactive.museum":true,"iraq.museum":true,"iron.museum":true,"isleofman.museum":true,"jamison.museum":true,"jefferson.museum":true,"jerusalem.museum":true,"jewelry.museum":true,"jewish.museum":true,"jewishart.museum":true,"jfk.museum":true,"journalism.museum":true,"judaica.museum":true,"judygarland.museum":true,"juedisches.museum":true,"juif.museum":true,"karate.museum":true,"karikatur.museum":true,"kids.museum":true,"koebenhavn.museum":true,"koeln.museum":true,"kunst.museum":true,"kunstsammlung.museum":true,"kunstunddesign.museum":true,"labor.museum":true,"labour.museum":true,"lajolla.museum":true,"lancashire.museum":true,"landes.museum":true,"lans.museum":true,"xn--lns-qla.museum":true,"larsson.museum":true,"lewismiller.museum":true,"lincoln.museum":true,"linz.museum":true,"living.museum":true,"livinghistory.museum":true,"localhistory.museum":true,"london.museum":true,"losangeles.museum":true,"louvre.museum":true,"loyalist.museum":true,"lucerne.museum":true,"luxembourg.museum":true,"luzern.museum":true,"mad.museum":true,"madrid.museum":true,"mallorca.museum":true,"manchester.museum":true,"mansion.museum":true,"mansions.museum":true,"manx.museum":true,"marburg.museum":true,"maritime.museum":true,"maritimo.museum":true,"maryland.museum":true,"marylhurst.museum":true,"media.museum":true,"medical.museum":true,"medizinhistorisches.museum":true,"meeres.museum":true,"memorial.museum":true,"mesaverde.museum":true,"michigan.museum":true,"midatlantic.museum":true,"military.museum":true,"mill.museum":true,"miners.museum":true,"mining.museum":true,"minnesota.museum":true,"missile.museum":true,"missoula.museum":true,"modern.museum":true,"moma.museum":true,"money.museum":true,"monmouth.museum":true,"monticello.museum":true,"montreal.museum":true,"moscow.museum":true,"motorcycle.museum":true,"muenchen.museum":true,"muenster.museum":true,"mulhouse.museum":true,"muncie.museum":true,"museet.museum":true,"museumcenter.museum":true,"museumvereniging.museum":true,"music.museum":true,"national.museum":true,"nationalfirearms.museum":true,"nationalheritage.museum":true,"nativeamerican.museum":true,"naturalhistory.museum":true,"naturalhistorymuseum.museum":true,"naturalsciences.museum":true,"nature.museum":true,"naturhistorisches.museum":true,"natuurwetenschappen.museum":true,"naumburg.museum":true,"naval.museum":true,"nebraska.museum":true,"neues.museum":true,"newhampshire.museum":true,"newjersey.museum":true,"newmexico.museum":true,"newport.museum":true,"newspaper.museum":true,"newyork.museum":true,"niepce.museum":true,"norfolk.museum":true,"north.museum":true,"nrw.museum":true,"nuernberg.museum":true,"nuremberg.museum":true,"nyc.museum":true,"nyny.museum":true,"oceanographic.museum":true,"oceanographique.museum":true,"omaha.museum":true,"online.museum":true,"ontario.museum":true,"openair.museum":true,"oregon.museum":true,"oregontrail.museum":true,"otago.museum":true,"oxford.museum":true,"pacific.museum":true,"paderborn.museum":true,"palace.museum":true,"paleo.museum":true,"palmsprings.museum":true,"panama.museum":true,"paris.museum":true,"pasadena.museum":true,"pharmacy.museum":true,"philadelphia.museum":true,"philadelphiaarea.museum":true,"philately.museum":true,"phoenix.museum":true,"photography.museum":true,"pilots.museum":true,"pittsburgh.museum":true,"planetarium.museum":true,"plantation.museum":true,"plants.museum":true,"plaza.museum":true,"portal.museum":true,"portland.museum":true,"portlligat.museum":true,"posts-and-telecommunications.museum":true,"preservation.museum":true,"presidio.museum":true,"press.museum":true,"project.museum":true,"public.museum":true,"pubol.museum":true,"quebec.museum":true,"railroad.museum":true,"railway.museum":true,"research.museum":true,"resistance.museum":true,"riodejaneiro.museum":true,"rochester.museum":true,"rockart.museum":true,"roma.museum":true,"russia.museum":true,"saintlouis.museum":true,"salem.museum":true,"salvadordali.museum":true,"salzburg.museum":true,"sandiego.museum":true,"sanfrancisco.museum":true,"santabarbara.museum":true,"santacruz.museum":true,"santafe.museum":true,"saskatchewan.museum":true,"satx.museum":true,"savannahga.museum":true,"schlesisches.museum":true,"schoenbrunn.museum":true,"schokoladen.museum":true,"school.museum":true,"schweiz.museum":true,"science.museum":true,"scienceandhistory.museum":true,"scienceandindustry.museum":true,"sciencecenter.museum":true,"sciencecenters.museum":true,"science-fiction.museum":true,"sciencehistory.museum":true,"sciences.museum":true,"sciencesnaturelles.museum":true,"scotland.museum":true,"seaport.museum":true,"settlement.museum":true,"settlers.museum":true,"shell.museum":true,"sherbrooke.museum":true,"sibenik.museum":true,"silk.museum":true,"ski.museum":true,"skole.museum":true,"society.museum":true,"sologne.museum":true,"soundandvision.museum":true,"southcarolina.museum":true,"southwest.museum":true,"space.museum":true,"spy.museum":true,"square.museum":true,"stadt.museum":true,"stalbans.museum":true,"starnberg.museum":true,"state.museum":true,"stateofdelaware.museum":true,"station.museum":true,"steam.museum":true,"steiermark.museum":true,"stjohn.museum":true,"stockholm.museum":true,"stpetersburg.museum":true,"stuttgart.museum":true,"suisse.museum":true,"surgeonshall.museum":true,"surrey.museum":true,"svizzera.museum":true,"sweden.museum":true,"sydney.museum":true,"tank.museum":true,"tcm.museum":true,"technology.museum":true,"telekommunikation.museum":true,"television.museum":true,"texas.museum":true,"textile.museum":true,"theater.museum":true,"time.museum":true,"timekeeping.museum":true,"topology.museum":true,"torino.museum":true,"touch.museum":true,"town.museum":true,"transport.museum":true,"tree.museum":true,"trolley.museum":true,"trust.museum":true,"trustee.museum":true,"uhren.museum":true,"ulm.museum":true,"undersea.museum":true,"university.museum":true,"usa.museum":true,"usantiques.museum":true,"usarts.museum":true,"uscountryestate.museum":true,"usculture.museum":true,"usdecorativearts.museum":true,"usgarden.museum":true,"ushistory.museum":true,"ushuaia.museum":true,"uslivinghistory.museum":true,"utah.museum":true,"uvic.museum":true,"valley.museum":true,"vantaa.museum":true,"versailles.museum":true,"viking.museum":true,"village.museum":true,"virginia.museum":true,"virtual.museum":true,"virtuel.museum":true,"vlaanderen.museum":true,"volkenkunde.museum":true,"wales.museum":true,"wallonie.museum":true,"war.museum":true,"washingtondc.museum":true,"watchandclock.museum":true,"watch-and-clock.museum":true,"western.museum":true,"westfalen.museum":true,"whaling.museum":true,"wildlife.museum":true,"williamsburg.museum":true,"windmill.museum":true,"workshop.museum":true,"york.museum":true,"yorkshire.museum":true,"yosemite.museum":true,"youth.museum":true,"zoological.museum":true,"zoology.museum":true,"xn--9dbhblg6di.museum":true,"xn--h1aegh.museum":true,"mv":true,"aero.mv":true,"biz.mv":true,"com.mv":true,"coop.mv":true,"edu.mv":true,"gov.mv":true,"info.mv":true,"int.mv":true,"mil.mv":true,"museum.mv":true,"name.mv":true,"net.mv":true,"org.mv":true,"pro.mv":true,"mw":true,"ac.mw":true,"biz.mw":true,"co.mw":true,"com.mw":true,"coop.mw":true,"edu.mw":true,"gov.mw":true,"int.mw":true,"museum.mw":true,"net.mw":true,"org.mw":true,"mx":true,"com.mx":true,"org.mx":true,"gob.mx":true,"edu.mx":true,"net.mx":true,"my":true,"com.my":true,"net.my":true,"org.my":true,"gov.my":true,"edu.my":true,"mil.my":true,"name.my":true,"*.mz":true,"teledata.mz":false,"na":true,"info.na":true,"pro.na":true,"name.na":true,"school.na":true,"or.na":true,"dr.na":true,"us.na":true,"mx.na":true,"ca.na":true,"in.na":true,"cc.na":true,"tv.na":true,"ws.na":true,"mobi.na":true,"co.na":true,"com.na":true,"org.na":true,"name":true,"nc":true,"asso.nc":true,"ne":true,"net":true,"nf":true,"com.nf":true,"net.nf":true,"per.nf":true,"rec.nf":true,"web.nf":true,"arts.nf":true,"firm.nf":true,"info.nf":true,"other.nf":true,"store.nf":true,"ng":true,"com.ng":true,"edu.ng":true,"name.ng":true,"net.ng":true,"org.ng":true,"sch.ng":true,"gov.ng":true,"mil.ng":true,"mobi.ng":true,"*.ni":true,"nl":true,"bv.nl":true,"no":true,"fhs.no":true,"vgs.no":true,"fylkesbibl.no":true,"folkebibl.no":true,"museum.no":true,"idrett.no":true,"priv.no":true,"mil.no":true,"stat.no":true,"dep.no":true,"kommune.no":true,"herad.no":true,"aa.no":true,"ah.no":true,"bu.no":true,"fm.no":true,"hl.no":true,"hm.no":true,"jan-mayen.no":true,"mr.no":true,"nl.no":true,"nt.no":true,"of.no":true,"ol.no":true,"oslo.no":true,"rl.no":true,"sf.no":true,"st.no":true,"svalbard.no":true,"tm.no":true,"tr.no":true,"va.no":true,"vf.no":true,"gs.aa.no":true,"gs.ah.no":true,"gs.bu.no":true,"gs.fm.no":true,"gs.hl.no":true,"gs.hm.no":true,"gs.jan-mayen.no":true,"gs.mr.no":true,"gs.nl.no":true,"gs.nt.no":true,"gs.of.no":true,"gs.ol.no":true,"gs.oslo.no":true,"gs.rl.no":true,"gs.sf.no":true,"gs.st.no":true,"gs.svalbard.no":true,"gs.tm.no":true,"gs.tr.no":true,"gs.va.no":true,"gs.vf.no":true,"akrehamn.no":true,"xn--krehamn-dxa.no":true,"algard.no":true,"xn--lgrd-poac.no":true,"arna.no":true,"brumunddal.no":true,"bryne.no":true,"bronnoysund.no":true,"xn--brnnysund-m8ac.no":true,"drobak.no":true,"xn--drbak-wua.no":true,"egersund.no":true,"fetsund.no":true,"floro.no":true,"xn--flor-jra.no":true,"fredrikstad.no":true,"hokksund.no":true,"honefoss.no":true,"xn--hnefoss-q1a.no":true,"jessheim.no":true,"jorpeland.no":true,"xn--jrpeland-54a.no":true,"kirkenes.no":true,"kopervik.no":true,"krokstadelva.no":true,"langevag.no":true,"xn--langevg-jxa.no":true,"leirvik.no":true,"mjondalen.no":true,"xn--mjndalen-64a.no":true,"mo-i-rana.no":true,"mosjoen.no":true,"xn--mosjen-eya.no":true,"nesoddtangen.no":true,"orkanger.no":true,"osoyro.no":true,"xn--osyro-wua.no":true,"raholt.no":true,"xn--rholt-mra.no":true,"sandnessjoen.no":true,"xn--sandnessjen-ogb.no":true,"skedsmokorset.no":true,"slattum.no":true,"spjelkavik.no":true,"stathelle.no":true,"stavern.no":true,"stjordalshalsen.no":true,"xn--stjrdalshalsen-sqb.no":true,"tananger.no":true,"tranby.no":true,"vossevangen.no":true,"afjord.no":true,"xn--fjord-lra.no":true,"agdenes.no":true,"al.no":true,"xn--l-1fa.no":true,"alesund.no":true,"xn--lesund-hua.no":true,"alstahaug.no":true,"alta.no":true,"xn--lt-liac.no":true,"alaheadju.no":true,"xn--laheadju-7ya.no":true,"alvdal.no":true,"amli.no":true,"xn--mli-tla.no":true,"amot.no":true,"xn--mot-tla.no":true,"andebu.no":true,"andoy.no":true,"xn--andy-ira.no":true,"andasuolo.no":true,"ardal.no":true,"xn--rdal-poa.no":true,"aremark.no":true,"arendal.no":true,"xn--s-1fa.no":true,"aseral.no":true,"xn--seral-lra.no":true,"asker.no":true,"askim.no":true,"askvoll.no":true,"askoy.no":true,"xn--asky-ira.no":true,"asnes.no":true,"xn--snes-poa.no":true,"audnedaln.no":true,"aukra.no":true,"aure.no":true,"aurland.no":true,"aurskog-holand.no":true,"xn--aurskog-hland-jnb.no":true,"austevoll.no":true,"austrheim.no":true,"averoy.no":true,"xn--avery-yua.no":true,"balestrand.no":true,"ballangen.no":true,"balat.no":true,"xn--blt-elab.no":true,"balsfjord.no":true,"bahccavuotna.no":true,"xn--bhccavuotna-k7a.no":true,"bamble.no":true,"bardu.no":true,"beardu.no":true,"beiarn.no":true,"bajddar.no":true,"xn--bjddar-pta.no":true,"baidar.no":true,"xn--bidr-5nac.no":true,"berg.no":true,"bergen.no":true,"berlevag.no":true,"xn--berlevg-jxa.no":true,"bearalvahki.no":true,"xn--bearalvhki-y4a.no":true,"bindal.no":true,"birkenes.no":true,"bjarkoy.no":true,"xn--bjarky-fya.no":true,"bjerkreim.no":true,"bjugn.no":true,"bodo.no":true,"xn--bod-2na.no":true,"badaddja.no":true,"xn--bdddj-mrabd.no":true,"budejju.no":true,"bokn.no":true,"bremanger.no":true,"bronnoy.no":true,"xn--brnny-wuac.no":true,"bygland.no":true,"bykle.no":true,"barum.no":true,"xn--brum-voa.no":true,"bo.telemark.no":true,"xn--b-5ga.telemark.no":true,"bo.nordland.no":true,"xn--b-5ga.nordland.no":true,"bievat.no":true,"xn--bievt-0qa.no":true,"bomlo.no":true,"xn--bmlo-gra.no":true,"batsfjord.no":true,"xn--btsfjord-9za.no":true,"bahcavuotna.no":true,"xn--bhcavuotna-s4a.no":true,"dovre.no":true,"drammen.no":true,"drangedal.no":true,"dyroy.no":true,"xn--dyry-ira.no":true,"donna.no":true,"xn--dnna-gra.no":true,"eid.no":true,"eidfjord.no":true,"eidsberg.no":true,"eidskog.no":true,"eidsvoll.no":true,"eigersund.no":true,"elverum.no":true,"enebakk.no":true,"engerdal.no":true,"etne.no":true,"etnedal.no":true,"evenes.no":true,"evenassi.no":true,"xn--eveni-0qa01ga.no":true,"evje-og-hornnes.no":true,"farsund.no":true,"fauske.no":true,"fuossko.no":true,"fuoisku.no":true,"fedje.no":true,"fet.no":true,"finnoy.no":true,"xn--finny-yua.no":true,"fitjar.no":true,"fjaler.no":true,"fjell.no":true,"flakstad.no":true,"flatanger.no":true,"flekkefjord.no":true,"flesberg.no":true,"flora.no":true,"fla.no":true,"xn--fl-zia.no":true,"folldal.no":true,"forsand.no":true,"fosnes.no":true,"frei.no":true,"frogn.no":true,"froland.no":true,"frosta.no":true,"frana.no":true,"xn--frna-woa.no":true,"froya.no":true,"xn--frya-hra.no":true,"fusa.no":true,"fyresdal.no":true,"forde.no":true,"xn--frde-gra.no":true,"gamvik.no":true,"gangaviika.no":true,"xn--ggaviika-8ya47h.no":true,"gaular.no":true,"gausdal.no":true,"gildeskal.no":true,"xn--gildeskl-g0a.no":true,"giske.no":true,"gjemnes.no":true,"gjerdrum.no":true,"gjerstad.no":true,"gjesdal.no":true,"gjovik.no":true,"xn--gjvik-wua.no":true,"gloppen.no":true,"gol.no":true,"gran.no":true,"grane.no":true,"granvin.no":true,"gratangen.no":true,"grimstad.no":true,"grong.no":true,"kraanghke.no":true,"xn--kranghke-b0a.no":true,"grue.no":true,"gulen.no":true,"hadsel.no":true,"halden.no":true,"halsa.no":true,"hamar.no":true,"hamaroy.no":true,"habmer.no":true,"xn--hbmer-xqa.no":true,"hapmir.no":true,"xn--hpmir-xqa.no":true,"hammerfest.no":true,"hammarfeasta.no":true,"xn--hmmrfeasta-s4ac.no":true,"haram.no":true,"hareid.no":true,"harstad.no":true,"hasvik.no":true,"aknoluokta.no":true,"xn--koluokta-7ya57h.no":true,"hattfjelldal.no":true,"aarborte.no":true,"haugesund.no":true,"hemne.no":true,"hemnes.no":true,"hemsedal.no":true,"heroy.more-og-romsdal.no":true,"xn--hery-ira.xn--mre-og-romsdal-qqb.no":true,"heroy.nordland.no":true,"xn--hery-ira.nordland.no":true,"hitra.no":true,"hjartdal.no":true,"hjelmeland.no":true,"hobol.no":true,"xn--hobl-ira.no":true,"hof.no":true,"hol.no":true,"hole.no":true,"holmestrand.no":true,"holtalen.no":true,"xn--holtlen-hxa.no":true,"hornindal.no":true,"horten.no":true,"hurdal.no":true,"hurum.no":true,"hvaler.no":true,"hyllestad.no":true,"hagebostad.no":true,"xn--hgebostad-g3a.no":true,"hoyanger.no":true,"xn--hyanger-q1a.no":true,"hoylandet.no":true,"xn--hylandet-54a.no":true,"ha.no":true,"xn--h-2fa.no":true,"ibestad.no":true,"inderoy.no":true,"xn--indery-fya.no":true,"iveland.no":true,"jevnaker.no":true,"jondal.no":true,"jolster.no":true,"xn--jlster-bya.no":true,"karasjok.no":true,"karasjohka.no":true,"xn--krjohka-hwab49j.no":true,"karlsoy.no":true,"galsa.no":true,"xn--gls-elac.no":true,"karmoy.no":true,"xn--karmy-yua.no":true,"kautokeino.no":true,"guovdageaidnu.no":true,"klepp.no":true,"klabu.no":true,"xn--klbu-woa.no":true,"kongsberg.no":true,"kongsvinger.no":true,"kragero.no":true,"xn--krager-gya.no":true,"kristiansand.no":true,"kristiansund.no":true,"krodsherad.no":true,"xn--krdsherad-m8a.no":true,"kvalsund.no":true,"rahkkeravju.no":true,"xn--rhkkervju-01af.no":true,"kvam.no":true,"kvinesdal.no":true,"kvinnherad.no":true,"kviteseid.no":true,"kvitsoy.no":true,"xn--kvitsy-fya.no":true,"kvafjord.no":true,"xn--kvfjord-nxa.no":true,"giehtavuoatna.no":true,"kvanangen.no":true,"xn--kvnangen-k0a.no":true,"navuotna.no":true,"xn--nvuotna-hwa.no":true,"kafjord.no":true,"xn--kfjord-iua.no":true,"gaivuotna.no":true,"xn--givuotna-8ya.no":true,"larvik.no":true,"lavangen.no":true,"lavagis.no":true,"loabat.no":true,"xn--loabt-0qa.no":true,"lebesby.no":true,"davvesiida.no":true,"leikanger.no":true,"leirfjord.no":true,"leka.no":true,"leksvik.no":true,"lenvik.no":true,"leangaviika.no":true,"xn--leagaviika-52b.no":true,"lesja.no":true,"levanger.no":true,"lier.no":true,"lierne.no":true,"lillehammer.no":true,"lillesand.no":true,"lindesnes.no":true,"lindas.no":true,"xn--linds-pra.no":true,"lom.no":true,"loppa.no":true,"lahppi.no":true,"xn--lhppi-xqa.no":true,"lund.no":true,"lunner.no":true,"luroy.no":true,"xn--lury-ira.no":true,"luster.no":true,"lyngdal.no":true,"lyngen.no":true,"ivgu.no":true,"lardal.no":true,"lerdal.no":true,"xn--lrdal-sra.no":true,"lodingen.no":true,"xn--ldingen-q1a.no":true,"lorenskog.no":true,"xn--lrenskog-54a.no":true,"loten.no":true,"xn--lten-gra.no":true,"malvik.no":true,"masoy.no":true,"xn--msy-ula0h.no":true,"muosat.no":true,"xn--muost-0qa.no":true,"mandal.no":true,"marker.no":true,"marnardal.no":true,"masfjorden.no":true,"meland.no":true,"meldal.no":true,"melhus.no":true,"meloy.no":true,"xn--mely-ira.no":true,"meraker.no":true,"xn--merker-kua.no":true,"moareke.no":true,"xn--moreke-jua.no":true,"midsund.no":true,"midtre-gauldal.no":true,"modalen.no":true,"modum.no":true,"molde.no":true,"moskenes.no":true,"moss.no":true,"mosvik.no":true,"malselv.no":true,"xn--mlselv-iua.no":true,"malatvuopmi.no":true,"xn--mlatvuopmi-s4a.no":true,"namdalseid.no":true,"aejrie.no":true,"namsos.no":true,"namsskogan.no":true,"naamesjevuemie.no":true,"xn--nmesjevuemie-tcba.no":true,"laakesvuemie.no":true,"nannestad.no":true,"narvik.no":true,"narviika.no":true,"naustdal.no":true,"nedre-eiker.no":true,"nes.akershus.no":true,"nes.buskerud.no":true,"nesna.no":true,"nesodden.no":true,"nesseby.no":true,"unjarga.no":true,"xn--unjrga-rta.no":true,"nesset.no":true,"nissedal.no":true,"nittedal.no":true,"nord-aurdal.no":true,"nord-fron.no":true,"nord-odal.no":true,"norddal.no":true,"nordkapp.no":true,"davvenjarga.no":true,"xn--davvenjrga-y4a.no":true,"nordre-land.no":true,"nordreisa.no":true,"raisa.no":true,"xn--risa-5na.no":true,"nore-og-uvdal.no":true,"notodden.no":true,"naroy.no":true,"xn--nry-yla5g.no":true,"notteroy.no":true,"xn--nttery-byae.no":true,"odda.no":true,"oksnes.no":true,"xn--ksnes-uua.no":true,"oppdal.no":true,"oppegard.no":true,"xn--oppegrd-ixa.no":true,"orkdal.no":true,"orland.no":true,"xn--rland-uua.no":true,"orskog.no":true,"xn--rskog-uua.no":true,"orsta.no":true,"xn--rsta-fra.no":true,"os.hedmark.no":true,"os.hordaland.no":true,"osen.no":true,"osteroy.no":true,"xn--ostery-fya.no":true,"ostre-toten.no":true,"xn--stre-toten-zcb.no":true,"overhalla.no":true,"ovre-eiker.no":true,"xn--vre-eiker-k8a.no":true,"oyer.no":true,"xn--yer-zna.no":true,"oygarden.no":true,"xn--ygarden-p1a.no":true,"oystre-slidre.no":true,"xn--ystre-slidre-ujb.no":true,"porsanger.no":true,"porsangu.no":true,"xn--porsgu-sta26f.no":true,"porsgrunn.no":true,"radoy.no":true,"xn--rady-ira.no":true,"rakkestad.no":true,"rana.no":true,"ruovat.no":true,"randaberg.no":true,"rauma.no":true,"rendalen.no":true,"rennebu.no":true,"rennesoy.no":true,"xn--rennesy-v1a.no":true,"rindal.no":true,"ringebu.no":true,"ringerike.no":true,"ringsaker.no":true,"rissa.no":true,"risor.no":true,"xn--risr-ira.no":true,"roan.no":true,"rollag.no":true,"rygge.no":true,"ralingen.no":true,"xn--rlingen-mxa.no":true,"rodoy.no":true,"xn--rdy-0nab.no":true,"romskog.no":true,"xn--rmskog-bya.no":true,"roros.no":true,"xn--rros-gra.no":true,"rost.no":true,"xn--rst-0na.no":true,"royken.no":true,"xn--ryken-vua.no":true,"royrvik.no":true,"xn--ryrvik-bya.no":true,"rade.no":true,"xn--rde-ula.no":true,"salangen.no":true,"siellak.no":true,"saltdal.no":true,"salat.no":true,"xn--slt-elab.no":true,"xn--slat-5na.no":true,"samnanger.no":true,"sande.more-og-romsdal.no":true,"sande.xn--mre-og-romsdal-qqb.no":true,"sande.vestfold.no":true,"sandefjord.no":true,"sandnes.no":true,"sandoy.no":true,"xn--sandy-yua.no":true,"sarpsborg.no":true,"sauda.no":true,"sauherad.no":true,"sel.no":true,"selbu.no":true,"selje.no":true,"seljord.no":true,"sigdal.no":true,"siljan.no":true,"sirdal.no":true,"skaun.no":true,"skedsmo.no":true,"ski.no":true,"skien.no":true,"skiptvet.no":true,"skjervoy.no":true,"xn--skjervy-v1a.no":true,"skierva.no":true,"xn--skierv-uta.no":true,"skjak.no":true,"xn--skjk-soa.no":true,"skodje.no":true,"skanland.no":true,"xn--sknland-fxa.no":true,"skanit.no":true,"xn--sknit-yqa.no":true,"smola.no":true,"xn--smla-hra.no":true,"snillfjord.no":true,"snasa.no":true,"xn--snsa-roa.no":true,"snoasa.no":true,"snaase.no":true,"xn--snase-nra.no":true,"sogndal.no":true,"sokndal.no":true,"sola.no":true,"solund.no":true,"songdalen.no":true,"sortland.no":true,"spydeberg.no":true,"stange.no":true,"stavanger.no":true,"steigen.no":true,"steinkjer.no":true,"stjordal.no":true,"xn--stjrdal-s1a.no":true,"stokke.no":true,"stor-elvdal.no":true,"stord.no":true,"stordal.no":true,"storfjord.no":true,"omasvuotna.no":true,"strand.no":true,"stranda.no":true,"stryn.no":true,"sula.no":true,"suldal.no":true,"sund.no":true,"sunndal.no":true,"surnadal.no":true,"sveio.no":true,"svelvik.no":true,"sykkylven.no":true,"sogne.no":true,"xn--sgne-gra.no":true,"somna.no":true,"xn--smna-gra.no":true,"sondre-land.no":true,"xn--sndre-land-0cb.no":true,"sor-aurdal.no":true,"xn--sr-aurdal-l8a.no":true,"sor-fron.no":true,"xn--sr-fron-q1a.no":true,"sor-odal.no":true,"xn--sr-odal-q1a.no":true,"sor-varanger.no":true,"xn--sr-varanger-ggb.no":true,"matta-varjjat.no":true,"xn--mtta-vrjjat-k7af.no":true,"sorfold.no":true,"xn--srfold-bya.no":true,"sorreisa.no":true,"xn--srreisa-q1a.no":true,"sorum.no":true,"xn--srum-gra.no":true,"tana.no":true,"deatnu.no":true,"time.no":true,"tingvoll.no":true,"tinn.no":true,"tjeldsund.no":true,"dielddanuorri.no":true,"tjome.no":true,"xn--tjme-hra.no":true,"tokke.no":true,"tolga.no":true,"torsken.no":true,"tranoy.no":true,"xn--trany-yua.no":true,"tromso.no":true,"xn--troms-zua.no":true,"tromsa.no":true,"romsa.no":true,"trondheim.no":true,"troandin.no":true,"trysil.no":true,"trana.no":true,"xn--trna-woa.no":true,"trogstad.no":true,"xn--trgstad-r1a.no":true,"tvedestrand.no":true,"tydal.no":true,"tynset.no":true,"tysfjord.no":true,"divtasvuodna.no":true,"divttasvuotna.no":true,"tysnes.no":true,"tysvar.no":true,"xn--tysvr-vra.no":true,"tonsberg.no":true,"xn--tnsberg-q1a.no":true,"ullensaker.no":true,"ullensvang.no":true,"ulvik.no":true,"utsira.no":true,"vadso.no":true,"xn--vads-jra.no":true,"cahcesuolo.no":true,"xn--hcesuolo-7ya35b.no":true,"vaksdal.no":true,"valle.no":true,"vang.no":true,"vanylven.no":true,"vardo.no":true,"xn--vard-jra.no":true,"varggat.no":true,"xn--vrggt-xqad.no":true,"vefsn.no":true,"vaapste.no":true,"vega.no":true,"vegarshei.no":true,"xn--vegrshei-c0a.no":true,"vennesla.no":true,"verdal.no":true,"verran.no":true,"vestby.no":true,"vestnes.no":true,"vestre-slidre.no":true,"vestre-toten.no":true,"vestvagoy.no":true,"xn--vestvgy-ixa6o.no":true,"vevelstad.no":true,"vik.no":true,"vikna.no":true,"vindafjord.no":true,"volda.no":true,"voss.no":true,"varoy.no":true,"xn--vry-yla5g.no":true,"vagan.no":true,"xn--vgan-qoa.no":true,"voagat.no":true,"vagsoy.no":true,"xn--vgsy-qoa0j.no":true,"vaga.no":true,"xn--vg-yiab.no":true,"valer.ostfold.no":true,"xn--vler-qoa.xn--stfold-9xa.no":true,"valer.hedmark.no":true,"xn--vler-qoa.hedmark.no":true,"*.np":true,"nr":true,"biz.nr":true,"info.nr":true,"gov.nr":true,"edu.nr":true,"org.nr":true,"net.nr":true,"com.nr":true,"nu":true,"nz":true,"ac.nz":true,"co.nz":true,"cri.nz":true,"geek.nz":true,"gen.nz":true,"govt.nz":true,"health.nz":true,"iwi.nz":true,"kiwi.nz":true,"maori.nz":true,"mil.nz":true,"xn--mori-qsa.nz":true,"net.nz":true,"org.nz":true,"parliament.nz":true,"school.nz":true,"om":true,"co.om":true,"com.om":true,"edu.om":true,"gov.om":true,"med.om":true,"museum.om":true,"net.om":true,"org.om":true,"pro.om":true,"org":true,"pa":true,"ac.pa":true,"gob.pa":true,"com.pa":true,"org.pa":true,"sld.pa":true,"edu.pa":true,"net.pa":true,"ing.pa":true,"abo.pa":true,"med.pa":true,"nom.pa":true,"pe":true,"edu.pe":true,"gob.pe":true,"nom.pe":true,"mil.pe":true,"org.pe":true,"com.pe":true,"net.pe":true,"pf":true,"com.pf":true,"org.pf":true,"edu.pf":true,"*.pg":true,"ph":true,"com.ph":true,"net.ph":true,"org.ph":true,"gov.ph":true,"edu.ph":true,"ngo.ph":true,"mil.ph":true,"i.ph":true,"pk":true,"com.pk":true,"net.pk":true,"edu.pk":true,"org.pk":true,"fam.pk":true,"biz.pk":true,"web.pk":true,"gov.pk":true,"gob.pk":true,"gok.pk":true,"gon.pk":true,"gop.pk":true,"gos.pk":true,"info.pk":true,"pl":true,"com.pl":true,"net.pl":true,"org.pl":true,"aid.pl":true,"agro.pl":true,"atm.pl":true,"auto.pl":true,"biz.pl":true,"edu.pl":true,"gmina.pl":true,"gsm.pl":true,"info.pl":true,"mail.pl":true,"miasta.pl":true,"media.pl":true,"mil.pl":true,"nieruchomosci.pl":true,"nom.pl":true,"pc.pl":true,"powiat.pl":true,"priv.pl":true,"realestate.pl":true,"rel.pl":true,"sex.pl":true,"shop.pl":true,"sklep.pl":true,"sos.pl":true,"szkola.pl":true,"targi.pl":true,"tm.pl":true,"tourism.pl":true,"travel.pl":true,"turystyka.pl":true,"gov.pl":true,"ap.gov.pl":true,"ic.gov.pl":true,"is.gov.pl":true,"us.gov.pl":true,"kmpsp.gov.pl":true,"kppsp.gov.pl":true,"kwpsp.gov.pl":true,"psp.gov.pl":true,"wskr.gov.pl":true,"kwp.gov.pl":true,"mw.gov.pl":true,"ug.gov.pl":true,"um.gov.pl":true,"umig.gov.pl":true,"ugim.gov.pl":true,"upow.gov.pl":true,"uw.gov.pl":true,"starostwo.gov.pl":true,"pa.gov.pl":true,"po.gov.pl":true,"psse.gov.pl":true,"pup.gov.pl":true,"rzgw.gov.pl":true,"sa.gov.pl":true,"so.gov.pl":true,"sr.gov.pl":true,"wsa.gov.pl":true,"sko.gov.pl":true,"uzs.gov.pl":true,"wiih.gov.pl":true,"winb.gov.pl":true,"pinb.gov.pl":true,"wios.gov.pl":true,"witd.gov.pl":true,"wzmiuw.gov.pl":true,"piw.gov.pl":true,"wiw.gov.pl":true,"griw.gov.pl":true,"wif.gov.pl":true,"oum.gov.pl":true,"sdn.gov.pl":true,"zp.gov.pl":true,"uppo.gov.pl":true,"mup.gov.pl":true,"wuoz.gov.pl":true,"konsulat.gov.pl":true,"oirm.gov.pl":true,"augustow.pl":true,"babia-gora.pl":true,"bedzin.pl":true,"beskidy.pl":true,"bialowieza.pl":true,"bialystok.pl":true,"bielawa.pl":true,"bieszczady.pl":true,"boleslawiec.pl":true,"bydgoszcz.pl":true,"bytom.pl":true,"cieszyn.pl":true,"czeladz.pl":true,"czest.pl":true,"dlugoleka.pl":true,"elblag.pl":true,"elk.pl":true,"glogow.pl":true,"gniezno.pl":true,"gorlice.pl":true,"grajewo.pl":true,"ilawa.pl":true,"jaworzno.pl":true,"jelenia-gora.pl":true,"jgora.pl":true,"kalisz.pl":true,"kazimierz-dolny.pl":true,"karpacz.pl":true,"kartuzy.pl":true,"kaszuby.pl":true,"katowice.pl":true,"kepno.pl":true,"ketrzyn.pl":true,"klodzko.pl":true,"kobierzyce.pl":true,"kolobrzeg.pl":true,"konin.pl":true,"konskowola.pl":true,"kutno.pl":true,"lapy.pl":true,"lebork.pl":true,"legnica.pl":true,"lezajsk.pl":true,"limanowa.pl":true,"lomza.pl":true,"lowicz.pl":true,"lubin.pl":true,"lukow.pl":true,"malbork.pl":true,"malopolska.pl":true,"mazowsze.pl":true,"mazury.pl":true,"mielec.pl":true,"mielno.pl":true,"mragowo.pl":true,"naklo.pl":true,"nowaruda.pl":true,"nysa.pl":true,"olawa.pl":true,"olecko.pl":true,"olkusz.pl":true,"olsztyn.pl":true,"opoczno.pl":true,"opole.pl":true,"ostroda.pl":true,"ostroleka.pl":true,"ostrowiec.pl":true,"ostrowwlkp.pl":true,"pila.pl":true,"pisz.pl":true,"podhale.pl":true,"podlasie.pl":true,"polkowice.pl":true,"pomorze.pl":true,"pomorskie.pl":true,"prochowice.pl":true,"pruszkow.pl":true,"przeworsk.pl":true,"pulawy.pl":true,"radom.pl":true,"rawa-maz.pl":true,"rybnik.pl":true,"rzeszow.pl":true,"sanok.pl":true,"sejny.pl":true,"slask.pl":true,"slupsk.pl":true,"sosnowiec.pl":true,"stalowa-wola.pl":true,"skoczow.pl":true,"starachowice.pl":true,"stargard.pl":true,"suwalki.pl":true,"swidnica.pl":true,"swiebodzin.pl":true,"swinoujscie.pl":true,"szczecin.pl":true,"szczytno.pl":true,"tarnobrzeg.pl":true,"tgory.pl":true,"turek.pl":true,"tychy.pl":true,"ustka.pl":true,"walbrzych.pl":true,"warmia.pl":true,"warszawa.pl":true,"waw.pl":true,"wegrow.pl":true,"wielun.pl":true,"wlocl.pl":true,"wloclawek.pl":true,"wodzislaw.pl":true,"wolomin.pl":true,"wroclaw.pl":true,"zachpomor.pl":true,"zagan.pl":true,"zarow.pl":true,"zgora.pl":true,"zgorzelec.pl":true,"pm":true,"pn":true,"gov.pn":true,"co.pn":true,"org.pn":true,"edu.pn":true,"net.pn":true,"post":true,"pr":true,"com.pr":true,"net.pr":true,"org.pr":true,"gov.pr":true,"edu.pr":true,"isla.pr":true,"pro.pr":true,"biz.pr":true,"info.pr":true,"name.pr":true,"est.pr":true,"prof.pr":true,"ac.pr":true,"pro":true,"aca.pro":true,"bar.pro":true,"cpa.pro":true,"jur.pro":true,"law.pro":true,"med.pro":true,"eng.pro":true,"ps":true,"edu.ps":true,"gov.ps":true,"sec.ps":true,"plo.ps":true,"com.ps":true,"org.ps":true,"net.ps":true,"pt":true,"net.pt":true,"gov.pt":true,"org.pt":true,"edu.pt":true,"int.pt":true,"publ.pt":true,"com.pt":true,"nome.pt":true,"pw":true,"co.pw":true,"ne.pw":true,"or.pw":true,"ed.pw":true,"go.pw":true,"belau.pw":true,"py":true,"com.py":true,"coop.py":true,"edu.py":true,"gov.py":true,"mil.py":true,"net.py":true,"org.py":true,"qa":true,"com.qa":true,"edu.qa":true,"gov.qa":true,"mil.qa":true,"name.qa":true,"net.qa":true,"org.qa":true,"sch.qa":true,"re":true,"com.re":true,"asso.re":true,"nom.re":true,"ro":true,"com.ro":true,"org.ro":true,"tm.ro":true,"nt.ro":true,"nom.ro":true,"info.ro":true,"rec.ro":true,"arts.ro":true,"firm.ro":true,"store.ro":true,"www.ro":true,"rs":true,"co.rs":true,"org.rs":true,"edu.rs":true,"ac.rs":true,"gov.rs":true,"in.rs":true,"ru":true,"ac.ru":true,"com.ru":true,"edu.ru":true,"int.ru":true,"net.ru":true,"org.ru":true,"pp.ru":true,"adygeya.ru":true,"altai.ru":true,"amur.ru":true,"arkhangelsk.ru":true,"astrakhan.ru":true,"bashkiria.ru":true,"belgorod.ru":true,"bir.ru":true,"bryansk.ru":true,"buryatia.ru":true,"cbg.ru":true,"chel.ru":true,"chelyabinsk.ru":true,"chita.ru":true,"chukotka.ru":true,"chuvashia.ru":true,"dagestan.ru":true,"dudinka.ru":true,"e-burg.ru":true,"grozny.ru":true,"irkutsk.ru":true,"ivanovo.ru":true,"izhevsk.ru":true,"jar.ru":true,"joshkar-ola.ru":true,"kalmykia.ru":true,"kaluga.ru":true,"kamchatka.ru":true,"karelia.ru":true,"kazan.ru":true,"kchr.ru":true,"kemerovo.ru":true,"khabarovsk.ru":true,"khakassia.ru":true,"khv.ru":true,"kirov.ru":true,"koenig.ru":true,"komi.ru":true,"kostroma.ru":true,"krasnoyarsk.ru":true,"kuban.ru":true,"kurgan.ru":true,"kursk.ru":true,"lipetsk.ru":true,"magadan.ru":true,"mari.ru":true,"mari-el.ru":true,"marine.ru":true,"mordovia.ru":true,"msk.ru":true,"murmansk.ru":true,"nalchik.ru":true,"nnov.ru":true,"nov.ru":true,"novosibirsk.ru":true,"nsk.ru":true,"omsk.ru":true,"orenburg.ru":true,"oryol.ru":true,"palana.ru":true,"penza.ru":true,"perm.ru":true,"ptz.ru":true,"rnd.ru":true,"ryazan.ru":true,"sakhalin.ru":true,"samara.ru":true,"saratov.ru":true,"simbirsk.ru":true,"smolensk.ru":true,"spb.ru":true,"stavropol.ru":true,"stv.ru":true,"surgut.ru":true,"tambov.ru":true,"tatarstan.ru":true,"tom.ru":true,"tomsk.ru":true,"tsaritsyn.ru":true,"tsk.ru":true,"tula.ru":true,"tuva.ru":true,"tver.ru":true,"tyumen.ru":true,"udm.ru":true,"udmurtia.ru":true,"ulan-ude.ru":true,"vladikavkaz.ru":true,"vladimir.ru":true,"vladivostok.ru":true,"volgograd.ru":true,"vologda.ru":true,"voronezh.ru":true,"vrn.ru":true,"vyatka.ru":true,"yakutia.ru":true,"yamal.ru":true,"yaroslavl.ru":true,"yekaterinburg.ru":true,"yuzhno-sakhalinsk.ru":true,"amursk.ru":true,"baikal.ru":true,"cmw.ru":true,"fareast.ru":true,"jamal.ru":true,"kms.ru":true,"k-uralsk.ru":true,"kustanai.ru":true,"kuzbass.ru":true,"magnitka.ru":true,"mytis.ru":true,"nakhodka.ru":true,"nkz.ru":true,"norilsk.ru":true,"oskol.ru":true,"pyatigorsk.ru":true,"rubtsovsk.ru":true,"snz.ru":true,"syzran.ru":true,"vdonsk.ru":true,"zgrad.ru":true,"gov.ru":true,"mil.ru":true,"test.ru":true,"rw":true,"gov.rw":true,"net.rw":true,"edu.rw":true,"ac.rw":true,"com.rw":true,"co.rw":true,"int.rw":true,"mil.rw":true,"gouv.rw":true,"sa":true,"com.sa":true,"net.sa":true,"org.sa":true,"gov.sa":true,"med.sa":true,"pub.sa":true,"edu.sa":true,"sch.sa":true,"sb":true,"com.sb":true,"edu.sb":true,"gov.sb":true,"net.sb":true,"org.sb":true,"sc":true,"com.sc":true,"gov.sc":true,"net.sc":true,"org.sc":true,"edu.sc":true,"sd":true,"com.sd":true,"net.sd":true,"org.sd":true,"edu.sd":true,"med.sd":true,"tv.sd":true,"gov.sd":true,"info.sd":true,"se":true,"a.se":true,"ac.se":true,"b.se":true,"bd.se":true,"brand.se":true,"c.se":true,"d.se":true,"e.se":true,"f.se":true,"fh.se":true,"fhsk.se":true,"fhv.se":true,"g.se":true,"h.se":true,"i.se":true,"k.se":true,"komforb.se":true,"kommunalforbund.se":true,"komvux.se":true,"l.se":true,"lanbib.se":true,"m.se":true,"n.se":true,"naturbruksgymn.se":true,"o.se":true,"org.se":true,"p.se":true,"parti.se":true,"pp.se":true,"press.se":true,"r.se":true,"s.se":true,"t.se":true,"tm.se":true,"u.se":true,"w.se":true,"x.se":true,"y.se":true,"z.se":true,"sg":true,"com.sg":true,"net.sg":true,"org.sg":true,"gov.sg":true,"edu.sg":true,"per.sg":true,"sh":true,"com.sh":true,"net.sh":true,"gov.sh":true,"org.sh":true,"mil.sh":true,"si":true,"sj":true,"sk":true,"sl":true,"com.sl":true,"net.sl":true,"edu.sl":true,"gov.sl":true,"org.sl":true,"sm":true,"sn":true,"art.sn":true,"com.sn":true,"edu.sn":true,"gouv.sn":true,"org.sn":true,"perso.sn":true,"univ.sn":true,"so":true,"com.so":true,"net.so":true,"org.so":true,"sr":true,"st":true,"co.st":true,"com.st":true,"consulado.st":true,"edu.st":true,"embaixada.st":true,"gov.st":true,"mil.st":true,"net.st":true,"org.st":true,"principe.st":true,"saotome.st":true,"store.st":true,"su":true,"adygeya.su":true,"arkhangelsk.su":true,"balashov.su":true,"bashkiria.su":true,"bryansk.su":true,"dagestan.su":true,"grozny.su":true,"ivanovo.su":true,"kalmykia.su":true,"kaluga.su":true,"karelia.su":true,"khakassia.su":true,"krasnodar.su":true,"kurgan.su":true,"lenug.su":true,"mordovia.su":true,"msk.su":true,"murmansk.su":true,"nalchik.su":true,"nov.su":true,"obninsk.su":true,"penza.su":true,"pokrovsk.su":true,"sochi.su":true,"spb.su":true,"togliatti.su":true,"troitsk.su":true,"tula.su":true,"tuva.su":true,"vladikavkaz.su":true,"vladimir.su":true,"vologda.su":true,"sv":true,"com.sv":true,"edu.sv":true,"gob.sv":true,"org.sv":true,"red.sv":true,"sx":true,"gov.sx":true,"sy":true,"edu.sy":true,"gov.sy":true,"net.sy":true,"mil.sy":true,"com.sy":true,"org.sy":true,"sz":true,"co.sz":true,"ac.sz":true,"org.sz":true,"tc":true,"td":true,"tel":true,"tf":true,"tg":true,"th":true,"ac.th":true,"co.th":true,"go.th":true,"in.th":true,"mi.th":true,"net.th":true,"or.th":true,"tj":true,"ac.tj":true,"biz.tj":true,"co.tj":true,"com.tj":true,"edu.tj":true,"go.tj":true,"gov.tj":true,"int.tj":true,"mil.tj":true,"name.tj":true,"net.tj":true,"nic.tj":true,"org.tj":true,"test.tj":true,"web.tj":true,"tk":true,"tl":true,"gov.tl":true,"tm":true,"com.tm":true,"co.tm":true,"org.tm":true,"net.tm":true,"nom.tm":true,"gov.tm":true,"mil.tm":true,"edu.tm":true,"tn":true,"com.tn":true,"ens.tn":true,"fin.tn":true,"gov.tn":true,"ind.tn":true,"intl.tn":true,"nat.tn":true,"net.tn":true,"org.tn":true,"info.tn":true,"perso.tn":true,"tourism.tn":true,"edunet.tn":true,"rnrt.tn":true,"rns.tn":true,"rnu.tn":true,"mincom.tn":true,"agrinet.tn":true,"defense.tn":true,"turen.tn":true,"to":true,"com.to":true,"gov.to":true,"net.to":true,"org.to":true,"edu.to":true,"mil.to":true,"tp":true,"tr":true,"com.tr":true,"info.tr":true,"biz.tr":true,"net.tr":true,"org.tr":true,"web.tr":true,"gen.tr":true,"tv.tr":true,"av.tr":true,"dr.tr":true,"bbs.tr":true,"name.tr":true,"tel.tr":true,"gov.tr":true,"bel.tr":true,"pol.tr":true,"mil.tr":true,"k12.tr":true,"edu.tr":true,"kep.tr":true,"nc.tr":true,"gov.nc.tr":true,"travel":true,"tt":true,"co.tt":true,"com.tt":true,"org.tt":true,"net.tt":true,"biz.tt":true,"info.tt":true,"pro.tt":true,"int.tt":true,"coop.tt":true,"jobs.tt":true,"mobi.tt":true,"travel.tt":true,"museum.tt":true,"aero.tt":true,"name.tt":true,"gov.tt":true,"edu.tt":true,"tv":true,"tw":true,"edu.tw":true,"gov.tw":true,"mil.tw":true,"com.tw":true,"net.tw":true,"org.tw":true,"idv.tw":true,"game.tw":true,"ebiz.tw":true,"club.tw":true,"xn--zf0ao64a.tw":true,"xn--uc0atv.tw":true,"xn--czrw28b.tw":true,"tz":true,"ac.tz":true,"co.tz":true,"go.tz":true,"hotel.tz":true,"info.tz":true,"me.tz":true,"mil.tz":true,"mobi.tz":true,"ne.tz":true,"or.tz":true,"sc.tz":true,"tv.tz":true,"ua":true,"com.ua":true,"edu.ua":true,"gov.ua":true,"in.ua":true,"net.ua":true,"org.ua":true,"cherkassy.ua":true,"cherkasy.ua":true,"chernigov.ua":true,"chernihiv.ua":true,"chernivtsi.ua":true,"chernovtsy.ua":true,"ck.ua":true,"cn.ua":true,"cr.ua":true,"crimea.ua":true,"cv.ua":true,"dn.ua":true,"dnepropetrovsk.ua":true,"dnipropetrovsk.ua":true,"dominic.ua":true,"donetsk.ua":true,"dp.ua":true,"if.ua":true,"ivano-frankivsk.ua":true,"kh.ua":true,"kharkiv.ua":true,"kharkov.ua":true,"kherson.ua":true,"khmelnitskiy.ua":true,"khmelnytskyi.ua":true,"kiev.ua":true,"kirovograd.ua":true,"km.ua":true,"kr.ua":true,"krym.ua":true,"ks.ua":true,"kv.ua":true,"kyiv.ua":true,"lg.ua":true,"lt.ua":true,"lugansk.ua":true,"lutsk.ua":true,"lv.ua":true,"lviv.ua":true,"mk.ua":true,"mykolaiv.ua":true,"nikolaev.ua":true,"od.ua":true,"odesa.ua":true,"odessa.ua":true,"pl.ua":true,"poltava.ua":true,"rivne.ua":true,"rovno.ua":true,"rv.ua":true,"sb.ua":true,"sebastopol.ua":true,"sevastopol.ua":true,"sm.ua":true,"sumy.ua":true,"te.ua":true,"ternopil.ua":true,"uz.ua":true,"uzhgorod.ua":true,"vinnica.ua":true,"vinnytsia.ua":true,"vn.ua":true,"volyn.ua":true,"yalta.ua":true,"zaporizhzhe.ua":true,"zaporizhzhia.ua":true,"zhitomir.ua":true,"zhytomyr.ua":true,"zp.ua":true,"zt.ua":true,"ug":true,"co.ug":true,"or.ug":true,"ac.ug":true,"sc.ug":true,"go.ug":true,"ne.ug":true,"com.ug":true,"org.ug":true,"uk":true,"ac.uk":true,"co.uk":true,"gov.uk":true,"ltd.uk":true,"me.uk":true,"net.uk":true,"nhs.uk":true,"org.uk":true,"plc.uk":true,"police.uk":true,"*.sch.uk":true,"us":true,"dni.us":true,"fed.us":true,"isa.us":true,"kids.us":true,"nsn.us":true,"ak.us":true,"al.us":true,"ar.us":true,"as.us":true,"az.us":true,"ca.us":true,"co.us":true,"ct.us":true,"dc.us":true,"de.us":true,"fl.us":true,"ga.us":true,"gu.us":true,"hi.us":true,"ia.us":true,"id.us":true,"il.us":true,"in.us":true,"ks.us":true,"ky.us":true,"la.us":true,"ma.us":true,"md.us":true,"me.us":true,"mi.us":true,"mn.us":true,"mo.us":true,"ms.us":true,"mt.us":true,"nc.us":true,"nd.us":true,"ne.us":true,"nh.us":true,"nj.us":true,"nm.us":true,"nv.us":true,"ny.us":true,"oh.us":true,"ok.us":true,"or.us":true,"pa.us":true,"pr.us":true,"ri.us":true,"sc.us":true,"sd.us":true,"tn.us":true,"tx.us":true,"ut.us":true,"vi.us":true,"vt.us":true,"va.us":true,"wa.us":true,"wi.us":true,"wv.us":true,"wy.us":true,"k12.ak.us":true,"k12.al.us":true,"k12.ar.us":true,"k12.as.us":true,"k12.az.us":true,"k12.ca.us":true,"k12.co.us":true,"k12.ct.us":true,"k12.dc.us":true,"k12.de.us":true,"k12.fl.us":true,"k12.ga.us":true,"k12.gu.us":true,"k12.ia.us":true,"k12.id.us":true,"k12.il.us":true,"k12.in.us":true,"k12.ks.us":true,"k12.ky.us":true,"k12.la.us":true,"k12.ma.us":true,"k12.md.us":true,"k12.me.us":true,"k12.mi.us":true,"k12.mn.us":true,"k12.mo.us":true,"k12.ms.us":true,"k12.mt.us":true,"k12.nc.us":true,"k12.ne.us":true,"k12.nh.us":true,"k12.nj.us":true,"k12.nm.us":true,"k12.nv.us":true,"k12.ny.us":true,"k12.oh.us":true,"k12.ok.us":true,"k12.or.us":true,"k12.pa.us":true,"k12.pr.us":true,"k12.ri.us":true,"k12.sc.us":true,"k12.tn.us":true,"k12.tx.us":true,"k12.ut.us":true,"k12.vi.us":true,"k12.vt.us":true,"k12.va.us":true,"k12.wa.us":true,"k12.wi.us":true,"k12.wy.us":true,"cc.ak.us":true,"cc.al.us":true,"cc.ar.us":true,"cc.as.us":true,"cc.az.us":true,"cc.ca.us":true,"cc.co.us":true,"cc.ct.us":true,"cc.dc.us":true,"cc.de.us":true,"cc.fl.us":true,"cc.ga.us":true,"cc.gu.us":true,"cc.hi.us":true,"cc.ia.us":true,"cc.id.us":true,"cc.il.us":true,"cc.in.us":true,"cc.ks.us":true,"cc.ky.us":true,"cc.la.us":true,"cc.ma.us":true,"cc.md.us":true,"cc.me.us":true,"cc.mi.us":true,"cc.mn.us":true,"cc.mo.us":true,"cc.ms.us":true,"cc.mt.us":true,"cc.nc.us":true,"cc.nd.us":true,"cc.ne.us":true,"cc.nh.us":true,"cc.nj.us":true,"cc.nm.us":true,"cc.nv.us":true,"cc.ny.us":true,"cc.oh.us":true,"cc.ok.us":true,"cc.or.us":true,"cc.pa.us":true,"cc.pr.us":true,"cc.ri.us":true,"cc.sc.us":true,"cc.sd.us":true,"cc.tn.us":true,"cc.tx.us":true,"cc.ut.us":true,"cc.vi.us":true,"cc.vt.us":true,"cc.va.us":true,"cc.wa.us":true,"cc.wi.us":true,"cc.wv.us":true,"cc.wy.us":true,"lib.ak.us":true,"lib.al.us":true,"lib.ar.us":true,"lib.as.us":true,"lib.az.us":true,"lib.ca.us":true,"lib.co.us":true,"lib.ct.us":true,"lib.dc.us":true,"lib.de.us":true,"lib.fl.us":true,"lib.ga.us":true,"lib.gu.us":true,"lib.hi.us":true,"lib.ia.us":true,"lib.id.us":true,"lib.il.us":true,"lib.in.us":true,"lib.ks.us":true,"lib.ky.us":true,"lib.la.us":true,"lib.ma.us":true,"lib.md.us":true,"lib.me.us":true,"lib.mi.us":true,"lib.mn.us":true,"lib.mo.us":true,"lib.ms.us":true,"lib.mt.us":true,"lib.nc.us":true,"lib.nd.us":true,"lib.ne.us":true,"lib.nh.us":true,"lib.nj.us":true,"lib.nm.us":true,"lib.nv.us":true,"lib.ny.us":true,"lib.oh.us":true,"lib.ok.us":true,"lib.or.us":true,"lib.pa.us":true,"lib.pr.us":true,"lib.ri.us":true,"lib.sc.us":true,"lib.sd.us":true,"lib.tn.us":true,"lib.tx.us":true,"lib.ut.us":true,"lib.vi.us":true,"lib.vt.us":true,"lib.va.us":true,"lib.wa.us":true,"lib.wi.us":true,"lib.wy.us":true,"pvt.k12.ma.us":true,"chtr.k12.ma.us":true,"paroch.k12.ma.us":true,"uy":true,"com.uy":true,"edu.uy":true,"gub.uy":true,"mil.uy":true,"net.uy":true,"org.uy":true,"uz":true,"co.uz":true,"com.uz":true,"net.uz":true,"org.uz":true,"va":true,"vc":true,"com.vc":true,"net.vc":true,"org.vc":true,"gov.vc":true,"mil.vc":true,"edu.vc":true,"ve":true,"arts.ve":true,"co.ve":true,"com.ve":true,"e12.ve":true,"edu.ve":true,"firm.ve":true,"gob.ve":true,"gov.ve":true,"info.ve":true,"int.ve":true,"mil.ve":true,"net.ve":true,"org.ve":true,"rec.ve":true,"store.ve":true,"tec.ve":true,"web.ve":true,"vg":true,"vi":true,"co.vi":true,"com.vi":true,"k12.vi":true,"net.vi":true,"org.vi":true,"vn":true,"com.vn":true,"net.vn":true,"org.vn":true,"edu.vn":true,"gov.vn":true,"int.vn":true,"ac.vn":true,"biz.vn":true,"info.vn":true,"name.vn":true,"pro.vn":true,"health.vn":true,"vu":true,"com.vu":true,"edu.vu":true,"net.vu":true,"org.vu":true,"wf":true,"ws":true,"com.ws":true,"net.ws":true,"org.ws":true,"gov.ws":true,"edu.ws":true,"yt":true,"xn--mgbaam7a8h":true,"xn--y9a3aq":true,"xn--54b7fta0cc":true,"xn--90ais":true,"xn--fiqs8s":true,"xn--fiqz9s":true,"xn--lgbbat1ad8j":true,"xn--wgbh1c":true,"xn--node":true,"xn--qxam":true,"xn--j6w193g":true,"xn--h2brj9c":true,"xn--mgbbh1a71e":true,"xn--fpcrj9c3d":true,"xn--gecrj9c":true,"xn--s9brj9c":true,"xn--45brj9c":true,"xn--xkc2dl3a5ee0h":true,"xn--mgba3a4f16a":true,"xn--mgba3a4fra":true,"xn--mgbtx2b":true,"xn--mgbayh7gpa":true,"xn--3e0b707e":true,"xn--80ao21a":true,"xn--fzc2c9e2c":true,"xn--xkc2al3hye2a":true,"xn--mgbc0a9azcg":true,"xn--d1alf":true,"xn--l1acc":true,"xn--mix891f":true,"xn--mix082f":true,"xn--mgbx4cd0ab":true,"xn--mgb9awbf":true,"xn--mgbai9azgqp6j":true,"xn--mgbai9a5eva00b":true,"xn--ygbi2ammx":true,"xn--90a3ac":true,"xn--o1ac.xn--90a3ac":true,"xn--c1avg.xn--90a3ac":true,"xn--90azh.xn--90a3ac":true,"xn--d1at.xn--90a3ac":true,"xn--o1ach.xn--90a3ac":true,"xn--80au.xn--90a3ac":true,"xn--p1ai":true,"xn--wgbl6a":true,"xn--mgberp4a5d4ar":true,"xn--mgberp4a5d4a87g":true,"xn--mgbqly7c0a67fbc":true,"xn--mgbqly7cvafr":true,"xn--mgbpl2fh":true,"xn--yfro4i67o":true,"xn--clchc0ea0b2g2a9gcd":true,"xn--ogbpf8fl":true,"xn--mgbtf8fl":true,"xn--o3cw4h":true,"xn--pgbs0dh":true,"xn--kpry57d":true,"xn--kprw13d":true,"xn--nnx388a":true,"xn--j1amh":true,"xn--mgb2ddes":true,"xxx":true,"*.ye":true,"ac.za":true,"agrica.za":true,"alt.za":true,"co.za":true,"edu.za":true,"gov.za":true,"grondar.za":true,"law.za":true,"mil.za":true,"net.za":true,"ngo.za":true,"nis.za":true,"nom.za":true,"org.za":true,"school.za":true,"tm.za":true,"web.za":true,"*.zm":true,"*.zw":true,"aaa":true,"aarp":true,"abarth":true,"abb":true,"abbott":true,"abbvie":true,"abc":true,"able":true,"abogado":true,"abudhabi":true,"academy":true,"accenture":true,"accountant":true,"accountants":true,"aco":true,"active":true,"actor":true,"adac":true,"ads":true,"adult":true,"aeg":true,"aetna":true,"afamilycompany":true,"afl":true,"africa":true,"africamagic":true,"agakhan":true,"agency":true,"aig":true,"aigo":true,"airbus":true,"airforce":true,"airtel":true,"akdn":true,"alfaromeo":true,"alibaba":true,"alipay":true,"allfinanz":true,"allstate":true,"ally":true,"alsace":true,"alstom":true,"americanexpress":true,"americanfamily":true,"amex":true,"amfam":true,"amica":true,"amsterdam":true,"analytics":true,"android":true,"anquan":true,"anz":true,"aol":true,"apartments":true,"app":true,"apple":true,"aquarelle":true,"aramco":true,"archi":true,"army":true,"arte":true,"asda":true,"associates":true,"athleta":true,"attorney":true,"auction":true,"audi":true,"audible":true,"audio":true,"auspost":true,"author":true,"auto":true,"autos":true,"avianca":true,"aws":true,"axa":true,"azure":true,"baby":true,"baidu":true,"banamex":true,"bananarepublic":true,"band":true,"bank":true,"bar":true,"barcelona":true,"barclaycard":true,"barclays":true,"barefoot":true,"bargains":true,"basketball":true,"bauhaus":true,"bayern":true,"bbc":true,"bbt":true,"bbva":true,"bcg":true,"bcn":true,"beats":true,"beer":true,"bentley":true,"berlin":true,"best":true,"bestbuy":true,"bet":true,"bharti":true,"bible":true,"bid":true,"bike":true,"bing":true,"bingo":true,"bio":true,"black":true,"blackfriday":true,"blanco":true,"blockbuster":true,"blog":true,"bloomberg":true,"blue":true,"bms":true,"bmw":true,"bnl":true,"bnpparibas":true,"boats":true,"boehringer":true,"bofa":true,"bom":true,"bond":true,"boo":true,"book":true,"booking":true,"boots":true,"bosch":true,"bostik":true,"bot":true,"boutique":true,"bradesco":true,"bridgestone":true,"broadway":true,"broker":true,"brother":true,"brussels":true,"budapest":true,"bugatti":true,"build":true,"builders":true,"business":true,"buy":true,"buzz":true,"bzh":true,"cab":true,"cafe":true,"cal":true,"call":true,"calvinklein":true,"camera":true,"camp":true,"cancerresearch":true,"canon":true,"capetown":true,"capital":true,"capitalone":true,"car":true,"caravan":true,"cards":true,"care":true,"career":true,"careers":true,"cars":true,"cartier":true,"casa":true,"case":true,"caseih":true,"cash":true,"casino":true,"catering":true,"cba":true,"cbn":true,"cbre":true,"cbs":true,"ceb":true,"center":true,"ceo":true,"cern":true,"cfa":true,"cfd":true,"chanel":true,"channel":true,"chase":true,"chat":true,"cheap":true,"chintai":true,"chloe":true,"christmas":true,"chrome":true,"chrysler":true,"church":true,"cipriani":true,"circle":true,"cisco":true,"citadel":true,"citi":true,"citic":true,"city":true,"cityeats":true,"claims":true,"cleaning":true,"click":true,"clinic":true,"clothing":true,"cloud":true,"club":true,"clubmed":true,"coach":true,"codes":true,"coffee":true,"college":true,"cologne":true,"comcast":true,"commbank":true,"community":true,"company":true,"computer":true,"comsec":true,"condos":true,"construction":true,"consulting":true,"contact":true,"contractors":true,"cooking":true,"cookingchannel":true,"cool":true,"corsica":true,"country":true,"coupon":true,"coupons":true,"courses":true,"credit":true,"creditcard":true,"creditunion":true,"cricket":true,"crown":true,"crs":true,"cruises":true,"csc":true,"cuisinella":true,"cymru":true,"cyou":true,"dabur":true,"dad":true,"dance":true,"date":true,"dating":true,"datsun":true,"day":true,"dclk":true,"dds":true,"deal":true,"dealer":true,"deals":true,"degree":true,"delivery":true,"dell":true,"deloitte":true,"delta":true,"democrat":true,"dental":true,"dentist":true,"desi":true,"design":true,"dev":true,"dhl":true,"diamonds":true,"diet":true,"digital":true,"direct":true,"directory":true,"discount":true,"discover":true,"dish":true,"dnp":true,"docs":true,"dodge":true,"dog":true,"doha":true,"domains":true,"doosan":true,"dot":true,"download":true,"drive":true,"dstv":true,"dtv":true,"dubai":true,"duck":true,"dunlop":true,"duns":true,"dupont":true,"durban":true,"dvag":true,"dwg":true,"earth":true,"eat":true,"edeka":true,"education":true,"email":true,"emerck":true,"emerson":true,"energy":true,"engineer":true,"engineering":true,"enterprises":true,"epost":true,"epson":true,"equipment":true,"ericsson":true,"erni":true,"esq":true,"estate":true,"esurance":true,"etisalat":true,"eurovision":true,"eus":true,"events":true,"everbank":true,"exchange":true,"expert":true,"exposed":true,"express":true,"extraspace":true,"fage":true,"fail":true,"fairwinds":true,"faith":true,"family":true,"fan":true,"fans":true,"farm":true,"farmers":true,"fashion":true,"fast":true,"fedex":true,"feedback":true,"ferrari":true,"ferrero":true,"fiat":true,"fidelity":true,"fido":true,"film":true,"final":true,"finance":true,"financial":true,"fire":true,"firestone":true,"firmdale":true,"fish":true,"fishing":true,"fit":true,"fitness":true,"flickr":true,"flights":true,"flir":true,"florist":true,"flowers":true,"flsmidth":true,"fly":true,"foo":true,"foodnetwork":true,"football":true,"ford":true,"forex":true,"forsale":true,"forum":true,"foundation":true,"fox":true,"fresenius":true,"frl":true,"frogans":true,"frontdoor":true,"frontier":true,"ftr":true,"fujitsu":true,"fujixerox":true,"fund":true,"furniture":true,"futbol":true,"fyi":true,"gal":true,"gallery":true,"gallo":true,"gallup":true,"game":true,"games":true,"gap":true,"garden":true,"gbiz":true,"gdn":true,"gea":true,"gent":true,"genting":true,"george":true,"ggee":true,"gift":true,"gifts":true,"gives":true,"giving":true,"glade":true,"glass":true,"gle":true,"global":true,"globo":true,"gmail":true,"gmo":true,"gmx":true,"godaddy":true,"gold":true,"goldpoint":true,"golf":true,"goo":true,"goodhands":true,"goodyear":true,"goog":true,"google":true,"gop":true,"got":true,"gotv":true,"grainger":true,"graphics":true,"gratis":true,"green":true,"gripe":true,"group":true,"guardian":true,"gucci":true,"guge":true,"guide":true,"guitars":true,"guru":true,"hamburg":true,"hangout":true,"haus":true,"hbo":true,"hdfc":true,"hdfcbank":true,"health":true,"healthcare":true,"help":true,"helsinki":true,"here":true,"hermes":true,"hgtv":true,"hiphop":true,"hisamitsu":true,"hitachi":true,"hiv":true,"hkt":true,"hockey":true,"holdings":true,"holiday":true,"homedepot":true,"homegoods":true,"homes":true,"homesense":true,"honda":true,"honeywell":true,"horse":true,"host":true,"hosting":true,"hot":true,"hoteles":true,"hotmail":true,"house":true,"how":true,"hsbc":true,"htc":true,"hughes":true,"hyatt":true,"hyundai":true,"ibm":true,"icbc":true,"ice":true,"icu":true,"ieee":true,"ifm":true,"iinet":true,"ikano":true,"imamat":true,"imdb":true,"immo":true,"immobilien":true,"industries":true,"infiniti":true,"ing":true,"ink":true,"institute":true,"insurance":true,"insure":true,"intel":true,"international":true,"intuit":true,"investments":true,"ipiranga":true,"irish":true,"iselect":true,"ismaili":true,"ist":true,"istanbul":true,"itau":true,"itv":true,"iveco":true,"iwc":true,"jaguar":true,"java":true,"jcb":true,"jcp":true,"jeep":true,"jetzt":true,"jewelry":true,"jio":true,"jlc":true,"jll":true,"jmp":true,"jnj":true,"joburg":true,"jot":true,"joy":true,"jpmorgan":true,"jprs":true,"juegos":true,"juniper":true,"kaufen":true,"kddi":true,"kerryhotels":true,"kerrylogistics":true,"kerryproperties":true,"kfh":true,"kia":true,"kim":true,"kinder":true,"kindle":true,"kitchen":true,"kiwi":true,"koeln":true,"komatsu":true,"kosher":true,"kpmg":true,"kpn":true,"krd":true,"kred":true,"kuokgroup":true,"kyknet":true,"kyoto":true,"lacaixa":true,"ladbrokes":true,"lamborghini":true,"lancaster":true,"lancia":true,"lancome":true,"land":true,"landrover":true,"lanxess":true,"lasalle":true,"lat":true,"latino":true,"latrobe":true,"law":true,"lawyer":true,"lds":true,"lease":true,"leclerc":true,"lefrak":true,"legal":true,"lego":true,"lexus":true,"lgbt":true,"liaison":true,"lidl":true,"life":true,"lifeinsurance":true,"lifestyle":true,"lighting":true,"like":true,"lilly":true,"limited":true,"limo":true,"lincoln":true,"linde":true,"link":true,"lipsy":true,"live":true,"living":true,"lixil":true,"loan":true,"loans":true,"locker":true,"locus":true,"loft":true,"lol":true,"london":true,"lotte":true,"lotto":true,"love":true,"lpl":true,"lplfinancial":true,"ltd":true,"ltda":true,"lundbeck":true,"lupin":true,"luxe":true,"luxury":true,"macys":true,"madrid":true,"maif":true,"maison":true,"makeup":true,"man":true,"management":true,"mango":true,"market":true,"marketing":true,"markets":true,"marriott":true,"marshalls":true,"maserati":true,"mattel":true,"mba":true,"mcd":true,"mcdonalds":true,"mckinsey":true,"med":true,"media":true,"meet":true,"melbourne":true,"meme":true,"memorial":true,"men":true,"menu":true,"meo":true,"metlife":true,"miami":true,"microsoft":true,"mini":true,"mint":true,"mit":true,"mitsubishi":true,"mlb":true,"mls":true,"mma":true,"mnet":true,"mobily":true,"moda":true,"moe":true,"moi":true,"mom":true,"monash":true,"money":true,"monster":true,"montblanc":true,"mopar":true,"mormon":true,"mortgage":true,"moscow":true,"moto":true,"motorcycles":true,"mov":true,"movie":true,"movistar":true,"msd":true,"mtn":true,"mtpc":true,"mtr":true,"multichoice":true,"mutual":true,"mutuelle":true,"mzansimagic":true,"nab":true,"nadex":true,"nagoya":true,"naspers":true,"nationwide":true,"natura":true,"navy":true,"nba":true,"nec":true,"netbank":true,"netflix":true,"network":true,"neustar":true,"new":true,"newholland":true,"news":true,"next":true,"nextdirect":true,"nexus":true,"nfl":true,"ngo":true,"nhk":true,"nico":true,"nike":true,"nikon":true,"ninja":true,"nissan":true,"nokia":true,"northwesternmutual":true,"norton":true,"now":true,"nowruz":true,"nowtv":true,"nra":true,"nrw":true,"ntt":true,"nyc":true,"obi":true,"observer":true,"off":true,"office":true,"okinawa":true,"olayan":true,"olayangroup":true,"oldnavy":true,"ollo":true,"omega":true,"one":true,"ong":true,"onl":true,"online":true,"onyourside":true,"ooo":true,"open":true,"oracle":true,"orange":true,"organic":true,"orientexpress":true,"osaka":true,"otsuka":true,"ott":true,"ovh":true,"page":true,"pamperedchef":true,"panasonic":true,"panerai":true,"paris":true,"pars":true,"partners":true,"parts":true,"party":true,"passagens":true,"pay":true,"payu":true,"pccw":true,"pet":true,"pfizer":true,"pharmacy":true,"philips":true,"photo":true,"photography":true,"photos":true,"physio":true,"piaget":true,"pics":true,"pictet":true,"pictures":true,"pid":true,"pin":true,"ping":true,"pink":true,"pioneer":true,"pizza":true,"place":true,"play":true,"playstation":true,"plumbing":true,"plus":true,"pnc":true,"pohl":true,"poker":true,"politie":true,"porn":true,"pramerica":true,"praxi":true,"press":true,"prime":true,"prod":true,"productions":true,"prof":true,"progressive":true,"promo":true,"properties":true,"property":true,"protection":true,"pru":true,"prudential":true,"pub":true,"qpon":true,"quebec":true,"quest":true,"qvc":true,"racing":true,"raid":true,"read":true,"realestate":true,"realtor":true,"realty":true,"recipes":true,"red":true,"redstone":true,"redumbrella":true,"rehab":true,"reise":true,"reisen":true,"reit":true,"reliance":true,"ren":true,"rent":true,"rentals":true,"repair":true,"report":true,"republican":true,"rest":true,"restaurant":true,"review":true,"reviews":true,"rexroth":true,"rich":true,"richardli":true,"ricoh":true,"rightathome":true,"ril":true,"rio":true,"rip":true,"rocher":true,"rocks":true,"rodeo":true,"rogers":true,"room":true,"rsvp":true,"ruhr":true,"run":true,"rwe":true,"ryukyu":true,"saarland":true,"safe":true,"safety":true,"sakura":true,"sale":true,"salon":true,"samsclub":true,"samsung":true,"sandvik":true,"sandvikcoromant":true,"sanofi":true,"sap":true,"sapo":true,"sarl":true,"sas":true,"save":true,"saxo":true,"sbi":true,"sbs":true,"sca":true,"scb":true,"schaeffler":true,"schmidt":true,"scholarships":true,"school":true,"schule":true,"schwarz":true,"science":true,"scjohnson":true,"scor":true,"scot":true,"seat":true,"secure":true,"security":true,"seek":true,"sener":true,"services":true,"ses":true,"seven":true,"sew":true,"sex":true,"sexy":true,"sfr":true,"shangrila":true,"sharp":true,"shaw":true,"shell":true,"shia":true,"shiksha":true,"shoes":true,"shouji":true,"show":true,"showtime":true,"shriram":true,"silk":true,"sina":true,"singles":true,"site":true,"ski":true,"skin":true,"sky":true,"skype":true,"sling":true,"smart":true,"smile":true,"sncf":true,"soccer":true,"social":true,"softbank":true,"software":true,"sohu":true,"solar":true,"solutions":true,"song":true,"sony":true,"soy":true,"space":true,"spiegel":true,"spot":true,"spreadbetting":true,"srl":true,"srt":true,"stada":true,"staples":true,"star":true,"starhub":true,"statebank":true,"statefarm":true,"statoil":true,"stc":true,"stcgroup":true,"stockholm":true,"storage":true,"store":true,"studio":true,"study":true,"style":true,"sucks":true,"supersport":true,"supplies":true,"supply":true,"support":true,"surf":true,"surgery":true,"suzuki":true,"swatch":true,"swiftcover":true,"swiss":true,"sydney":true,"symantec":true,"systems":true,"tab":true,"taipei":true,"talk":true,"taobao":true,"target":true,"tatamotors":true,"tatar":true,"tattoo":true,"tax":true,"taxi":true,"tci":true,"tdk":true,"team":true,"tech":true,"technology":true,"telecity":true,"telefonica":true,"temasek":true,"tennis":true,"teva":true,"thd":true,"theater":true,"theatre":true,"theguardian":true,"tiaa":true,"tickets":true,"tienda":true,"tiffany":true,"tips":true,"tires":true,"tirol":true,"tjmaxx":true,"tjx":true,"tkmaxx":true,"tmall":true,"today":true,"tokyo":true,"tools":true,"top":true,"toray":true,"toshiba":true,"total":true,"tours":true,"town":true,"toyota":true,"toys":true,"trade":true,"trading":true,"training":true,"travelchannel":true,"travelers":true,"travelersinsurance":true,"trust":true,"trv":true,"tube":true,"tui":true,"tunes":true,"tushu":true,"tvs":true,"ubank":true,"ubs":true,"uconnect":true,"university":true,"uno":true,"uol":true,"ups":true,"vacations":true,"vana":true,"vanguard":true,"vegas":true,"ventures":true,"verisign":true,"versicherung":true,"vet":true,"viajes":true,"video":true,"vig":true,"viking":true,"villas":true,"vin":true,"vip":true,"virgin":true,"visa":true,"vision":true,"vista":true,"vistaprint":true,"viva":true,"vivo":true,"vlaanderen":true,"vodka":true,"volkswagen":true,"vote":true,"voting":true,"voto":true,"voyage":true,"vuelos":true,"wales":true,"walmart":true,"walter":true,"wang":true,"wanggou":true,"warman":true,"watch":true,"watches":true,"weather":true,"weatherchannel":true,"webcam":true,"weber":true,"website":true,"wed":true,"wedding":true,"weibo":true,"weir":true,"whoswho":true,"wien":true,"wiki":true,"williamhill":true,"win":true,"windows":true,"wine":true,"winners":true,"wme":true,"wolterskluwer":true,"woodside":true,"work":true,"works":true,"world":true,"wtc":true,"wtf":true,"xbox":true,"xerox":true,"xfinity":true,"xihuan":true,"xin":true,"xn--11b4c3d":true,"xn--1ck2e1b":true,"xn--1qqw23a":true,"xn--30rr7y":true,"xn--3bst00m":true,"xn--3ds443g":true,"xn--3oq18vl8pn36a":true,"xn--3pxu8k":true,"xn--42c2d9a":true,"xn--45q11c":true,"xn--4gbrim":true,"xn--4gq48lf9j":true,"xn--55qw42g":true,"xn--55qx5d":true,"xn--5su34j936bgsg":true,"xn--5tzm5g":true,"xn--6frz82g":true,"xn--6qq986b3xl":true,"xn--80adxhks":true,"xn--80asehdb":true,"xn--80aswg":true,"xn--8y0a063a":true,"xn--9dbq2a":true,"xn--9et52u":true,"xn--9krt00a":true,"xn--b4w605ferd":true,"xn--bck1b9a5dre4c":true,"xn--c1avg":true,"xn--c2br7g":true,"xn--cck2b3b":true,"xn--cg4bki":true,"xn--czr694b":true,"xn--czrs0t":true,"xn--czru2d":true,"xn--d1acj3b":true,"xn--eckvdtc9d":true,"xn--efvy88h":true,"xn--estv75g":true,"xn--fct429k":true,"xn--fhbei":true,"xn--fiq228c5hs":true,"xn--fiq64b":true,"xn--fjq720a":true,"xn--flw351e":true,"xn--fzys8d69uvgm":true,"xn--g2xx48c":true,"xn--gckr3f0f":true,"xn--hxt814e":true,"xn--i1b6b1a6a2e":true,"xn--imr513n":true,"xn--io0a7i":true,"xn--j1aef":true,"xn--jlq61u9w7b":true,"xn--jvr189m":true,"xn--kcrx77d1x4a":true,"xn--kpu716f":true,"xn--kput3i":true,"xn--mgba3a3ejt":true,"xn--mgba7c0bbn0a":true,"xn--mgbaakc7dvf":true,"xn--mgbab2bd":true,"xn--mgbb9fbpob":true,"xn--mgbca7dzdo":true,"xn--mgbt3dhd":true,"xn--mk1bu44c":true,"xn--mxtq1m":true,"xn--ngbc5azd":true,"xn--ngbe9e0a":true,"xn--nqv7f":true,"xn--nqv7fs00ema":true,"xn--nyqy26a":true,"xn--p1acf":true,"xn--pbt977c":true,"xn--pssy2u":true,"xn--q9jyb4c":true,"xn--qcka1pmc":true,"xn--rhqv96g":true,"xn--rovu88b":true,"xn--ses554g":true,"xn--t60b56a":true,"xn--tckwe":true,"xn--unup4y":true,"xn--vermgensberater-ctb":true,"xn--vermgensberatung-pwb":true,"xn--vhquv":true,"xn--vuq861b":true,"xn--w4r85el8fhu5dnra":true,"xn--w4rs40l":true,"xn--xhq521b":true,"xn--zfr164b":true,"xperia":true,"xyz":true,"yachts":true,"yahoo":true,"yamaxun":true,"yandex":true,"yodobashi":true,"yoga":true,"yokohama":true,"you":true,"youtube":true,"yun":true,"zappos":true,"zara":true,"zero":true,"zip":true,"zippo":true,"zone":true,"zuerich":true,"cloudfront.net":true,"ap-northeast-1.compute.amazonaws.com":true,"ap-southeast-1.compute.amazonaws.com":true,"ap-southeast-2.compute.amazonaws.com":true,"cn-north-1.compute.amazonaws.cn":true,"compute.amazonaws.cn":true,"compute.amazonaws.com":true,"compute-1.amazonaws.com":true,"eu-west-1.compute.amazonaws.com":true,"eu-central-1.compute.amazonaws.com":true,"sa-east-1.compute.amazonaws.com":true,"us-east-1.amazonaws.com":true,"us-gov-west-1.compute.amazonaws.com":true,"us-west-1.compute.amazonaws.com":true,"us-west-2.compute.amazonaws.com":true,"z-1.compute-1.amazonaws.com":true,"z-2.compute-1.amazonaws.com":true,"elasticbeanstalk.com":true,"elb.amazonaws.com":true,"s3.amazonaws.com":true,"s3-ap-northeast-1.amazonaws.com":true,"s3-ap-southeast-1.amazonaws.com":true,"s3-ap-southeast-2.amazonaws.com":true,"s3-external-1.amazonaws.com":true,"s3-external-2.amazonaws.com":true,"s3-fips-us-gov-west-1.amazonaws.com":true,"s3-eu-central-1.amazonaws.com":true,"s3-eu-west-1.amazonaws.com":true,"s3-sa-east-1.amazonaws.com":true,"s3-us-gov-west-1.amazonaws.com":true,"s3-us-west-1.amazonaws.com":true,"s3-us-west-2.amazonaws.com":true,"s3.cn-north-1.amazonaws.com.cn":true,"s3.eu-central-1.amazonaws.com":true,"betainabox.com":true,"ae.org":true,"ar.com":true,"br.com":true,"cn.com":true,"com.de":true,"com.se":true,"de.com":true,"eu.com":true,"gb.com":true,"gb.net":true,"hu.com":true,"hu.net":true,"jp.net":true,"jpn.com":true,"kr.com":true,"mex.com":true,"no.com":true,"qc.com":true,"ru.com":true,"sa.com":true,"se.com":true,"se.net":true,"uk.com":true,"uk.net":true,"us.com":true,"uy.com":true,"za.bz":true,"za.com":true,"africa.com":true,"gr.com":true,"in.net":true,"us.org":true,"co.com":true,"c.la":true,"cloudcontrolled.com":true,"cloudcontrolapp.com":true,"co.ca":true,"c.cdn77.org":true,"cdn77-ssl.net":true,"r.cdn77.net":true,"rsc.cdn77.org":true,"ssl.origin.cdn77-secure.org":true,"co.nl":true,"co.no":true,"*.platform.sh":true,"cupcake.is":true,"dreamhosters.com":true,"duckdns.org":true,"dyndns-at-home.com":true,"dyndns-at-work.com":true,"dyndns-blog.com":true,"dyndns-free.com":true,"dyndns-home.com":true,"dyndns-ip.com":true,"dyndns-mail.com":true,"dyndns-office.com":true,"dyndns-pics.com":true,"dyndns-remote.com":true,"dyndns-server.com":true,"dyndns-web.com":true,"dyndns-wiki.com":true,"dyndns-work.com":true,"dyndns.biz":true,"dyndns.info":true,"dyndns.org":true,"dyndns.tv":true,"at-band-camp.net":true,"ath.cx":true,"barrel-of-knowledge.info":true,"barrell-of-knowledge.info":true,"better-than.tv":true,"blogdns.com":true,"blogdns.net":true,"blogdns.org":true,"blogsite.org":true,"boldlygoingnowhere.org":true,"broke-it.net":true,"buyshouses.net":true,"cechire.com":true,"dnsalias.com":true,"dnsalias.net":true,"dnsalias.org":true,"dnsdojo.com":true,"dnsdojo.net":true,"dnsdojo.org":true,"does-it.net":true,"doesntexist.com":true,"doesntexist.org":true,"dontexist.com":true,"dontexist.net":true,"dontexist.org":true,"doomdns.com":true,"doomdns.org":true,"dvrdns.org":true,"dyn-o-saur.com":true,"dynalias.com":true,"dynalias.net":true,"dynalias.org":true,"dynathome.net":true,"dyndns.ws":true,"endofinternet.net":true,"endofinternet.org":true,"endoftheinternet.org":true,"est-a-la-maison.com":true,"est-a-la-masion.com":true,"est-le-patron.com":true,"est-mon-blogueur.com":true,"for-better.biz":true,"for-more.biz":true,"for-our.info":true,"for-some.biz":true,"for-the.biz":true,"forgot.her.name":true,"forgot.his.name":true,"from-ak.com":true,"from-al.com":true,"from-ar.com":true,"from-az.net":true,"from-ca.com":true,"from-co.net":true,"from-ct.com":true,"from-dc.com":true,"from-de.com":true,"from-fl.com":true,"from-ga.com":true,"from-hi.com":true,"from-ia.com":true,"from-id.com":true,"from-il.com":true,"from-in.com":true,"from-ks.com":true,"from-ky.com":true,"from-la.net":true,"from-ma.com":true,"from-md.com":true,"from-me.org":true,"from-mi.com":true,"from-mn.com":true,"from-mo.com":true,"from-ms.com":true,"from-mt.com":true,"from-nc.com":true,"from-nd.com":true,"from-ne.com":true,"from-nh.com":true,"from-nj.com":true,"from-nm.com":true,"from-nv.com":true,"from-ny.net":true,"from-oh.com":true,"from-ok.com":true,"from-or.com":true,"from-pa.com":true,"from-pr.com":true,"from-ri.com":true,"from-sc.com":true,"from-sd.com":true,"from-tn.com":true,"from-tx.com":true,"from-ut.com":true,"from-va.com":true,"from-vt.com":true,"from-wa.com":true,"from-wi.com":true,"from-wv.com":true,"from-wy.com":true,"ftpaccess.cc":true,"fuettertdasnetz.de":true,"game-host.org":true,"game-server.cc":true,"getmyip.com":true,"gets-it.net":true,"go.dyndns.org":true,"gotdns.com":true,"gotdns.org":true,"groks-the.info":true,"groks-this.info":true,"ham-radio-op.net":true,"here-for-more.info":true,"hobby-site.com":true,"hobby-site.org":true,"home.dyndns.org":true,"homedns.org":true,"homeftp.net":true,"homeftp.org":true,"homeip.net":true,"homelinux.com":true,"homelinux.net":true,"homelinux.org":true,"homeunix.com":true,"homeunix.net":true,"homeunix.org":true,"iamallama.com":true,"in-the-band.net":true,"is-a-anarchist.com":true,"is-a-blogger.com":true,"is-a-bookkeeper.com":true,"is-a-bruinsfan.org":true,"is-a-bulls-fan.com":true,"is-a-candidate.org":true,"is-a-caterer.com":true,"is-a-celticsfan.org":true,"is-a-chef.com":true,"is-a-chef.net":true,"is-a-chef.org":true,"is-a-conservative.com":true,"is-a-cpa.com":true,"is-a-cubicle-slave.com":true,"is-a-democrat.com":true,"is-a-designer.com":true,"is-a-doctor.com":true,"is-a-financialadvisor.com":true,"is-a-geek.com":true,"is-a-geek.net":true,"is-a-geek.org":true,"is-a-green.com":true,"is-a-guru.com":true,"is-a-hard-worker.com":true,"is-a-hunter.com":true,"is-a-knight.org":true,"is-a-landscaper.com":true,"is-a-lawyer.com":true,"is-a-liberal.com":true,"is-a-libertarian.com":true,"is-a-linux-user.org":true,"is-a-llama.com":true,"is-a-musician.com":true,"is-a-nascarfan.com":true,"is-a-nurse.com":true,"is-a-painter.com":true,"is-a-patsfan.org":true,"is-a-personaltrainer.com":true,"is-a-photographer.com":true,"is-a-player.com":true,"is-a-republican.com":true,"is-a-rockstar.com":true,"is-a-socialist.com":true,"is-a-soxfan.org":true,"is-a-student.com":true,"is-a-teacher.com":true,"is-a-techie.com":true,"is-a-therapist.com":true,"is-an-accountant.com":true,"is-an-actor.com":true,"is-an-actress.com":true,"is-an-anarchist.com":true,"is-an-artist.com":true,"is-an-engineer.com":true,"is-an-entertainer.com":true,"is-by.us":true,"is-certified.com":true,"is-found.org":true,"is-gone.com":true,"is-into-anime.com":true,"is-into-cars.com":true,"is-into-cartoons.com":true,"is-into-games.com":true,"is-leet.com":true,"is-lost.org":true,"is-not-certified.com":true,"is-saved.org":true,"is-slick.com":true,"is-uberleet.com":true,"is-very-bad.org":true,"is-very-evil.org":true,"is-very-good.org":true,"is-very-nice.org":true,"is-very-sweet.org":true,"is-with-theband.com":true,"isa-geek.com":true,"isa-geek.net":true,"isa-geek.org":true,"isa-hockeynut.com":true,"issmarterthanyou.com":true,"isteingeek.de":true,"istmein.de":true,"kicks-ass.net":true,"kicks-ass.org":true,"knowsitall.info":true,"land-4-sale.us":true,"lebtimnetz.de":true,"leitungsen.de":true,"likes-pie.com":true,"likescandy.com":true,"merseine.nu":true,"mine.nu":true,"misconfused.org":true,"mypets.ws":true,"myphotos.cc":true,"neat-url.com":true,"office-on-the.net":true,"on-the-web.tv":true,"podzone.net":true,"podzone.org":true,"readmyblog.org":true,"saves-the-whales.com":true,"scrapper-site.net":true,"scrapping.cc":true,"selfip.biz":true,"selfip.com":true,"selfip.info":true,"selfip.net":true,"selfip.org":true,"sells-for-less.com":true,"sells-for-u.com":true,"sells-it.net":true,"sellsyourhome.org":true,"servebbs.com":true,"servebbs.net":true,"servebbs.org":true,"serveftp.net":true,"serveftp.org":true,"servegame.org":true,"shacknet.nu":true,"simple-url.com":true,"space-to-rent.com":true,"stuff-4-sale.org":true,"stuff-4-sale.us":true,"teaches-yoga.com":true,"thruhere.net":true,"traeumtgerade.de":true,"webhop.biz":true,"webhop.info":true,"webhop.net":true,"webhop.org":true,"worse-than.tv":true,"writesthisblog.com":true,"eu.org":true,"al.eu.org":true,"asso.eu.org":true,"at.eu.org":true,"au.eu.org":true,"be.eu.org":true,"bg.eu.org":true,"ca.eu.org":true,"cd.eu.org":true,"ch.eu.org":true,"cn.eu.org":true,"cy.eu.org":true,"cz.eu.org":true,"de.eu.org":true,"dk.eu.org":true,"edu.eu.org":true,"ee.eu.org":true,"es.eu.org":true,"fi.eu.org":true,"fr.eu.org":true,"gr.eu.org":true,"hr.eu.org":true,"hu.eu.org":true,"ie.eu.org":true,"il.eu.org":true,"in.eu.org":true,"int.eu.org":true,"is.eu.org":true,"it.eu.org":true,"jp.eu.org":true,"kr.eu.org":true,"lt.eu.org":true,"lu.eu.org":true,"lv.eu.org":true,"mc.eu.org":true,"me.eu.org":true,"mk.eu.org":true,"mt.eu.org":true,"my.eu.org":true,"net.eu.org":true,"ng.eu.org":true,"nl.eu.org":true,"no.eu.org":true,"nz.eu.org":true,"paris.eu.org":true,"pl.eu.org":true,"pt.eu.org":true,"q-a.eu.org":true,"ro.eu.org":true,"ru.eu.org":true,"se.eu.org":true,"si.eu.org":true,"sk.eu.org":true,"tr.eu.org":true,"uk.eu.org":true,"us.eu.org":true,"a.ssl.fastly.net":true,"b.ssl.fastly.net":true,"global.ssl.fastly.net":true,"a.prod.fastly.net":true,"global.prod.fastly.net":true,"firebaseapp.com":true,"flynnhub.com":true,"service.gov.uk":true,"github.io":true,"githubusercontent.com":true,"ro.com":true,"appspot.com":true,"blogspot.ae":true,"blogspot.al":true,"blogspot.am":true,"blogspot.ba":true,"blogspot.be":true,"blogspot.bg":true,"blogspot.bj":true,"blogspot.ca":true,"blogspot.cf":true,"blogspot.ch":true,"blogspot.cl":true,"blogspot.co.at":true,"blogspot.co.id":true,"blogspot.co.il":true,"blogspot.co.ke":true,"blogspot.co.nz":true,"blogspot.co.uk":true,"blogspot.co.za":true,"blogspot.com":true,"blogspot.com.ar":true,"blogspot.com.au":true,"blogspot.com.br":true,"blogspot.com.by":true,"blogspot.com.co":true,"blogspot.com.cy":true,"blogspot.com.ee":true,"blogspot.com.eg":true,"blogspot.com.es":true,"blogspot.com.mt":true,"blogspot.com.ng":true,"blogspot.com.tr":true,"blogspot.com.uy":true,"blogspot.cv":true,"blogspot.cz":true,"blogspot.de":true,"blogspot.dk":true,"blogspot.fi":true,"blogspot.fr":true,"blogspot.gr":true,"blogspot.hk":true,"blogspot.hr":true,"blogspot.hu":true,"blogspot.ie":true,"blogspot.in":true,"blogspot.is":true,"blogspot.it":true,"blogspot.jp":true,"blogspot.kr":true,"blogspot.li":true,"blogspot.lt":true,"blogspot.lu":true,"blogspot.md":true,"blogspot.mk":true,"blogspot.mr":true,"blogspot.mx":true,"blogspot.my":true,"blogspot.nl":true,"blogspot.no":true,"blogspot.pe":true,"blogspot.pt":true,"blogspot.qa":true,"blogspot.re":true,"blogspot.ro":true,"blogspot.rs":true,"blogspot.ru":true,"blogspot.se":true,"blogspot.sg":true,"blogspot.si":true,"blogspot.sk":true,"blogspot.sn":true,"blogspot.td":true,"blogspot.tw":true,"blogspot.ug":true,"blogspot.vn":true,"codespot.com":true,"googleapis.com":true,"googlecode.com":true,"pagespeedmobilizer.com":true,"withgoogle.com":true,"withyoutube.com":true,"herokuapp.com":true,"herokussl.com":true,"iki.fi":true,"biz.at":true,"info.at":true,"co.pl":true,"azurewebsites.net":true,"azure-mobile.net":true,"cloudapp.net":true,"bmoattachments.org":true,"4u.com":true,"nfshost.com":true,"nyc.mn":true,"nid.io":true,"operaunite.com":true,"outsystemscloud.com":true,"art.pl":true,"gliwice.pl":true,"krakow.pl":true,"poznan.pl":true,"wroc.pl":true,"zakopane.pl":true,"pantheon.io":true,"gotpantheon.com":true,"priv.at":true,"qa2.com":true,"rhcloud.com":true,"sandcats.io":true,"biz.ua":true,"co.ua":true,"pp.ua":true,"sinaapp.com":true,"vipsinaapp.com":true,"1kapp.com":true,"gda.pl":true,"gdansk.pl":true,"gdynia.pl":true,"med.pl":true,"sopot.pl":true,"hk.com":true,"hk.org":true,"ltd.hk":true,"inc.hk":true,"yolasite.com":true,"za.net":true,"za.org":true}); +/***/ }), +/* 308 */ +/***/ (function(module, exports, __webpack_require__) { -// END of automatically generated file +module.exports = __webpack_require__(26); /***/ }), -/* 275 */ +/* 309 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * Copyright (c) 2015, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * 3. Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -/*jshint unused:false */ -function Store() { -} -exports.Store = Store; -// Stores may be synchronous, but are still required to use a -// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync" -// API that converts from synchronous-callbacks to imperative style. -Store.prototype.synchronous = false; +var Buffer = __webpack_require__(87).Buffer; -Store.prototype.findCookie = function(domain, path, key, cb) { - throw new Error('findCookie is not implemented'); +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } }; -Store.prototype.findCookies = function(domain, path, cb) { - throw new Error('findCookies is not implemented'); +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } }; -Store.prototype.putCookie = function(cookie, cb) { - throw new Error('putCookie is not implemented'); -}; +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} -Store.prototype.updateCookie = function(oldCookie, newCookie, cb) { - // recommended default implementation: - // return this.putCookie(newCookie, cb); - throw new Error('updateCookie is not implemented'); -}; +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} -Store.prototype.removeCookie = function(domain, path, key, cb) { - throw new Error('removeCookie is not implemented'); +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; }; -Store.prototype.removeCookies = function(domain, path, cb) { - throw new Error('removeCookies is not implemented'); -}; +StringDecoder.prototype.end = utf8End; -Store.prototype.getAllCookies = function(cb) { - throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)'); +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; }; +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return -1; +} -/***/ }), -/* 276 */ -/***/ (function(module, exports) { +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -var byteToHex = []; -for (var i = 0; i < 256; ++i) { - byteToHex[i] = (i + 0x100).toString(16).substr(1); +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } + } + } } -function bytesToUuid(buf, offset) { - var i = offset || 0; - var bth = byteToHex; - return bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + '-' + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]] + - bth[buf[i++]] + bth[buf[i++]]; +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; } -module.exports = bytesToUuid; +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} +// For UTF-8, a replacement character for each buffered byte of a (partial) +// character needs to be added to the output. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); + return r; +} -/***/ }), -/* 277 */ -/***/ (function(module, exports, __webpack_require__) { +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} -// Unique ID creation requires a high quality random # generator. In node.js -// this is prett straight-forward - we use the crypto API. +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} -var rb = __webpack_require__(7).randomBytes; +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} -function rng() { - return rb(16); -}; +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} -module.exports = rng; +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} /***/ }), -/* 278 */ -/***/ (function(module, exports) { +/* 310 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = extend +"use strict"; +/*! + * repeat-element <https://github.com/jonschlinkert/repeat-element> + * + * Copyright (c) 2015 Jon Schlinkert. + * Licensed under the MIT license. + */ -var hasOwnProperty = Object.prototype.hasOwnProperty; -function extend() { - var target = {} - for (var i = 0; i < arguments.length; i++) { - var source = arguments[i] +module.exports = function repeat(ele, num) { + var arr = new Array(num); - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - } - - return target -} - - -/***/ }), -/* 279 */ -/***/ (function(module, exports) { + for (var i = 0; i < num; i++) { + arr[i] = ele; + } -module.exports = { - "name": "yarn", - "installationMethod": "unknown", - "version": "0.27.5", - "license": "BSD-2-Clause", - "preferGlobal": true, - "description": "📦🈠Fast, reliable, and secure dependency management.", - "dependencies": { - "babel-runtime": "^6.0.0", - "bytes": "^2.4.0", - "camelcase": "^4.0.0", - "chalk": "^1.1.1", - "cmd-shim": "^2.0.1", - "commander": "^2.9.0", - "death": "^1.0.0", - "debug": "^2.2.0", - "detect-indent": "^5.0.0", - "glob": "^7.1.1", - "gunzip-maybe": "^1.4.0", - "ini": "^1.3.4", - "inquirer": "^3.0.1", - "invariant": "^2.2.0", - "is-builtin-module": "^1.0.0", - "is-ci": "^1.0.10", - "leven": "^2.0.0", - "loud-rejection": "^1.2.0", - "micromatch": "^2.3.11", - "mkdirp": "^0.5.1", - "node-emoji": "^1.0.4", - "object-path": "^0.11.2", - "proper-lockfile": "^2.0.0", - "read": "^1.0.7", - "request": "^2.81.0", - "request-capture-har": "^1.2.2", - "rimraf": "^2.5.0", - "semver": "^5.1.0", - "strip-bom": "^3.0.0", - "tar-fs": "^1.15.1", - "tar-stream": "^1.5.2", - "uuid": "^3.0.1", - "v8-compile-cache": "^1.1.0", - "validate-npm-package-license": "^3.0.1" - }, - "devDependencies": { - "babel-core": "^6.24.1", - "babel-eslint": "^6.1.2", - "babel-jest": "^19.0.0", - "babel-loader": "^6.2.5", - "babel-plugin-array-includes": "^2.0.3", - "babel-plugin-transform-es2015-typeof-symbol": "^6.8.0", - "babel-plugin-transform-inline-imports-commonjs": "^1.0.0", - "babel-plugin-transform-runtime": "^6.4.3", - "babel-preset-es2015-node4": "^2.1.0", - "babel-preset-node5": "^10.2.0", - "babel-preset-stage-0": "^6.0.0", - "babylon": "^6.5.0", - "eslint": "^3.19.0", - "eslint-config-fb-strict": "^20.0.1", - "eslint-plugin-babel": "^3.3.0", - "eslint-plugin-flowtype": "^2.32.1", - "eslint-plugin-react": "^6.7.1", - "eslint-plugin-yarn-internal": "file:scripts/eslint-rules", - "flow-bin": "^0.48.0", - "gulp": "^3.9.0", - "gulp-babel": "^6.0.0", - "gulp-if": "^2.0.1", - "gulp-newer": "^1.0.0", - "gulp-plumber": "^1.0.1", - "gulp-sourcemaps": "^2.2.0", - "gulp-util": "^3.0.7", - "gulp-watch": "^4.3.5", - "jest": "^19.0.2", - "mock-stdin": "^0.3.0", - "prettier": "^1.3.1", - "temp": "^0.8.3", - "webpack": "^2.1.0-beta.25", - "yargs": "^6.3.0" - }, - "engines": { - "node": ">=4.0.0" - }, - "repository": "yarnpkg/yarn", - "bin": { - "yarn": "./bin/yarn.js", - "yarnpkg": "./bin/yarn.js" - }, - "scripts": { - "build": "gulp build", - "build-bundle": "node ./scripts/build-webpack.js", - "build-chocolatey": "powershell ./scripts/build-chocolatey.ps1", - "build-deb": "./scripts/build-deb.sh", - "build-dist": "bash ./scripts/build-dist.sh", - "build-win-installer": "scripts\\build-windows-installer.bat", - "check-lockfile": "./scripts/check-lockfile.sh", - "lint": "yarn run lint-prettier && eslint . && flow check", - "lint-prettier": "node scripts/prettier.js lint", - "prettier": "node scripts/prettier.js write", - "release-branch": "./scripts/release-branch.sh", - "test": "yarn lint && yarn test-only", - "test-ci": "yarn build && yarn test-only", - "test-only": "jest --coverage --verbose", - "watch": "gulp watch" - }, - "jest": { - "collectCoverageFrom": [ - "src/**/*.js" - ], - "timers": "fake", - "testEnvironment": "node", - "modulePathIgnorePatterns": [ - "__tests__/fixtures/" - ], - "testPathIgnorePatterns": [ - "__tests__/(fixtures|__mocks__)/", - "updates/", - "/_(temp|mock|install|init|helpers).js$" - ] - } + return arr; }; -/***/ }), -/* 280 */ -/***/ (function(module, exports) { - -module.exports = require("constants"); - -/***/ }), -/* 281 */ -/***/ (function(module, exports) { - -module.exports = require("punycode"); - -/***/ }), -/* 282 */ -/***/ (function(module, exports) { - -module.exports = require("tls"); /***/ }), -/* 283 */ +/* 311 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _index; - -function _load_index() { - return _index = __webpack_require__(82); -} - -var _index2; - -function _load_index2() { - return _index2 = __webpack_require__(24); -} - -var _index3; - -function _load_index3() { - return _index3 = _interopRequireDefault(__webpack_require__(190)); -} - -var _constants; - -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} - -var _network; - -function _load_network() { - return _network = _interopRequireWildcard(__webpack_require__(207)); -} - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); -} - -var _config; - -function _load_config() { - return _config = _interopRequireDefault(__webpack_require__(120)); -} - -var _rc; +var tough = __webpack_require__(643) -function _load_rc() { - return _rc = __webpack_require__(363); -} +var Cookie = tough.Cookie + , CookieJar = tough.CookieJar -var _yarnVersion; -function _load_yarnVersion() { - return _yarnVersion = __webpack_require__(65); +exports.parse = function(str) { + if (str && str.uri) { + str = str.uri + } + if (typeof str !== 'string') { + throw new Error('The cookie function only accepts STRING as param') + } + return Cookie.parse(str, {loose: true}) } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const commander = __webpack_require__(411); - -const fs = __webpack_require__(6); -const invariant = __webpack_require__(5); -const lockfile = __webpack_require__(572); -const loudRejection = __webpack_require__(553); -const net = __webpack_require__(77); -const onDeath = __webpack_require__(451); -const path = __webpack_require__(1); - -loudRejection(); - -const startArgs = process.argv.slice(0, 2); - -// ignore all arguments after a -- -const doubleDashIndex = process.argv.findIndex(element => element === '--'); -const args = process.argv.slice(2, doubleDashIndex === -1 ? process.argv.length : doubleDashIndex); -const endArgs = doubleDashIndex === -1 ? [] : process.argv.slice(doubleDashIndex + 1, process.argv.length); - -// set global options -commander.version((_yarnVersion || _load_yarnVersion()).version); -commander.usage('[command] [flags]'); -commander.option('--verbose', 'output verbose messages on internal operations'); -commander.option('--offline', 'trigger an error if any required dependencies are not available in local cache'); -commander.option('--prefer-offline', 'use network only if dependencies are not available in local cache'); -commander.option('--strict-semver'); -commander.option('--json', ''); -commander.option('--ignore-scripts', "don't run lifecycle scripts"); -commander.option('--har', 'save HAR output of network traffic'); -commander.option('--ignore-platform', 'ignore platform checks'); -commander.option('--ignore-engines', 'ignore engines check'); -commander.option('--ignore-optional', 'ignore optional dependencies'); -commander.option('--force', 'install and build packages even if they were built before, overwrite lockfile'); -commander.option('--skip-integrity-check', 'run install without checking if node_modules is installed'); -commander.option('--check-files', 'install will verify file tree of packages for consistency'); -commander.option('--no-bin-links', "don't generate bin links when setting up packages"); -commander.option('--flat', 'only allow one version of a package'); -commander.option('--prod, --production [prod]', ''); -commander.option('--no-lockfile', "don't read or generate a lockfile"); -commander.option('--pure-lockfile', "don't generate a lockfile"); -commander.option('--frozen-lockfile', "don't generate a lockfile and fail if an update is needed"); -commander.option('--link-duplicates', 'create hardlinks to the repeated modules in node_modules'); -commander.option('--global-folder <path>', 'specify a custom folder to store global packages'); -commander.option('--modules-folder <path>', 'rather than installing modules into the node_modules folder relative to the cwd, output them here'); -commander.option('--cache-folder <path>', 'specify a custom folder to store the yarn cache'); -commander.option('--mutex <type>[:specifier]', 'use a mutex to ensure only one yarn instance is executing'); -commander.option('--emoji', 'enable emoji in output', process.platform === 'darwin'); -commander.option('-s, --silent', 'skip Yarn console logs, other types of logs (script output) will be printed'); -commander.option('--proxy <host>', ''); -commander.option('--https-proxy <host>', ''); -commander.option('--no-progress', 'disable progress bar'); -commander.option('--network-concurrency <number>', 'maximum number of concurrent network requests', parseInt); -commander.option('--network-timeout <milliseconds>', 'TCP timeout for network requests', parseInt); -commander.option('--non-interactive', 'do not show interactive prompts'); -commander.option('--scripts-prepend-node-path [bool]', 'prepend the node executable dir to the PATH in scripts'); - -// get command name -let commandName = args.shift() || 'install'; - -if (commandName === '--help' || commandName === '-h') { - commandName = 'help'; -} - -if (args.indexOf('--help') >= 0 || args.indexOf('-h') >= 0) { - args.unshift(commandName); - commandName = 'help'; -} - -// if no args or command name looks like a flag then set default to `install` -if (commandName[0] === '-') { - args.unshift(commandName); - commandName = 'install'; -} - -let command; -if (Object.prototype.hasOwnProperty.call((_index3 || _load_index3()).default, commandName)) { - command = (_index3 || _load_index3()).default[commandName]; -} - -// if command is not recognized, then set default to `run` -if (!command) { - args.unshift(commandName); - command = (_index3 || _load_index3()).default.run; -} - -command.setFlags(commander); -commander.parse([...startArgs, -// we use this for https://github.com/tj/commander.js/issues/346, otherwise -// it will strip some args that match with any options -'this-arg-will-get-stripped-later', ...(0, (_rc || _load_rc()).getRcArgs)(commandName), ...args]); -commander.args = commander.args.concat(endArgs); - -// we strip cmd -console.assert(commander.args.length >= 1); -console.assert(commander.args[0] === 'this-arg-will-get-stripped-later'); -commander.args.shift(); - -// -const Reporter = commander.json ? (_index || _load_index()).JSONReporter : (_index || _load_index()).ConsoleReporter; -const reporter = new Reporter({ - emoji: process.stdout.isTTY && commander.emoji, - verbose: commander.verbose, - noProgress: !commander.progress, - isSilent: process.env.YARN_SILENT === '1' || commander.silent -}); - -reporter.initPeakMemoryCounter(); - -const config = new (_config || _load_config()).default(reporter); -const outputWrapper = !commander.json && command.hasWrapper(commander, commander.args); - -if (outputWrapper) { - reporter.header(commandName, { name: 'yarn', version: (_yarnVersion || _load_yarnVersion()).version }); +// Adapt the sometimes-Async api of tough.CookieJar to our requirements +function RequestJar(store) { + var self = this + self._jar = new CookieJar(store, {looseMode: true}) } - -if (command.noArguments && commander.args.length) { - reporter.error(reporter.lang('noArguments')); - reporter.info(command.getDocsInfo); - process.exit(1); +RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) { + var self = this + return self._jar.setCookieSync(cookieOrStr, uri, options || {}) } - -// -if (commander.yes) { - reporter.warn(reporter.lang('yesWarning')); +RequestJar.prototype.getCookieString = function(uri) { + var self = this + return self._jar.getCookieStringSync(uri) } - -// -if (!commander.offline && (_network || _load_network()).isOffline()) { - reporter.warn(reporter.lang('networkWarning')); +RequestJar.prototype.getCookies = function(uri) { + var self = this + return self._jar.getCookiesSync(uri) } -// -if (command.requireLockfile && !fs.existsSync(path.join(config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME))) { - reporter.error(reporter.lang('noRequiredLockfile')); - process.exit(1); +exports.jar = function(store) { + return new RequestJar(store) } -// -const run = () => { - invariant(command, 'missing command'); - return command.run(config, reporter, commander, commander.args).then(exitCode => { - reporter.close(); - if (outputWrapper) { - reporter.footer(false); - } - return exitCode; - }); -}; - -// -const runEventuallyWithFile = (mutexFilename, isFirstTime) => { - return new Promise(ok => { - const lockFilename = mutexFilename || path.join(config.cwd, (_constants || _load_constants()).SINGLE_INSTANCE_FILENAME); - lockfile.lock(lockFilename, { realpath: false }, (err, release) => { - if (err) { - if (isFirstTime) { - reporter.warn(reporter.lang('waitingInstance')); - } - setTimeout(() => { - ok(runEventuallyWithFile(mutexFilename, false)); - }, 200); // do not starve the CPU - } else { - onDeath(() => { - process.exit(1); - }); - ok(run().then(release)); - } - }); - }); -}; - -// -const runEventuallyWithNetwork = mutexPort => { - return new Promise(ok => { - const connectionOptions = { - port: +mutexPort || (_constants || _load_constants()).SINGLE_INSTANCE_PORT - }; - - const server = net.createServer(); - - server.on('error', () => { - // another Yarn instance exists, let's connect to it to know when it dies. - reporter.warn(reporter.lang('waitingInstance')); - const socket = net.createConnection(connectionOptions); - - socket.on('connect', () => { - // Allow the program to exit if this is the only active server in the event system. - socket.unref(); - }).on('close', hadError => { - // the `close` event gets always called after the `error` event - if (!hadError) { - process.nextTick(() => { - ok(runEventuallyWithNetwork(mutexPort)); - }); - } - }).on('error', () => { - // No server to listen to ? Let's retry to become the next server then. - process.nextTick(() => { - ok(runEventuallyWithNetwork(mutexPort)); - }); - }); - }); - - const onServerEnd = () => { - server.close(); - return Promise.resolve(); - }; - - // open the server and continue only if succeed. - server.listen(connectionOptions, () => { - // ensure the server gets closed properly on SIGNALS. - onDeath(onServerEnd); - ok(run().then(onServerEnd)); - }); - }); -}; +/***/ }), +/* 312 */ +/***/ (function(module, exports, __webpack_require__) { -function onUnexpectedError(err) { - function indent(str) { - return '\n ' + str.trim().split('\n').join('\n '); - } +/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. - const log = []; - log.push(`Arguments: ${indent(process.argv.join(' '))}`); - log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`); - log.push(`Yarn version: ${indent((_yarnVersion || _load_yarnVersion()).version)}`); - log.push(`Node version: ${indent(process.versions.node)}`); - log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`); +;(function (factory) { + var objectTypes = { + 'function': true, + 'object': true + }; - // add manifests - for (const registryName of (_index2 || _load_index2()).registryNames) { - const possibleLoc = path.join(config.cwd, (_index2 || _load_index2()).registries[registryName].filename); - const manifest = fs.existsSync(possibleLoc) ? fs.readFileSync(possibleLoc, 'utf8') : 'No manifest'; - log.push(`${registryName} manifest: ${indent(manifest)}`); + function checkGlobal(value) { + return (value && value.Object === Object) ? value : null; } - // lockfile - const lockLoc = path.join(config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME); - const lockfile = fs.existsSync(lockLoc) ? fs.readFileSync(lockLoc, 'utf8') : 'No lockfile'; - log.push(`Lockfile: ${indent(lockfile)}`); - - log.push(`Trace: ${indent(err.stack)}`); - - const errorReportLoc = writeErrorReport(log); - - reporter.error(reporter.lang('unexpectedError', err.message)); + var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null; + var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null; + var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global); + var freeSelf = checkGlobal(objectTypes[typeof self] && self); + var freeWindow = checkGlobal(objectTypes[typeof window] && window); + var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null; + var thisGlobal = checkGlobal(objectTypes[typeof this] && this); + var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); - if (errorReportLoc) { - reporter.info(reporter.lang('bugReport', errorReportLoc)); + // Because of build optimizers + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + return factory(root, exports, Rx); + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); } -} +}.call(this, function (root, exp, Rx, undefined) { -function writeErrorReport(log) { - const errorReportLoc = config.enableMetaFolder ? path.join(config.cwd, (_constants || _load_constants()).META_FOLDER, 'yarn-error.log') : path.join(config.cwd, 'yarn-error.log'); + var Observable = Rx.Observable, + observableProto = Observable.prototype, + AnonymousObservable = Rx.AnonymousObservable, + ObservableBase = Rx.ObservableBase, + Subject = Rx.Subject, + AsyncSubject = Rx.AsyncSubject, + Observer = Rx.Observer, + ScheduledObserver = Rx.internals.ScheduledObserver, + disposableCreate = Rx.Disposable.create, + disposableEmpty = Rx.Disposable.empty, + BinaryDisposable = Rx.BinaryDisposable, + currentThreadScheduler = Rx.Scheduler.currentThread, + isFunction = Rx.helpers.isFunction, + inherits = Rx.internals.inherits, + addProperties = Rx.internals.addProperties, + checkDisposed = Rx.Disposable.checkDisposed; - try { - fs.writeFileSync(errorReportLoc, log.join('\n\n') + '\n'); - } catch (err) { - reporter.error(reporter.lang('fileWriteError', errorReportLoc, err.message)); - return undefined; + // Utilities + function cloneArray(arr) { + var len = arr.length, a = new Array(len); + for(var i = 0; i < len; i++) { a[i] = arr[i]; } + return a; } - return errorReportLoc; -} - -config.init({ - binLinks: commander.binLinks, - modulesFolder: commander.modulesFolder, - globalFolder: commander.globalFolder, - cacheFolder: commander.cacheFolder, - preferOffline: commander.preferOffline, - captureHar: commander.har, - ignorePlatform: commander.ignorePlatform, - ignoreEngines: commander.ignoreEngines, - ignoreScripts: commander.ignoreScripts, - offline: commander.preferOffline || commander.offline, - looseSemver: !commander.strictSemver, - production: commander.production, - httpProxy: commander.proxy, - httpsProxy: commander.httpsProxy, - networkConcurrency: commander.networkConcurrency, - networkTimeout: commander.networkTimeout, - nonInteractive: commander.nonInteractive, - scriptsPrependNodePath: commander.scriptsPrependNodePath, + var MulticastObservable = (function (__super__) { + inherits(MulticastObservable, __super__); + function MulticastObservable(source, fn1, fn2) { + this.source = source; + this._fn1 = fn1; + this._fn2 = fn2; + __super__.call(this); + } - commandName: commandName === 'run' ? commander.args[0] : commandName -}).then(() => { - // option "no-progress" stored in yarn config - const noProgressConfig = config.registries.yarn.getOption('no-progress'); + MulticastObservable.prototype.subscribeCore = function (o) { + var connectable = this.source.multicast(this._fn1()); + return new BinaryDisposable(this._fn2(connectable).subscribe(o), connectable.connect()); + }; - if (noProgressConfig) { - reporter.disableProgress(); - } + return MulticastObservable; + }(ObservableBase)); - const exit = exitCode => { - process.exit(exitCode || 0); + /** + * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each + * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's + * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. + * + * @example + * 1 - res = source.multicast(observable); + * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); + * + * @param {Function|Subject} subjectOrSubjectSelector + * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + * Or: + * Subject to push source elements into. + * + * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.multicast = function (subjectOrSubjectSelector, selector) { + return isFunction(subjectOrSubjectSelector) ? + new MulticastObservable(this, subjectOrSubjectSelector, selector) : + new ConnectableObservable(this, subjectOrSubjectSelector); }; - // verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer - reporter.verbose(`current time: ${new Date().toISOString()}`); - - const mutex = commander.mutex; - if (mutex && typeof mutex === 'string') { - const parts = mutex.split(':'); - const mutexType = parts.shift(); - const mutexSpecifier = parts.join(':'); - - if (mutexType === 'file') { - return runEventuallyWithFile(mutexSpecifier, true).then(exit); - } else if (mutexType === 'network') { - return runEventuallyWithNetwork(mutexSpecifier).then(exit); - } else { - throw new (_errors || _load_errors()).MessageError(`Unknown single instance type ${mutexType}`); - } - } else { - return run().then(exit); - } -}).catch(err => { - reporter.verbose(err.stack); - - if (err instanceof (_errors || _load_errors()).MessageError) { - reporter.error(err.message); - } else { - onUnexpectedError(err); - } - if ((_index3 || _load_index3()).default[commandName]) { - reporter.info((_index3 || _load_index3()).default[commandName].getDocsInfo); - } - - process.exit(1); -}); + /** + * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. + * This operator is a specialization of Multicast using a regular Subject. + * + * @example + * var resres = source.publish(); + * var res = source.publish(function (x) { return x; }); + * + * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.publish = function (selector) { + return selector && isFunction(selector) ? + this.multicast(function () { return new Subject(); }, selector) : + this.multicast(new Subject()); + }; -/***/ }), -/* 284 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence. + * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + observableProto.share = function () { + return this.publish().refCount(); + }; -"use strict"; + /** + * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. + * This operator is a specialization of Multicast using a AsyncSubject. + * + * @example + * var res = source.publishLast(); + * var res = source.publishLast(function (x) { return x; }); + * + * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.publishLast = function (selector) { + return selector && isFunction(selector) ? + this.multicast(function () { return new AsyncSubject(); }, selector) : + this.multicast(new AsyncSubject()); + }; + /** + * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. + * This operator is a specialization of Multicast using a BehaviorSubject. + * + * @example + * var res = source.publishValue(42); + * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); + * + * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. + * @param {Mixed} initialValue Initial value received by observers upon subscription. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.publishValue = function (initialValueOrSelector, initialValue) { + return arguments.length === 2 ? + this.multicast(function () { + return new BehaviorSubject(initialValue); + }, initialValueOrSelector) : + this.multicast(new BehaviorSubject(initialValueOrSelector)); + }; -var compileSchema = __webpack_require__(289) - , resolve = __webpack_require__(173) - , Cache = __webpack_require__(285) - , SchemaObject = __webpack_require__(174) - , stableStringify = __webpack_require__(156) - , formats = __webpack_require__(288) - , rules = __webpack_require__(290) - , v5 = __webpack_require__(314) - , util = __webpack_require__(42) - , async = __webpack_require__(171) - , co = __webpack_require__(212); + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. + * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * @param {Mixed} initialValue Initial value received by observers upon subscription. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + observableProto.shareValue = function (initialValue) { + return this.publishValue(initialValue).refCount(); + }; -module.exports = Ajv; + /** + * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. + * This operator is a specialization of Multicast using a ReplaySubject. + * + * @example + * var res = source.replay(null, 3); + * var res = source.replay(null, 3, 500); + * var res = source.replay(null, 3, 500, scheduler); + * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); + * + * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. + * @param bufferSize [Optional] Maximum element count of the replay buffer. + * @param windowSize [Optional] Maximum time length of the replay buffer. + * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { + return selector && isFunction(selector) ? + this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : + this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); + }; -Ajv.prototype.compileAsync = async.compile; + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. + * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. + * + * @example + * var res = source.shareReplay(3); + * var res = source.shareReplay(3, 500); + * var res = source.shareReplay(3, 500, scheduler); + * -var customKeyword = __webpack_require__(311); -Ajv.prototype.addKeyword = customKeyword.add; -Ajv.prototype.getKeyword = customKeyword.get; -Ajv.prototype.removeKeyword = customKeyword.remove; -Ajv.ValidationError = __webpack_require__(175); + * @param bufferSize [Optional] Maximum element count of the replay buffer. + * @param window [Optional] Maximum time length of the replay buffer. + * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { + return this.replay(null, bufferSize, windowSize, scheduler).refCount(); + }; -var META_SCHEMA_ID = 'http://json-schema.org/draft-04/schema'; -var SCHEMA_URI_FORMAT = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i; -function SCHEMA_URI_FORMAT_FUNC(str) { - return SCHEMA_URI_FORMAT.test(str); -} + var InnerSubscription = function (s, o) { + this._s = s; + this._o = o; + }; -var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ]; + InnerSubscription.prototype.dispose = function () { + if (!this._s.isDisposed && this._o !== null) { + var idx = this._s.observers.indexOf(this._o); + this._s.observers.splice(idx, 1); + this._o = null; + } + }; -/** - * Creates validator instance. - * Usage: `Ajv(opts)` - * @param {Object} opts optional options - * @return {Object} ajv instance - */ -function Ajv(opts) { - if (!(this instanceof Ajv)) return new Ajv(opts); - var self = this; + /** + * Represents a value that changes over time. + * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. + */ + var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { + inherits(BehaviorSubject, __super__); + function BehaviorSubject(value) { + __super__.call(this); + this.value = value; + this.observers = []; + this.isDisposed = false; + this.isStopped = false; + this.hasError = false; + } - opts = this._opts = util.copy(opts) || {}; - this._schemas = {}; - this._refs = {}; - this._fragments = {}; - this._formats = formats(opts.format); - this._cache = opts.cache || new Cache; - this._loadingSchemas = {}; - this._compilations = []; - this.RULES = rules(); - - // this is done on purpose, so that methods are bound to the instance - // (without using bind) so that they can be used without the instance - this.validate = validate; - this.compile = compile; - this.addSchema = addSchema; - this.addMetaSchema = addMetaSchema; - this.validateSchema = validateSchema; - this.getSchema = getSchema; - this.removeSchema = removeSchema; - this.addFormat = addFormat; - this.errorsText = errorsText; + addProperties(BehaviorSubject.prototype, Observer.prototype, { + _subscribe: function (o) { + checkDisposed(this); + if (!this.isStopped) { + this.observers.push(o); + o.onNext(this.value); + return new InnerSubscription(this, o); + } + if (this.hasError) { + o.onError(this.error); + } else { + o.onCompleted(); + } + return disposableEmpty; + }, + /** + * Gets the current value or throws an exception. + * Value is frozen after onCompleted is called. + * After onError is called always throws the specified exception. + * An exception is always thrown after dispose is called. + * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. + */ + getValue: function () { + checkDisposed(this); + if (this.hasError) { thrower(this.error); } + return this.value; + }, + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onCompleted(); + } - this._addSchema = _addSchema; - this._compile = _compile; + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.hasError = true; + this.error = error; - opts.loopRequired = opts.loopRequired || Infinity; - if (opts.async || opts.transpile) async.setup(opts); - if (opts.beautify === true) opts.beautify = { indent_size: 2 }; - if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; - this._metaOpts = getMetaSchemaOptions(); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onError(error); + } - if (opts.formats) addInitialFormats(); - addDraft4MetaSchema(); - if (opts.v5) v5.enable(this); - if (typeof opts.meta == 'object') addMetaSchema(opts.meta); - addInitialSchemas(); + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + this.value = value; + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + os[i].onNext(value); + } + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + this.value = null; + this.error = null; + } + }); + return BehaviorSubject; + }(Observable)); /** - * Validate data using schema - * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize. - * @param {String|Object} schemaKeyRef key, ref or schema object - * @param {Any} data to be validated - * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + * Represents an object that is both an observable sequence as well as an observer. + * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ - function validate(schemaKeyRef, data) { - var v; - if (typeof schemaKeyRef == 'string') { - v = getSchema(schemaKeyRef); - if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); - } else { - var schemaObj = _addSchema(schemaKeyRef); - v = schemaObj.validate || _compile(schemaObj); - } - - var valid = v(data); - if (v.$async === true) - return self._opts.async == '*' ? co(valid) : valid; - self.errors = v.errors; - return valid; - } + var ReplaySubject = Rx.ReplaySubject = (function (__super__) { + var maxSafeInteger = Math.pow(2, 53) - 1; - /** - * Create validating function for passed schema. - * @param {Object} schema schema object - * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. - * @return {Function} validating function - */ - function compile(schema, _meta) { - var schemaObj = _addSchema(schema, undefined, _meta); - return schemaObj.validate || _compile(schemaObj); - } + function createRemovableDisposable(subject, observer) { + return disposableCreate(function () { + observer.dispose(); + !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); + }); + } + inherits(ReplaySubject, __super__); - /** - * Adds schema to the instance. - * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. - * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. - * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. - * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. - */ - function addSchema(schema, key, _skipValidation, _meta) { - if (Array.isArray(schema)){ - for (var i=0; i<schema.length; i++) addSchema(schema[i], undefined, _skipValidation, _meta); - return; + /** + * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. + * @param {Number} [bufferSize] Maximum element count of the replay buffer. + * @param {Number} [windowSize] Maximum time length of the replay buffer. + * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. + */ + function ReplaySubject(bufferSize, windowSize, scheduler) { + this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; + this.windowSize = windowSize == null ? maxSafeInteger : windowSize; + this.scheduler = scheduler || currentThreadScheduler; + this.q = []; + this.observers = []; + this.isStopped = false; + this.isDisposed = false; + this.hasError = false; + this.error = null; + __super__.call(this); } - // can key/id have # inside? - key = resolve.normalizeId(key || schema.id); - checkUnique(key); - self._schemas[key] = _addSchema(schema, _skipValidation, _meta, true); - } + addProperties(ReplaySubject.prototype, Observer.prototype, { + _subscribe: function (o) { + checkDisposed(this); + var so = new ScheduledObserver(this.scheduler, o), subscription = createRemovableDisposable(this, so); - /** - * Add schema that will be used to validate other schemas - * options in META_IGNORE_OPTIONS are alway set to false - * @param {Object} schema schema object - * @param {String} key optional schema key - * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema - */ - function addMetaSchema(schema, key, skipValidation) { - addSchema(schema, key, skipValidation, true); - } + this._trim(this.scheduler.now()); + this.observers.push(so); + for (var i = 0, len = this.q.length; i < len; i++) { + so.onNext(this.q[i].value); + } - /** - * Validate schema - * @param {Object} schema schema to validate - * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid - * @return {Boolean} true if schema is valid - */ - function validateSchema(schema, throwOrLogError) { - var $schema = schema.$schema || self._opts.defaultMeta || defaultMeta(); - var currentUriFormat = self._formats.uri; - self._formats.uri = typeof currentUriFormat == 'function' - ? SCHEMA_URI_FORMAT_FUNC - : SCHEMA_URI_FORMAT; - var valid; - try { valid = validate($schema, schema); } - finally { self._formats.uri = currentUriFormat; } - if (!valid && throwOrLogError) { - var message = 'schema is invalid: ' + errorsText(); - if (self._opts.validateSchema == 'log') console.error(message); - else throw new Error(message); - } - return valid; - } + if (this.hasError) { + so.onError(this.error); + } else if (this.isStopped) { + so.onCompleted(); + } + so.ensureActive(); + return subscription; + }, + /** + * Indicates whether the subject has observers subscribed to it. + * @returns {Boolean} Indicates whether the subject has observers subscribed to it. + */ + hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, + _trim: function (now) { + while (this.q.length > this.bufferSize) { + this.q.shift(); + } + while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { + this.q.shift(); + } + }, + /** + * Notifies all subscribed observers about the arrival of the specified element in the sequence. + * @param {Mixed} value The value to send to all observers. + */ + onNext: function (value) { + checkDisposed(this); + if (this.isStopped) { return; } + var now = this.scheduler.now(); + this.q.push({ interval: now, value: value }); + this._trim(now); - function defaultMeta() { - var meta = self._opts.meta; - self._opts.defaultMeta = typeof meta == 'object' - ? meta.id || meta - : self._opts.v5 - ? v5.META_SCHEMA_ID - : META_SCHEMA_ID; - return self._opts.defaultMeta; - } + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onNext(value); + observer.ensureActive(); + } + }, + /** + * Notifies all subscribed observers about the exception. + * @param {Mixed} error The exception to send to all observers. + */ + onError: function (error) { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + this.error = error; + this.hasError = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onError(error); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Notifies all subscribed observers about the end of the sequence. + */ + onCompleted: function () { + checkDisposed(this); + if (this.isStopped) { return; } + this.isStopped = true; + var now = this.scheduler.now(); + this._trim(now); + for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { + var observer = os[i]; + observer.onCompleted(); + observer.ensureActive(); + } + this.observers.length = 0; + }, + /** + * Unsubscribe all observers and release resources. + */ + dispose: function () { + this.isDisposed = true; + this.observers = null; + } + }); + return ReplaySubject; + }(Observable)); - /** - * Get compiled schema from the instance by `key` or `ref`. - * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). - * @return {Function} schema validating function (with property `schema`). - */ - function getSchema(keyRef) { - var schemaObj = _getSchemaObj(keyRef); - switch (typeof schemaObj) { - case 'object': return schemaObj.validate || _compile(schemaObj); - case 'string': return getSchema(schemaObj); - case 'undefined': return _getSchemaFragment(keyRef); + var RefCountObservable = (function (__super__) { + inherits(RefCountObservable, __super__); + function RefCountObservable(source) { + this.source = source; + this._count = 0; + this._connectableSubscription = null; + __super__.call(this); } - } + RefCountObservable.prototype.subscribeCore = function (o) { + var subscription = this.source.subscribe(o); + ++this._count === 1 && (this._connectableSubscription = this.source.connect()); + return new RefCountDisposable(this, subscription); + }; - function _getSchemaFragment(ref) { - var res = resolve.schema.call(self, { schema: {} }, ref); - if (res) { - var schema = res.schema - , root = res.root - , baseId = res.baseId; - var v = compileSchema.call(self, schema, root, undefined, baseId); - self._fragments[ref] = new SchemaObject({ - ref: ref, - fragment: true, - schema: schema, - root: root, - baseId: baseId, - validate: v - }); - return v; + function RefCountDisposable(p, s) { + this._p = p; + this._s = s; + this.isDisposed = false; } - } - - function _getSchemaObj(keyRef) { - keyRef = resolve.normalizeId(keyRef); - return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; - } + RefCountDisposable.prototype.dispose = function () { + if (!this.isDisposed) { + this.isDisposed = true; + this._s.dispose(); + --this._p._count === 0 && this._p._connectableSubscription.dispose(); + } + }; + return RefCountObservable; + }(ObservableBase)); - /** - * Remove cached schema(s). - * If no parameter is passed all schemas but meta-schemas are removed. - * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. - * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. - * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object - */ - function removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - _removeAllSchemas(self._schemas, schemaKeyRef); - _removeAllSchemas(self._refs, schemaKeyRef); - return; - } - switch (typeof schemaKeyRef) { - case 'undefined': - _removeAllSchemas(self._schemas); - _removeAllSchemas(self._refs); - self._cache.clear(); - return; - case 'string': - var schemaObj = _getSchemaObj(schemaKeyRef); - if (schemaObj) self._cache.del(schemaObj.jsonStr); - delete self._schemas[schemaKeyRef]; - delete self._refs[schemaKeyRef]; - return; - case 'object': - var jsonStr = stableStringify(schemaKeyRef); - self._cache.del(jsonStr); - var id = schemaKeyRef.id; - if (id) { - id = resolve.normalizeId(id); - delete self._schemas[id]; - delete self._refs[id]; - } + var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { + inherits(ConnectableObservable, __super__); + function ConnectableObservable(source, subject) { + this.source = source; + this._connection = null; + this._source = source.asObservable(); + this._subject = subject; + __super__.call(this); } - } + function ConnectDisposable(parent, subscription) { + this._p = parent; + this._s = subscription; + } - function _removeAllSchemas(schemas, regex) { - for (var keyRef in schemas) { - var schemaObj = schemas[keyRef]; - if (!schemaObj.meta && (!regex || regex.test(keyRef))) { - self._cache.del(schemaObj.jsonStr); - delete schemas[keyRef]; + ConnectDisposable.prototype.dispose = function () { + if (this._s) { + this._s.dispose(); + this._s = null; + this._p._connection = null; } - } - } + }; + ConnectableObservable.prototype.connect = function () { + if (!this._connection) { + if (this._subject.isStopped) { + return disposableEmpty; + } + var subscription = this._source.subscribe(this._subject); + this._connection = new ConnectDisposable(this, subscription); + } + return this._connection; + }; - function _addSchema(schema, skipValidation, meta, shouldAddSchema) { - if (typeof schema != 'object') throw new Error('schema should be object'); - var jsonStr = stableStringify(schema); - var cached = self._cache.get(jsonStr); - if (cached) return cached; + ConnectableObservable.prototype._subscribe = function (o) { + return this._subject.subscribe(o); + }; - shouldAddSchema = shouldAddSchema || self._opts.addUsedSchema !== false; + ConnectableObservable.prototype.refCount = function () { + return new RefCountObservable(this); + }; - var id = resolve.normalizeId(schema.id); - if (id && shouldAddSchema) checkUnique(id); + return ConnectableObservable; + }(Observable)); - var willValidate = self._opts.validateSchema !== false && !skipValidation; - var recursiveMeta; - if (willValidate && !(recursiveMeta = schema.id && schema.id == schema.$schema)) - validateSchema(schema, true); + /** + * Returns an observable sequence that shares a single subscription to the underlying sequence. This observable sequence + * can be resubscribed to, even if all prior subscriptions have ended. (unlike `.publish().refCount()`) + * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source. + */ + observableProto.singleInstance = function() { + var source = this, hasObservable = false, observable; - var localRefs = resolve.ids.call(self, schema); + function getObservable() { + if (!hasObservable) { + hasObservable = true; + observable = source['finally'](function() { hasObservable = false; }).publish().refCount(); + } + return observable; + } - var schemaObj = new SchemaObject({ - id: id, - schema: schema, - localRefs: localRefs, - jsonStr: jsonStr, - meta: meta + return new AnonymousObservable(function(o) { + return getObservable().subscribe(o); }); + }; - if (id[0] != '#' && shouldAddSchema) self._refs[id] = schemaObj; - self._cache.put(jsonStr, schemaObj); + return Rx; +})); - if (willValidate && recursiveMeta) validateSchema(schema, true); +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) - return schemaObj; - } +/***/ }), +/* 313 */ +/***/ (function(module, exports, __webpack_require__) { +/* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. - function _compile(schemaObj, root) { - if (schemaObj.compiling) { - schemaObj.validate = callValidate; - callValidate.schema = schemaObj.schema; - callValidate.errors = null; - callValidate.root = root ? root : callValidate; - if (schemaObj.schema.$async === true) - callValidate.$async = true; - return callValidate; - } - schemaObj.compiling = true; +;(function (factory) { + var objectTypes = { + 'function': true, + 'object': true + }; - var currentOpts; - if (schemaObj.meta) { - currentOpts = self._opts; - self._opts = self._metaOpts; - } + function checkGlobal(value) { + return (value && value.Object === Object) ? value : null; + } - var v; - try { v = compileSchema.call(self, schemaObj.schema, root, schemaObj.localRefs); } - finally { - schemaObj.compiling = false; - if (schemaObj.meta) self._opts = currentOpts; - } + var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null; + var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null; + var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global); + var freeSelf = checkGlobal(objectTypes[typeof self] && self); + var freeWindow = checkGlobal(objectTypes[typeof window] && window); + var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null; + var thisGlobal = checkGlobal(objectTypes[typeof this] && this); + var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')(); - schemaObj.validate = v; - schemaObj.refs = v.refs; - schemaObj.refVal = v.refVal; - schemaObj.root = v.root; - return v; + // Because of build optimizers + if (true) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + return factory(root, exports, Rx); + }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + } else if (typeof module === 'object' && module && module.exports === freeExports) { + module.exports = factory(root, module.exports, require('./rx')); + } else { + root.Rx = factory(root, {}, root.Rx); + } +}.call(this, function (root, exp, Rx, undefined) { + + // Aliases + var Scheduler = Rx.Scheduler, + ScheduledItem = Rx.internals.ScheduledItem, + SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive, + PriorityQueue = Rx.internals.PriorityQueue, + inherits = Rx.internals.inherits, + defaultSubComparer = Rx.helpers.defaultSubComparer, + notImplemented = Rx.helpers.notImplemented; + /** Provides a set of extension methods for virtual time scheduling. */ + var VirtualTimeScheduler = Rx.VirtualTimeScheduler = (function (__super__) { + inherits(VirtualTimeScheduler, __super__); - function callValidate() { - var _validate = schemaObj.validate; - var result = _validate.apply(null, arguments); - callValidate.errors = _validate.errors; - return result; + /** + * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. + * + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function VirtualTimeScheduler(initialClock, comparer) { + this.clock = initialClock; + this.comparer = comparer; + this.isEnabled = false; + this.queue = new PriorityQueue(1024); + __super__.call(this); } - } + var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; - /** - * Convert array of error message objects to string - * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used. - * @param {Object} options optional options with properties `separator` and `dataVar`. - * @return {String} human readable string with all errors descriptions - */ - function errorsText(errors, options) { - errors = errors || self.errors; - if (!errors) return 'No errors'; - options = options || {}; - var separator = options.separator === undefined ? ', ' : options.separator; - var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + VirtualTimeSchedulerPrototype.now = function () { + return this.toAbsoluteTime(this.clock); + }; - var text = ''; - for (var i=0; i<errors.length; i++) { - var e = errors[i]; - if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; - } - return text.slice(0, -separator.length); - } + VirtualTimeSchedulerPrototype.schedule = function (state, action) { + return this.scheduleAbsolute(state, this.clock, action); + }; + VirtualTimeSchedulerPrototype.scheduleFuture = function (state, dueTime, action) { + var dt = dueTime instanceof Date ? + this.toRelativeTime(dueTime - this.now()) : + this.toRelativeTime(dueTime); - /** - * Add custom format - * @param {String} name format name - * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) - */ - function addFormat(name, format) { - if (typeof format == 'string') format = new RegExp(format); - self._formats[name] = format; - } + return this.scheduleRelative(state, dt, action); + }; + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + VirtualTimeSchedulerPrototype.add = notImplemented; - function addDraft4MetaSchema() { - if (self._opts.meta !== false) { - var metaSchema = __webpack_require__(312); - addMetaSchema(metaSchema, META_SCHEMA_ID, true); - self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; - } - } + /** + * Converts an absolute time to a number + * @param {Any} The absolute time. + * @returns {Number} The absolute time in ms + */ + VirtualTimeSchedulerPrototype.toAbsoluteTime = notImplemented; + /** + * Converts the TimeSpan value to a relative virtual time value. + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + VirtualTimeSchedulerPrototype.toRelativeTime = notImplemented; - function addInitialSchemas() { - var optsSchemas = self._opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) addSchema(optsSchemas); - else for (var key in optsSchemas) addSchema(optsSchemas[key], key); - } + /** + * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. + * @param {Mixed} state Initial state passed to the action upon the first iteration. + * @param {Number} period Period for running the work periodically. + * @param {Function} action Action to be executed, potentially updating the state. + * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). + */ + VirtualTimeSchedulerPrototype.schedulePeriodic = function (state, period, action) { + var s = new SchedulePeriodicRecursive(this, state, period, action); + return s.start(); + }; + /** + * Schedules an action to be executed after dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Relative time after which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleRelative = function (state, dueTime, action) { + var runAt = this.add(this.clock, dueTime); + return this.scheduleAbsolute(state, runAt, action); + }; - function addInitialFormats() { - for (var name in self._opts.formats) { - var format = self._opts.formats[name]; - addFormat(name, format); - } - } + /** + * Starts the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.start = function () { + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + } + }; + /** + * Stops the virtual time scheduler. + */ + VirtualTimeSchedulerPrototype.stop = function () { + this.isEnabled = false; + }; - function checkUnique(id) { - if (self._schemas[id] || self._refs[id]) - throw new Error('schema with key or id "' + id + '" already exists'); - } + /** + * Advances the scheduler's clock to the specified time, running all work till that point. + * @param {Number} time Absolute time to advance the scheduler's clock to. + */ + VirtualTimeSchedulerPrototype.advanceTo = function (time) { + var dueToClock = this.comparer(this.clock, time); + if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } + if (!this.isEnabled) { + this.isEnabled = true; + do { + var next = this.getNext(); + if (next !== null && this.comparer(next.dueTime, time) <= 0) { + this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); + next.invoke(); + } else { + this.isEnabled = false; + } + } while (this.isEnabled); + this.clock = time; + } + }; + /** + * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.advanceBy = function (time) { + var dt = this.add(this.clock, time), + dueToClock = this.comparer(this.clock, dt); + if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } + if (dueToClock === 0) { return; } - function getMetaSchemaOptions() { - var metaOpts = util.copy(self._opts); - for (var i=0; i<META_IGNORE_OPTIONS.length; i++) - delete metaOpts[META_IGNORE_OPTIONS[i]]; - return metaOpts; - } -} + this.advanceTo(dt); + }; + /** + * Advances the scheduler's clock by the specified relative time. + * @param {Number} time Relative time to advance the scheduler's clock by. + */ + VirtualTimeSchedulerPrototype.sleep = function (time) { + var dt = this.add(this.clock, time); + if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } -/***/ }), -/* 285 */ -/***/ (function(module, exports, __webpack_require__) { + this.clock = dt; + }; -"use strict"; + /** + * Gets the next scheduled item to be executed. + * @returns {ScheduledItem} The next scheduled item. + */ + VirtualTimeSchedulerPrototype.getNext = function () { + while (this.queue.length > 0) { + var next = this.queue.peek(); + if (next.isCancelled()) { + this.queue.dequeue(); + } else { + return next; + } + } + return null; + }; + /** + * Schedules an action to be executed at dueTime. + * @param {Mixed} state State passed to the action to be executed. + * @param {Number} dueTime Absolute time at which to execute the action. + * @param {Function} action Action to be executed. + * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). + */ + VirtualTimeSchedulerPrototype.scheduleAbsolute = function (state, dueTime, action) { + var self = this; + function run(scheduler, state1) { + self.queue.remove(si); + return action(scheduler, state1); + } -var Cache = module.exports = function Cache() { - this._cache = {}; -}; + var si = new ScheduledItem(this, state, run, dueTime, this.comparer); + this.queue.enqueue(si); + return si.disposable; + }; -Cache.prototype.put = function Cache_put(key, value) { - this._cache[key] = value; -}; + return VirtualTimeScheduler; + }(Scheduler)); + /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ + Rx.HistoricalScheduler = (function (__super__) { + inherits(HistoricalScheduler, __super__); -Cache.prototype.get = function Cache_get(key) { - return this._cache[key]; -}; + /** + * Creates a new historical scheduler with the specified initial clock value. + * @constructor + * @param {Number} initialClock Initial value for the clock. + * @param {Function} comparer Comparer to determine causality of events based on absolute time. + */ + function HistoricalScheduler(initialClock, comparer) { + var clock = initialClock == null ? 0 : initialClock; + var cmp = comparer || defaultSubComparer; + __super__.call(this, clock, cmp); + } + var HistoricalSchedulerProto = HistoricalScheduler.prototype; -Cache.prototype.del = function Cache_del(key) { - delete this._cache[key]; -}; + /** + * Adds a relative time value to an absolute time value. + * @param {Number} absolute Absolute virtual time value. + * @param {Number} relative Relative virtual time value to add. + * @return {Number} Resulting absolute virtual time sum value. + */ + HistoricalSchedulerProto.add = function (absolute, relative) { + return absolute + relative; + }; + HistoricalSchedulerProto.toAbsoluteTime = function (absolute) { + return new Date(absolute).getTime(); + }; -Cache.prototype.clear = function Cache_clear() { - this._cache = {}; -}; + /** + * Converts the TimeSpan value to a relative virtual time value. + * @memberOf HistoricalScheduler + * @param {Number} timeSpan TimeSpan value to convert. + * @return {Number} Corresponding relative virtual time value. + */ + HistoricalSchedulerProto.toRelativeTime = function (timeSpan) { + return timeSpan; + }; + return HistoricalScheduler; + }(Rx.VirtualTimeScheduler)); -/***/ }), -/* 286 */ -/***/ (function(module, exports) { + return Rx; +})); -function webpackEmptyContext(req) { - throw new Error("Cannot find module '" + req + "'."); -} -webpackEmptyContext.keys = function() { return []; }; -webpackEmptyContext.resolve = webpackEmptyContext; -module.exports = webpackEmptyContext; -webpackEmptyContext.id = 286; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 287 */ +/* 314 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Note: since nyc uses this module to output coverage, any lines +// that are in the direct sync flow of nyc's outputCoverage are +// ignored, since we can never get coverage for them. +var assert = __webpack_require__(18) +var signals = __webpack_require__(626) +var EE = __webpack_require__(46) +/* istanbul ignore if */ +if (typeof EE !== 'function') { + EE = EE.EventEmitter +} -//all requires must be explicit because browserify won't work with dynamic requires -module.exports = { - '$ref': __webpack_require__(307), - allOf: __webpack_require__(293), - anyOf: __webpack_require__(294), - dependencies: __webpack_require__(297), - 'enum': __webpack_require__(298), - format: __webpack_require__(299), - items: __webpack_require__(300), - maximum: __webpack_require__(176), - minimum: __webpack_require__(176), - maxItems: __webpack_require__(177), - minItems: __webpack_require__(177), - maxLength: __webpack_require__(178), - minLength: __webpack_require__(178), - maxProperties: __webpack_require__(179), - minProperties: __webpack_require__(179), - multipleOf: __webpack_require__(301), - not: __webpack_require__(302), - oneOf: __webpack_require__(303), - pattern: __webpack_require__(304), - properties: __webpack_require__(306), - required: __webpack_require__(308), - uniqueItems: __webpack_require__(310), - validate: __webpack_require__(180) -}; +var emitter +if (process.__signal_exit_emitter__) { + emitter = process.__signal_exit_emitter__ +} else { + emitter = process.__signal_exit_emitter__ = new EE() + emitter.count = 0 + emitter.emitted = {} +} +// Because this emitter is a global, we have to check to see if a +// previous version of this library failed to enable infinite listeners. +// I know what you're about to say. But literally everything about +// signal-exit is a compromise with evil. Get used to it. +if (!emitter.infinite) { + emitter.setMaxListeners(Infinity) + emitter.infinite = true +} -/***/ }), -/* 288 */ -/***/ (function(module, exports, __webpack_require__) { +module.exports = function (cb, opts) { + assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler') -"use strict"; + if (loaded === false) { + load() + } + var ev = 'exit' + if (opts && opts.alwaysLast) { + ev = 'afterexit' + } -var util = __webpack_require__(42); + var remove = function () { + emitter.removeListener(ev, cb) + if (emitter.listeners('exit').length === 0 && + emitter.listeners('afterexit').length === 0) { + unload() + } + } + emitter.on(ev, cb) -var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/; -var DAYS = [0,31,29,31,30,31,30,31,31,30,31,30,31]; -var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i; -var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i; -var URI = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i; -var UUID = /^(?:urn\:uuid\:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; -var JSON_POINTER = /^(?:\/(?:[^~\/]|~0|~1)*)*$|^\#(?:\/(?:[a-z0-9_\-\.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; -var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:\#|(?:\/(?:[^~\/]|~0|~1)*)*)$/; + return remove +} +module.exports.unload = unload +function unload () { + if (!loaded) { + return + } + loaded = false -module.exports = formats; + signals.forEach(function (sig) { + try { + process.removeListener(sig, sigListeners[sig]) + } catch (er) {} + }) + process.emit = originalProcessEmit + process.reallyExit = originalProcessReallyExit + emitter.count -= 1 +} -function formats(mode) { - mode = mode == 'full' ? 'full' : 'fast'; - var formatDefs = util.copy(formats[mode]); - for (var fName in formats.compare) { - formatDefs[fName] = { - validate: formatDefs[fName], - compare: formats.compare[fName] - }; +function emit (event, code, signal) { + if (emitter.emitted[event]) { + return } - return formatDefs; + emitter.emitted[event] = true + emitter.emit(event, code, signal) } +// { <signal>: <listener fn>, ... } +var sigListeners = {} +signals.forEach(function (sig) { + sigListeners[sig] = function listener () { + // If there are no other listeners, an exit is coming! + // Simplest way: remove us and then re-send the signal. + // We know that this will kill the process, so we can + // safely emit now. + var listeners = process.listeners(sig) + if (listeners.length === emitter.count) { + unload() + emit('exit', null, sig) + /* istanbul ignore next */ + emit('afterexit', null, sig) + /* istanbul ignore next */ + process.kill(process.pid, sig) + } + } +}) -formats.fast = { - // date: http://tools.ietf.org/html/rfc3339#section-5.6 - date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, - // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 - time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i, - 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i, - // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js - uri: /^(?:[a-z][a-z0-9+-.]*)?(?:\:|\/)\/?[^\s]*$/i, - // email (sources from jsen validator): - // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 - // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') - email: /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, - hostname: HOSTNAME, - // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses - ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, - regex: regex, - // uuid: http://tools.ietf.org/html/rfc4122 - uuid: UUID, - // JSON-pointer: https://tools.ietf.org/html/rfc6901 - // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A - 'json-pointer': JSON_POINTER, - // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 - 'relative-json-pointer': RELATIVE_JSON_POINTER -}; - +module.exports.signals = function () { + return signals +} -formats.full = { - date: date, - time: time, - 'date-time': date_time, - uri: uri, - email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: hostname, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, - ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, - regex: regex, - uuid: UUID, - 'json-pointer': JSON_POINTER, - 'relative-json-pointer': RELATIVE_JSON_POINTER -}; +module.exports.load = load +var loaded = false -formats.compare = { - date: compareDate, - time: compareTime, - 'date-time': compareDateTime -}; +function load () { + if (loaded) { + return + } + loaded = true + // This is the number of onSignalExit's that are in play. + // It's important so that we can count the correct number of + // listeners on signals, and don't wait for the other one to + // handle it instead of us. + emitter.count += 1 -function date(str) { - // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 - var matches = str.match(DATE); - if (!matches) return false; + signals = signals.filter(function (sig) { + try { + process.on(sig, sigListeners[sig]) + return true + } catch (er) { + return false + } + }) - var month = +matches[1]; - var day = +matches[2]; - return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month]; + process.emit = processEmit + process.reallyExit = processReallyExit } - -function time(str, full) { - var matches = str.match(TIME); - if (!matches) return false; - - var hour = matches[1]; - var minute = matches[2]; - var second = matches[3]; - var timeZone = matches[5]; - return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone); +var originalProcessReallyExit = process.reallyExit +function processReallyExit (code) { + process.exitCode = code || 0 + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + /* istanbul ignore next */ + originalProcessReallyExit.call(process, process.exitCode) } - -var DATE_TIME_SEPARATOR = /t|\s/i; -function date_time(str) { - // http://tools.ietf.org/html/rfc3339#section-5.6 - var dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +var originalProcessEmit = process.emit +function processEmit (ev, arg) { + if (ev === 'exit') { + if (arg !== undefined) { + process.exitCode = arg + } + var ret = originalProcessEmit.apply(this, arguments) + emit('exit', process.exitCode, null) + /* istanbul ignore next */ + emit('afterexit', process.exitCode, null) + return ret + } else { + return originalProcessEmit.apply(this, arguments) + } } -function hostname(str) { - // https://tools.ietf.org/html/rfc1034#section-3.5 - // https://tools.ietf.org/html/rfc1123#section-2 - return str.length <= 255 && HOSTNAME.test(str); -} - +/***/ }), +/* 315 */ +/***/ (function(module, exports, __webpack_require__) { -var NOT_URI_FRAGMENT = /\/|\:/; -function uri(str) { - // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." - return NOT_URI_FRAGMENT.test(str) && URI.test(str); -} +module.exports = __webpack_require__(627); +/***/ }), +/* 316 */ +/***/ (function(module, exports, __webpack_require__) { -function regex(str) { - try { - new RegExp(str); - return true; - } catch(e) { - return false; - } -} +// Copyright 2017 Joyent, Inc. +module.exports = { + DiffieHellman: DiffieHellman, + generateECDSA: generateECDSA, + generateED25519: generateED25519 +}; -function compareDate(d1, d2) { - if (!(d1 && d2)) return; - if (d1 > d2) return 1; - if (d1 < d2) return -1; - if (d1 === d2) return 0; -} +var assert = __webpack_require__(11); +var crypto = __webpack_require__(8); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); +var ed; +var nacl; +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); -function compareTime(t1, t2) { - if (!(t1 && t2)) return; - t1 = t1.match(TIME); - t2 = t2.match(TIME); - if (!(t1 && t2)) return; - t1 = t1[1] + t1[2] + t1[3] + (t1[4]||''); - t2 = t2[1] + t2[2] + t2[3] + (t2[4]||''); - if (t1 > t2) return 1; - if (t1 < t2) return -1; - if (t1 === t2) return 0; -} +var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined); +var ecdh, ec, jsbn; -function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return; - dt1 = dt1.split(DATE_TIME_SEPARATOR); - dt2 = dt2.split(DATE_TIME_SEPARATOR); - var res = compareDate(dt1[0], dt2[0]); - if (res === undefined) return; - return res || compareTime(dt1[1], dt2[1]); -} +function DiffieHellman(key) { + utils.assertCompatible(key, Key, [1, 4], 'key'); + this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]); + this._algo = key.type; + this._curve = key.curve; + this._key = key; + if (key.type === 'dsa') { + if (!CRYPTO_HAVE_ECDH) { + throw (new Error('Due to bugs in the node 0.10 ' + + 'crypto API, node 0.12.x or later is required ' + + 'to use DH')); + } + this._dh = crypto.createDiffieHellman( + key.part.p.data, undefined, + key.part.g.data, undefined); + this._p = key.part.p; + this._g = key.part.g; + if (this._isPriv) + this._dh.setPrivateKey(key.part.x.data); + this._dh.setPublicKey(key.part.y.data); + } else if (key.type === 'ecdsa') { + if (!CRYPTO_HAVE_ECDH) { + if (ecdh === undefined) + ecdh = __webpack_require__(284); + if (ec === undefined) + ec = __webpack_require__(130); + if (jsbn === undefined) + jsbn = __webpack_require__(56).BigInteger; -/***/ }), -/* 289 */ -/***/ (function(module, exports, __webpack_require__) { + this._ecParams = new X9ECParameters(this._curve); -"use strict"; + if (this._isPriv) { + this._priv = new ECPrivate( + this._ecParams, key.part.d.data); + } + return; + } + var curve = { + 'nistp256': 'prime256v1', + 'nistp384': 'secp384r1', + 'nistp521': 'secp521r1' + }[key.curve]; + this._dh = crypto.createECDH(curve); + if (typeof (this._dh) !== 'object' || + typeof (this._dh.setPrivateKey) !== 'function') { + CRYPTO_HAVE_ECDH = false; + DiffieHellman.call(this, key); + return; + } + if (this._isPriv) + this._dh.setPrivateKey(key.part.d.data); + this._dh.setPublicKey(key.part.Q.data); -var resolve = __webpack_require__(173) - , util = __webpack_require__(42) - , stableStringify = __webpack_require__(156) - , async = __webpack_require__(171); + } else if (key.type === 'curve25519') { + if (ed === undefined) + ed = __webpack_require__(215); -var beautify; + if (this._isPriv) { + this._priv = key.part.r.data; + if (this._priv[0] === 0x00) + this._priv = this._priv.slice(1); + this._priv = this._priv.slice(0, 32); + } -function loadBeautify(){ - if (beautify === undefined) { - var name = 'js-beautify'; - try { beautify = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()).js_beautify; } - catch(e) { beautify = false; } - } + } else { + throw (new Error('DH not supported for ' + key.type + ' keys')); + } } -var validateGenerator = __webpack_require__(180); +DiffieHellman.prototype.getPublicKey = function () { + if (this._isPriv) + return (this._key.toPublic()); + return (this._key); +}; -/** - * Functions below are used inside compiled validations function - */ +DiffieHellman.prototype.getPrivateKey = function () { + if (this._isPriv) + return (this._key); + else + return (undefined); +}; +DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey; -var co = __webpack_require__(212); -var ucs2length = util.ucs2length; -var equal = __webpack_require__(172); +DiffieHellman.prototype._keyCheck = function (pk, isPub) { + assert.object(pk, 'key'); + if (!isPub) + utils.assertCompatible(pk, PrivateKey, [1, 3], 'key'); + utils.assertCompatible(pk, Key, [1, 4], 'key'); -// this error is thrown by async schemas to return validation errors via exception -var ValidationError = __webpack_require__(175); + if (pk.type !== this._algo) { + throw (new Error('A ' + pk.type + ' key cannot be used in ' + + this._algo + ' Diffie-Hellman')); + } -module.exports = compile; + if (pk.curve !== this._curve) { + throw (new Error('A key from the ' + pk.curve + ' curve ' + + 'cannot be used with a ' + this._curve + + ' Diffie-Hellman')); + } + if (pk.type === 'dsa') { + assert.deepEqual(pk.part.p, this._p, + 'DSA key prime does not match'); + assert.deepEqual(pk.part.g, this._g, + 'DSA key generator does not match'); + } +}; -/** - * Compiles schema to validation function - * @this Ajv - * @param {Object} schema schema object - * @param {Object} root object with information about the root schema for this schema - * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution - * @param {String} baseId base ID for IDs in the schema - * @return {Function} validation function - */ -function compile(schema, root, localRefs, baseId) { - /* jshint validthis: true, evil: true */ - /* eslint no-shadow: 0 */ - var self = this - , opts = this._opts - , refVal = [ undefined ] - , refs = {} - , patterns = [] - , patternsHash = {} - , defaults = [] - , defaultsHash = {} - , customRules = [] - , keepSourceCode = opts.sourceCode !== false; +DiffieHellman.prototype.setKey = function (pk) { + this._keyCheck(pk); - root = root || { schema: schema, refVal: refVal, refs: refs }; + if (pk.type === 'dsa') { + this._dh.setPrivateKey(pk.part.x.data); + this._dh.setPublicKey(pk.part.y.data); - var c = checkCompiling.call(this, schema, root, baseId); - var compilation = this._compilations[c.index]; - if (c.compiling) return (compilation.callValidate = callValidate); + } else if (pk.type === 'ecdsa') { + if (CRYPTO_HAVE_ECDH) { + this._dh.setPrivateKey(pk.part.d.data); + this._dh.setPublicKey(pk.part.Q.data); + } else { + this._priv = new ECPrivate( + this._ecParams, pk.part.d.data); + } - var formats = this._formats; - var RULES = this.RULES; + } else if (pk.type === 'curve25519') { + this._priv = pk.part.r.data; + if (this._priv[0] === 0x00) + this._priv = this._priv.slice(1); + this._priv = this._priv.slice(0, 32); + } + this._key = pk; + this._isPriv = true; +}; +DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey; - try { - var v = localCompile(schema, root, localRefs, baseId); - compilation.validate = v; - var cv = compilation.callValidate; - if (cv) { - cv.schema = v.schema; - cv.errors = null; - cv.refs = v.refs; - cv.refVal = v.refVal; - cv.root = v.root; - cv.$async = v.$async; - if (keepSourceCode) cv.sourceCode = v.sourceCode; - } - return v; - } finally { - endCompiling.call(this, schema, root, baseId); - } +DiffieHellman.prototype.computeSecret = function (otherpk) { + this._keyCheck(otherpk, true); + if (!this._isPriv) + throw (new Error('DH exchange has not been initialized with ' + + 'a private key yet')); - function callValidate() { - var validate = compilation.validate; - var result = validate.apply(null, arguments); - callValidate.errors = validate.errors; - return result; - } + var pub; + if (this._algo === 'dsa') { + return (this._dh.computeSecret( + otherpk.part.y.data)); - function localCompile(_schema, _root, localRefs, baseId) { - var isRoot = !_root || (_root && _root.schema == _schema); - if (_root.schema != root.schema) - return compile.call(self, _schema, _root, localRefs, baseId); + } else if (this._algo === 'ecdsa') { + if (CRYPTO_HAVE_ECDH) { + return (this._dh.computeSecret( + otherpk.part.Q.data)); + } else { + pub = new ECPublic( + this._ecParams, otherpk.part.Q.data); + return (this._priv.deriveSharedSecret(pub)); + } - var $async = _schema.$async === true; - if ($async && !opts.transpile) async.setup(opts); + } else if (this._algo === 'curve25519') { + pub = otherpk.part.R.data; + if (pub[0] === 0x00) + pub = pub.slice(1); - var sourceCode = validateGenerator({ - isTop: true, - schema: _schema, - isRoot: isRoot, - baseId: baseId, - root: _root, - schemaPath: '', - errSchemaPath: '#', - errorPath: '""', - RULES: RULES, - validate: validateGenerator, - util: util, - resolve: resolve, - resolveRef: resolveRef, - usePattern: usePattern, - useDefault: useDefault, - useCustomRule: useCustomRule, - opts: opts, - formats: formats, - self: self - }); + var secret = ed.dh.computeKey( + this._priv.toString('binary'), + pub.toString('binary')); - sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) - + vars(defaults, defaultCode) + vars(customRules, customRuleCode) - + sourceCode; + return (new Buffer(secret, 'binary')); + } - if (opts.beautify) { - loadBeautify(); - /* istanbul ignore else */ - if (beautify) sourceCode = beautify(sourceCode, opts.beautify); - else console.error('"npm install js-beautify" to use beautify option'); - } - // console.log('\n\n\n *** \n', sourceCode); - var validate, validateCode - , transpile = opts._transpileFunc; - try { - validateCode = $async && transpile - ? transpile(sourceCode) - : sourceCode; + throw (new Error('Invalid algorithm: ' + this._algo)); +}; - var makeValidate = new Function( - 'self', - 'RULES', - 'formats', - 'root', - 'refVal', - 'defaults', - 'customRules', - 'co', - 'equal', - 'ucs2length', - 'ValidationError', - validateCode - ); +DiffieHellman.prototype.generateKey = function () { + var parts = []; + var priv, pub; + if (this._algo === 'dsa') { + this._dh.generateKeys(); - validate = makeValidate( - self, - RULES, - formats, - root, - refVal, - defaults, - customRules, - co, - equal, - ucs2length, - ValidationError - ); + parts.push({name: 'p', data: this._p.data}); + parts.push({name: 'q', data: this._key.part.q.data}); + parts.push({name: 'g', data: this._g.data}); + parts.push({name: 'y', data: this._dh.getPublicKey()}); + parts.push({name: 'x', data: this._dh.getPrivateKey()}); + this._key = new PrivateKey({ + type: 'dsa', + parts: parts + }); + this._isPriv = true; + return (this._key); - refVal[0] = validate; - } catch(e) { - console.error('Error compiling schema, function code:', validateCode); - throw e; - } + } else if (this._algo === 'ecdsa') { + if (CRYPTO_HAVE_ECDH) { + this._dh.generateKeys(); - validate.schema = _schema; - validate.errors = null; - validate.refs = refs; - validate.refVal = refVal; - validate.root = isRoot ? validate : _root; - if ($async) validate.$async = true; - if (keepSourceCode) validate.sourceCode = sourceCode; - if (opts.sourceCode === true) { - validate.source = { - patterns: patterns, - defaults: defaults - }; - } + parts.push({name: 'curve', + data: new Buffer(this._curve)}); + parts.push({name: 'Q', data: this._dh.getPublicKey()}); + parts.push({name: 'd', data: this._dh.getPrivateKey()}); + this._key = new PrivateKey({ + type: 'ecdsa', + curve: this._curve, + parts: parts + }); + this._isPriv = true; + return (this._key); - return validate; - } + } else { + var n = this._ecParams.getN(); + var r = new jsbn(crypto.randomBytes(n.bitLength())); + var n1 = n.subtract(jsbn.ONE); + priv = r.mod(n1).add(jsbn.ONE); + pub = this._ecParams.getG().multiply(priv); - function resolveRef(baseId, ref, isRoot) { - ref = resolve.url(baseId, ref); - var refIndex = refs[ref]; - var _refVal, refCode; - if (refIndex !== undefined) { - _refVal = refVal[refIndex]; - refCode = 'refVal[' + refIndex + ']'; - return resolvedRef(_refVal, refCode); - } - if (!isRoot && root.refs) { - var rootRefId = root.refs[ref]; - if (rootRefId !== undefined) { - _refVal = root.refVal[rootRefId]; - refCode = addLocalRef(ref, _refVal); - return resolvedRef(_refVal, refCode); - } - } + priv = new Buffer(priv.toByteArray()); + pub = new Buffer(this._ecParams.getCurve(). + encodePointHex(pub), 'hex'); - refCode = addLocalRef(ref); - var v = resolve.call(self, localCompile, root, ref); - if (!v) { - var localSchema = localRefs && localRefs[ref]; - if (localSchema) { - v = resolve.inlineRef(localSchema, opts.inlineRefs) - ? localSchema - : compile.call(self, localSchema, root, localRefs, baseId); - } - } + this._priv = new ECPrivate(this._ecParams, priv); - if (v) { - replaceLocalRef(ref, v); - return resolvedRef(v, refCode); - } - } + parts.push({name: 'curve', + data: new Buffer(this._curve)}); + parts.push({name: 'Q', data: pub}); + parts.push({name: 'd', data: priv}); - function addLocalRef(ref, v) { - var refId = refVal.length; - refVal[refId] = v; - refs[ref] = refId; - return 'refVal' + refId; - } - - function replaceLocalRef(ref, v) { - var refId = refs[ref]; - refVal[refId] = v; - } - - function resolvedRef(refVal, code) { - return typeof refVal == 'object' - ? { code: code, schema: refVal, inline: true } - : { code: code, $async: refVal && refVal.$async }; - } + this._key = new PrivateKey({ + type: 'ecdsa', + curve: this._curve, + parts: parts + }); + this._isPriv = true; + return (this._key); + } - function usePattern(regexStr) { - var index = patternsHash[regexStr]; - if (index === undefined) { - index = patternsHash[regexStr] = patterns.length; - patterns[index] = regexStr; - } - return 'pattern' + index; - } + } else if (this._algo === 'curve25519') { + priv = ed.dh.generateKey(); + pub = ed.dh.publicKey(priv); + this._priv = priv = new Buffer(priv, 'binary'); + pub = new Buffer(pub, 'binary'); - function useDefault(value) { - switch (typeof value) { - case 'boolean': - case 'number': - return '' + value; - case 'string': - return util.toQuotedString(value); - case 'object': - if (value === null) return 'null'; - var valueStr = stableStringify(value); - var index = defaultsHash[valueStr]; - if (index === undefined) { - index = defaultsHash[valueStr] = defaults.length; - defaults[index] = value; - } - return 'default' + index; - } - } + parts.push({name: 'R', data: pub}); + parts.push({name: 'r', data: Buffer.concat([priv, pub])}); + this._key = new PrivateKey({ + type: 'curve25519', + parts: parts + }); + this._isPriv = true; + return (this._key); + } - function useCustomRule(rule, schema, parentSchema, it) { - var validateSchema = rule.definition.validateSchema; - if (validateSchema && self._opts.validateSchema !== false) { - var valid = validateSchema(schema); - if (!valid) { - var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); - if (self._opts.validateSchema == 'log') console.error(message); - else throw new Error(message); - } - } + throw (new Error('Invalid algorithm: ' + this._algo)); +}; +DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey; - var compile = rule.definition.compile - , inline = rule.definition.inline - , macro = rule.definition.macro; +/* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */ - var validate; - if (compile) { - validate = compile.call(self, schema, parentSchema, it); - } else if (macro) { - validate = macro.call(self, schema, parentSchema, it); - if (opts.validateSchema !== false) self.validateSchema(validate, true); - } else if (inline) { - validate = inline.call(self, it, rule.keyword, schema, parentSchema); - } else { - validate = rule.definition.validate; - } +function X9ECParameters(name) { + var params = algs.curves[name]; + assert.object(params); - var index = customRules.length; - customRules[index] = validate; + var p = new jsbn(params.p); + var a = new jsbn(params.a); + var b = new jsbn(params.b); + var n = new jsbn(params.n); + var h = jsbn.ONE; + var curve = new ec.ECCurveFp(p, a, b); + var G = curve.decodePointHex(params.G.toString('hex')); - return { - code: 'customRule' + index, - validate: validate - }; - } + this.curve = curve; + this.g = G; + this.n = n; + this.h = h; } +X9ECParameters.prototype.getCurve = function () { return (this.curve); }; +X9ECParameters.prototype.getG = function () { return (this.g); }; +X9ECParameters.prototype.getN = function () { return (this.n); }; +X9ECParameters.prototype.getH = function () { return (this.h); }; +function ECPublic(params, buffer) { + this._params = params; + if (buffer[0] === 0x00) + buffer = buffer.slice(1); + this._pub = params.getCurve().decodePointHex(buffer.toString('hex')); +} -/** - * Checks if the schema is currently compiled - * @this Ajv - * @param {Object} schema schema to compile - * @param {Object} root root object - * @param {String} baseId base schema ID - * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) - */ -function checkCompiling(schema, root, baseId) { - /* jshint validthis: true */ - var index = compIndex.call(this, schema, root, baseId); - if (index >= 0) return { index: index, compiling: true }; - index = this._compilations.length; - this._compilations[index] = { - schema: schema, - root: root, - baseId: baseId - }; - return { index: index, compiling: false }; +function ECPrivate(params, buffer) { + this._params = params; + this._priv = new jsbn(utils.mpNormalize(buffer)); } +ECPrivate.prototype.deriveSharedSecret = function (pubKey) { + assert.ok(pubKey instanceof ECPublic); + var S = pubKey._pub.multiply(this._priv); + return (new Buffer(S.getX().toBigInteger().toByteArray())); +}; +function generateED25519() { + if (nacl === undefined) + nacl = __webpack_require__(146); -/** - * Removes the schema from the currently compiled list - * @this Ajv - * @param {Object} schema schema to compile - * @param {Object} root root object - * @param {String} baseId base schema ID - */ -function endCompiling(schema, root, baseId) { - /* jshint validthis: true */ - var i = compIndex.call(this, schema, root, baseId); - if (i >= 0) this._compilations.splice(i, 1); + var pair = nacl.sign.keyPair(); + var priv = new Buffer(pair.secretKey); + var pub = new Buffer(pair.publicKey); + assert.strictEqual(priv.length, 64); + assert.strictEqual(pub.length, 32); + + var parts = []; + parts.push({name: 'R', data: pub}); + parts.push({name: 'r', data: priv}); + var key = new PrivateKey({ + type: 'ed25519', + parts: parts + }); + return (key); } +/* Generates a new ECDSA private key on a given curve. */ +function generateECDSA(curve) { + var parts = []; + var key; -/** - * Index of schema compilation in the currently compiled list - * @this Ajv - * @param {Object} schema schema to compile - * @param {Object} root root object - * @param {String} baseId base schema ID - * @return {Integer} compilation index - */ -function compIndex(schema, root, baseId) { - /* jshint validthis: true */ - for (var i=0; i<this._compilations.length; i++) { - var c = this._compilations[i]; - if (c.schema == schema && c.root == root && c.baseId == baseId) return i; - } - return -1; -} + if (CRYPTO_HAVE_ECDH) { + /* + * Node crypto doesn't expose key generation directly, but the + * ECDH instances can generate keys. It turns out this just + * calls into the OpenSSL generic key generator, and we can + * read its output happily without doing an actual DH. So we + * use that here. + */ + var osCurve = { + 'nistp256': 'prime256v1', + 'nistp384': 'secp384r1', + 'nistp521': 'secp521r1' + }[curve]; + var dh = crypto.createECDH(osCurve); + dh.generateKeys(); -function patternCode(i, patterns) { - return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');'; -} + parts.push({name: 'curve', + data: new Buffer(curve)}); + parts.push({name: 'Q', data: dh.getPublicKey()}); + parts.push({name: 'd', data: dh.getPrivateKey()}); + key = new PrivateKey({ + type: 'ecdsa', + curve: curve, + parts: parts + }); + return (key); -function defaultCode(i) { - return 'var default' + i + ' = defaults[' + i + '];'; -} + } else { + if (ecdh === undefined) + ecdh = __webpack_require__(284); + if (ec === undefined) + ec = __webpack_require__(130); + if (jsbn === undefined) + jsbn = __webpack_require__(56).BigInteger; + var ecParams = new X9ECParameters(curve); -function refValCode(i, refVal) { - return refVal[i] ? 'var refVal' + i + ' = refVal[' + i + '];' : ''; -} + /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */ + var n = ecParams.getN(); + /* + * The crypto.randomBytes() function can only give us whole + * bytes, so taking a nod from X9.62, we round up. + */ + var cByteLen = Math.ceil((n.bitLength() + 64) / 8); + var c = new jsbn(crypto.randomBytes(cByteLen)); + var n1 = n.subtract(jsbn.ONE); + var priv = c.mod(n1).add(jsbn.ONE); + var pub = ecParams.getG().multiply(priv); -function customRuleCode(i) { - return 'var customRule' + i + ' = customRules[' + i + '];'; -} + priv = new Buffer(priv.toByteArray()); + pub = new Buffer(ecParams.getCurve(). + encodePointHex(pub), 'hex'); + parts.push({name: 'curve', data: new Buffer(curve)}); + parts.push({name: 'Q', data: pub}); + parts.push({name: 'd', data: priv}); -function vars(arr, statement) { - if (!arr.length) return ''; - var code = ''; - for (var i=0; i<arr.length; i++) - code += statement(i, arr); - return code; + key = new PrivateKey({ + type: 'ecdsa', + curve: curve, + parts: parts + }); + return (key); + } } /***/ }), -/* 290 */ +/* 317 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Copyright 2015 Joyent, Inc. +module.exports = { + Verifier: Verifier, + Signer: Signer +}; -var ruleModules = __webpack_require__(287) - , toHash = __webpack_require__(42).toHash; +var nacl; +var stream = __webpack_require__(26); +var util = __webpack_require__(2); +var assert = __webpack_require__(11); +var Signature = __webpack_require__(45); -module.exports = function rules() { - var RULES = [ - { type: 'number', - rules: [ 'maximum', 'minimum', 'multipleOf'] }, - { type: 'string', - rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, - { type: 'array', - rules: [ 'maxItems', 'minItems', 'uniqueItems', 'items' ] }, - { type: 'object', - rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'properties' ] }, - { rules: [ '$ref', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] } - ]; +function Verifier(key, hashAlgo) { + if (nacl === undefined) + nacl = __webpack_require__(146); - var ALL = [ 'type', 'additionalProperties', 'patternProperties' ]; - var KEYWORDS = [ 'additionalItems', '$schema', 'id', 'title', 'description', 'default' ]; - var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; - RULES.all = toHash(ALL); + if (hashAlgo.toLowerCase() !== 'sha512') + throw (new Error('ED25519 only supports the use of ' + + 'SHA-512 hashes')); - RULES.forEach(function (group) { - group.rules = group.rules.map(function (keyword) { - ALL.push(keyword); - var rule = RULES.all[keyword] = { - keyword: keyword, - code: ruleModules[keyword] - }; - return rule; - }); - }); + this.key = key; + this.chunks = []; - RULES.keywords = toHash(ALL.concat(KEYWORDS)); - RULES.types = toHash(TYPES); - RULES.custom = {}; + stream.Writable.call(this, {}); +} +util.inherits(Verifier, stream.Writable); - return RULES; +Verifier.prototype._write = function (chunk, enc, cb) { + this.chunks.push(chunk); + cb(); +}; + +Verifier.prototype.update = function (chunk) { + if (typeof (chunk) === 'string') + chunk = new Buffer(chunk, 'binary'); + this.chunks.push(chunk); +}; + +Verifier.prototype.verify = function (signature, fmt) { + var sig; + if (Signature.isSignature(signature, [2, 0])) { + if (signature.type !== 'ed25519') + return (false); + sig = signature.toBuffer('raw'); + + } else if (typeof (signature) === 'string') { + sig = new Buffer(signature, 'base64'); + + } else if (Signature.isSignature(signature, [1, 0])) { + throw (new Error('signature was created by too old ' + + 'a version of sshpk and cannot be verified')); + } + + assert.buffer(sig); + return (nacl.sign.detached.verify( + new Uint8Array(Buffer.concat(this.chunks)), + new Uint8Array(sig), + new Uint8Array(this.key.part.R.data))); +}; + +function Signer(key, hashAlgo) { + if (nacl === undefined) + nacl = __webpack_require__(146); + + if (hashAlgo.toLowerCase() !== 'sha512') + throw (new Error('ED25519 only supports the use of ' + + 'SHA-512 hashes')); + + this.key = key; + this.chunks = []; + + stream.Writable.call(this, {}); +} +util.inherits(Signer, stream.Writable); + +Signer.prototype._write = function (chunk, enc, cb) { + this.chunks.push(chunk); + cb(); +}; + +Signer.prototype.update = function (chunk) { + if (typeof (chunk) === 'string') + chunk = new Buffer(chunk, 'binary'); + this.chunks.push(chunk); +}; + +Signer.prototype.sign = function () { + var sig = nacl.sign.detached( + new Uint8Array(Buffer.concat(this.chunks)), + new Uint8Array(this.key.part.r.data)); + var sigBuf = new Buffer(sig); + var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw'); + sigObj.hashAlgorithm = 'sha512'; + return (sigObj); }; /***/ }), -/* 291 */ +/* 318 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; - +// Copyright 2015 Joyent, Inc. -// https://mathiasbynens.be/notes/javascript-encoding -// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode -module.exports = function ucs2length(str) { - var length = 0 - , len = str.length - , pos = 0 - , value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 0xD800 && value <= 0xDBFF && pos < len) { - // high surrogate, and there is a next character - value = str.charCodeAt(pos); - if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate - } - } - return length; +module.exports = { + read: read, + write: write }; +var assert = __webpack_require__(11); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); + +var pem = __webpack_require__(58); +var ssh = __webpack_require__(319); +var rfc4253 = __webpack_require__(75); + +function read(buf, options) { + if (typeof (buf) === 'string') { + if (buf.trim().match(/^[-]+[ ]*BEGIN/)) + return (pem.read(buf, options)); + if (buf.match(/^\s*ssh-[a-z]/)) + return (ssh.read(buf, options)); + if (buf.match(/^\s*ecdsa-/)) + return (ssh.read(buf, options)); + buf = new Buffer(buf, 'binary'); + } else { + assert.buffer(buf); + if (findPEMHeader(buf)) + return (pem.read(buf, options)); + if (findSSHHeader(buf)) + return (ssh.read(buf, options)); + } + if (buf.readUInt32BE(0) < buf.length) + return (rfc4253.read(buf, options)); + throw (new Error('Failed to auto-detect format of key')); +} + +function findSSHHeader(buf) { + var offset = 0; + while (offset < buf.length && + (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9)) + ++offset; + if (offset + 4 <= buf.length && + buf.slice(offset, offset + 4).toString('ascii') === 'ssh-') + return (true); + if (offset + 6 <= buf.length && + buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-') + return (true); + return (false); +} + +function findPEMHeader(buf) { + var offset = 0; + while (offset < buf.length && + (buf[offset] === 32 || buf[offset] === 10)) + ++offset; + if (buf[offset] !== 45) + return (false); + while (offset < buf.length && + (buf[offset] === 45)) + ++offset; + while (offset < buf.length && + (buf[offset] === 32)) + ++offset; + if (offset + 5 > buf.length || + buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN') + return (false); + return (true); +} + +function write(key, options) { + throw (new Error('"auto" format cannot be used for writing')); +} + /***/ }), -/* 292 */ +/* 319 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Copyright 2015 Joyent, Inc. -module.exports = function generate__formatLimit(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - out += 'var ' + ($valid) + ' = undefined;'; - if (it.opts.format === false) { - out += ' ' + ($valid) + ' = true; '; - return out; - } - var $schemaFormat = it.schema.format, - $isDataFormat = it.opts.v5 && $schemaFormat.$data, - $closingBraces = ''; - if ($isDataFormat) { - var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr), - $format = 'format' + $lvl, - $compare = 'compare' + $lvl; - out += ' var ' + ($format) + ' = formats[' + ($schemaValueFormat) + '] , ' + ($compare) + ' = ' + ($format) + ' && ' + ($format) + '.compare;'; - } else { - var $format = it.formats[$schemaFormat]; - if (!($format && $format.compare)) { - out += ' ' + ($valid) + ' = true; '; - return out; - } - var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare'; - } - var $isMax = $keyword == 'formatMaximum', - $exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum'), - $schemaExcl = it.schema[$exclusiveKeyword], - $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data, - $op = $isMax ? '<' : '>', - $result = 'result' + $lvl; - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if ($isDataExcl) { - var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), - $exclusive = 'exclusive' + $lvl, - $opExpr = 'op' + $lvl, - $opStr = '\' + ' + $opExpr + ' + \''; - out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; - $schemaValueExcl = 'schemaExcl' + $lvl; - out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; '; - var $errorKeyword = $exclusiveKeyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - if ($isData) { - out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; - $closingBraces += '}'; - } - if ($isDataFormat) { - out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; - $closingBraces += '}'; - } - out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; - } else { - var $exclusive = $schemaExcl === true, - $opStr = $op; - if (!$exclusive) $opStr += '='; - var $opExpr = '\'' + $opStr + '\''; - if ($isData) { - out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; - $closingBraces += '}'; - } - if ($isDataFormat) { - out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; - $closingBraces += '}'; - } - out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op); - if (!$exclusive) { - out += '='; - } - out += ' 0;'; - } - out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; - var $errorKeyword = $keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' , exclusive: ' + ($exclusive) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be ' + ($opStr) + ' "'; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + (it.util.escapeQuotes($schema)); - } - out += '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '}'; - return out; +module.exports = { + read: read, + write: write +}; + +var assert = __webpack_require__(11); +var rfc4253 = __webpack_require__(75); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); + +var sshpriv = __webpack_require__(143); + +/*JSSTYLED*/ +var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([\n \t]+([^\n]+))?$/; +/*JSSTYLED*/ +var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/ \t\n]+[=]*)(.*)$/; + +function read(buf, options) { + if (typeof (buf) !== 'string') { + assert.buffer(buf, 'buf'); + buf = buf.toString('ascii'); + } + + var trimmed = buf.trim().replace(/[\\\r]/g, ''); + var m = trimmed.match(SSHKEY_RE); + if (!m) + m = trimmed.match(SSHKEY_RE2); + assert.ok(m, 'key must match regex'); + + var type = rfc4253.algToKeyType(m[1]); + var kbuf = new Buffer(m[2], 'base64'); + + /* + * This is a bit tricky. If we managed to parse the key and locate the + * key comment with the regex, then do a non-partial read and assert + * that we have consumed all bytes. If we couldn't locate the key + * comment, though, there may be whitespace shenanigans going on that + * have conjoined the comment to the rest of the key. We do a partial + * read in this case to try to make the best out of a sorry situation. + */ + var key; + var ret = {}; + if (m[4]) { + try { + key = rfc4253.read(kbuf); + + } catch (e) { + m = trimmed.match(SSHKEY_RE2); + assert.ok(m, 'key must match regex'); + kbuf = new Buffer(m[2], 'base64'); + key = rfc4253.readInternal(ret, 'public', kbuf); + } + } else { + key = rfc4253.readInternal(ret, 'public', kbuf); + } + + assert.strictEqual(type, key.type); + + if (m[4] && m[4].length > 0) { + key.comment = m[4]; + + } else if (ret.consumed) { + /* + * Now the magic: trying to recover the key comment when it's + * gotten conjoined to the key or otherwise shenanigan'd. + * + * Work out how much base64 we used, then drop all non-base64 + * chars from the beginning up to this point in the the string. + * Then offset in this and try to make up for missing = chars. + */ + var data = m[2] + m[3]; + var realOffset = Math.ceil(ret.consumed / 3) * 4; + data = data.slice(0, realOffset - 2). /*JSSTYLED*/ + replace(/[^a-zA-Z0-9+\/=]/g, '') + + data.slice(realOffset - 2); + + var padding = ret.consumed % 3; + if (padding > 0 && + data.slice(realOffset - 1, realOffset) !== '=') + realOffset--; + while (data.slice(realOffset, realOffset + 1) === '=') + realOffset++; + + /* Finally, grab what we think is the comment & clean it up. */ + var trailer = data.slice(realOffset); + trailer = trailer.replace(/[\r\n]/g, ' '). + replace(/^\s+/, ''); + if (trailer.match(/^[a-zA-Z0-9]/)) + key.comment = trailer; + } + + return (key); } +function write(key, options) { + assert.object(key); + if (!Key.isKey(key)) + throw (new Error('Must be a public key')); -/***/ }), -/* 293 */ -/***/ (function(module, exports, __webpack_require__) { + var parts = []; + var alg = rfc4253.keyTypeToAlg(key); + parts.push(alg); -"use strict"; + var buf = rfc4253.write(key); + parts.push(buf.toString('base64')); -module.exports = function generate_allOf(it, $keyword) { - var out = ' '; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $currentBaseId = $it.baseId, - $allSchemasEmpty = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if (it.util.schemaHasRules($sch, it.RULES.all)) { - $allSchemasEmpty = false; - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if ($breakOnError) { - if ($allSchemasEmpty) { - out += ' if (true) { '; - } else { - out += ' ' + ($closingBraces.slice(0, -1)) + ' '; - } - } - out = it.util.cleanUpCode(out); - return out; + if (key.comment) + parts.push(key.comment); + + return (new Buffer(parts.join(' '))); } /***/ }), -/* 294 */ +/* 320 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Copyright 2017 Joyent, Inc. -module.exports = function generate_anyOf(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $noEmptySchema = $schema.every(function($sch) { - return it.util.schemaHasRules($sch, it.RULES.all); - }); - if ($noEmptySchema) { - var $currentBaseId = $it.baseId; - out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; - $closingBraces += '}'; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should match some schema in anyOf\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - if (it.opts.allErrors) { - out += ' } '; - } - out = it.util.cleanUpCode(out); - } else { - if ($breakOnError) { - out += ' if (true) { '; - } - } - return out; +module.exports = { + read: read, + verify: verify, + sign: sign, + signAsync: signAsync, + write: write +}; + +var assert = __webpack_require__(11); +var asn1 = __webpack_require__(50); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var pem = __webpack_require__(58); +var Identity = __webpack_require__(118); +var Signature = __webpack_require__(45); +var Certificate = __webpack_require__(115); +var pkcs8 = __webpack_require__(117); + +/* + * This file is based on RFC5280 (X.509). + */ + +/* Helper to read in a single mpint */ +function readMPInt(der, nm) { + assert.strictEqual(der.peek(), asn1.Ber.Integer, + nm + ' is not an Integer'); + return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true))); } +function verify(cert, key) { + var sig = cert.signatures.x509; + assert.object(sig, 'x509 signature'); -/***/ }), -/* 295 */ -/***/ (function(module, exports, __webpack_require__) { + var algParts = sig.algo.split('-'); + if (algParts[0] !== key.type) + return (false); -"use strict"; + var blob = sig.cache; + if (blob === undefined) { + var der = new asn1.BerWriter(); + writeTBSCert(cert, der); + blob = der.buffer; + } -module.exports = function generate_constant(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if (!$isData) { - out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; - } - out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('constant') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should be equal to constant\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' }'; - return out; + var verifier = key.createVerify(algParts[1]); + verifier.write(blob); + return (verifier.verify(sig.signature)); } +function Local(i) { + return (asn1.Ber.Context | asn1.Ber.Constructor | i); +} -/***/ }), -/* 296 */ -/***/ (function(module, exports, __webpack_require__) { +function Context(i) { + return (asn1.Ber.Context | i); +} -"use strict"; +var SIGN_ALGS = { + 'rsa-md5': '1.2.840.113549.1.1.4', + 'rsa-sha1': '1.2.840.113549.1.1.5', + 'rsa-sha256': '1.2.840.113549.1.1.11', + 'rsa-sha384': '1.2.840.113549.1.1.12', + 'rsa-sha512': '1.2.840.113549.1.1.13', + 'dsa-sha1': '1.2.840.10040.4.3', + 'dsa-sha256': '2.16.840.1.101.3.4.3.2', + 'ecdsa-sha1': '1.2.840.10045.4.1', + 'ecdsa-sha256': '1.2.840.10045.4.3.2', + 'ecdsa-sha384': '1.2.840.10045.4.3.3', + 'ecdsa-sha512': '1.2.840.10045.4.3.4' +}; +Object.keys(SIGN_ALGS).forEach(function (k) { + SIGN_ALGS[SIGN_ALGS[k]] = k; +}); +SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5'; +SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1'; -module.exports = function generate_custom(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $errorKeyword; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $rule = this, - $definition = 'definition' + $lvl, - $rDef = $rule.definition; - var $compile, $inline, $macro, $ruleValidate, $validateCode; - if ($isData && $rDef.$data) { - $validateCode = 'keywordValidate' + $lvl; - var $validateSchema = $rDef.validateSchema; - out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; - } else { - $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); - $schemaValue = 'validate.schema' + $schemaPath; - $validateCode = $ruleValidate.code; - $compile = $rDef.compile; - $inline = $rDef.inline; - $macro = $rDef.macro; - } - var $ruleErrs = $validateCode + '.errors', - $i = 'i' + $lvl, - $ruleErr = 'ruleErr' + $lvl, - $asyncKeyword = $rDef.async; - if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); - if (!($inline || $macro)) { - out += '' + ($ruleErrs) + ' = null;'; - } - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if ($validateSchema) { - out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') {'; - } - if ($inline) { - if ($rDef.statements) { - out += ' ' + ($ruleValidate.validate) + ' '; - } else { - out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; - } - } else if ($macro) { - var $it = it.util.copy(it); - $it.level++; - var $nextValid = 'valid' + $it.level; - $it.schema = $ruleValidate.validate; - $it.schemaPath = ''; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($code); - } else { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - out += ' ' + ($validateCode) + '.call( '; - if (it.opts.passContext) { - out += 'this'; - } else { - out += 'self'; - } - if ($compile || $rDef.schema === false) { - out += ' , ' + ($data) + ' '; - } else { - out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; - } - out += ' , (dataPath || \'\')'; - if (it.errorPath != '""') { - out += ' + ' + (it.errorPath); - } - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; - var def_callRuleValidate = out; - out = $$outStack.pop(); - if ($rDef.errors === false) { - out += ' ' + ($valid) + ' = '; - if ($asyncKeyword) { - out += '' + (it.yieldAwait); - } - out += '' + (def_callRuleValidate) + '; '; - } else { - if ($asyncKeyword) { - $ruleErrs = 'customErrors' + $lvl; - out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; - } else { - out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; - } - } - } - if ($rDef.modifying) { - out += ' ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; - } - if ($validateSchema) { - out += ' }'; - } - if ($rDef.valid) { - if ($breakOnError) { - out += ' if (true) { '; - } - } else { - out += ' if ( '; - if ($rDef.valid === undefined) { - out += ' !'; - if ($macro) { - out += '' + ($nextValid); - } else { - out += '' + ($valid); - } - } else { - out += ' ' + (!$rDef.valid) + ' '; - } - out += ') { '; - $errorKeyword = $rule.keyword; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - var def_customError = out; - out = $$outStack.pop(); - if ($inline) { - if ($rDef.errors) { - if ($rDef.errors != 'full') { - out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } '; - if (it.opts.verbose) { - out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; - } - out += ' } '; - } - } else { - if ($rDef.errors === false) { - out += ' ' + (def_customError) + ' '; - } else { - out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else { for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } '; - if (it.opts.verbose) { - out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; - } - out += ' } } '; - } - } - } else if ($macro) { - out += ' var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError(vErrors); '; - } else { - out += ' validate.errors = vErrors; return false; '; - } - } - } else { - if ($rDef.errors === false) { - out += ' ' + (def_customError) + ' '; - } else { - out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; '; - if (it.opts.verbose) { - out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; - } - out += ' } } else { ' + (def_customError) + ' } '; - } - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - } - return out; -} +var EXTS = { + 'issuerKeyId': '2.5.29.35', + 'altName': '2.5.29.17', + 'basicConstraints': '2.5.29.19', + 'keyUsage': '2.5.29.15', + 'extKeyUsage': '2.5.29.37' +}; +function read(buf, options) { + if (typeof (buf) === 'string') { + buf = new Buffer(buf, 'binary'); + } + assert.buffer(buf, 'buf'); -/***/ }), -/* 297 */ -/***/ (function(module, exports, __webpack_require__) { + var der = new asn1.BerReader(buf); -"use strict"; + der.readSequence(); + if (Math.abs(der.length - der.remain) > 1) { + throw (new Error('DER sequence does not contain whole byte ' + + 'stream')); + } -module.exports = function generate_dependencies(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $schemaDeps = {}, - $propertyDeps = {}; - for ($property in $schema) { - var $sch = $schema[$property]; - var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; - $deps[$property] = $sch; - } - out += 'var ' + ($errs) + ' = errors;'; - var $currentErrorPath = it.errorPath; - out += 'var missing' + ($lvl) + ';'; - for (var $property in $propertyDeps) { - $deps = $propertyDeps[$property]; - out += ' if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; - if ($breakOnError) { - out += ' && ( '; - var arr1 = $deps; - if (arr1) { - var _$property, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - _$property = arr1[$i += 1]; - if ($i) { - out += ' || '; - } - var $prop = it.util.getProperty(_$property); - out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) '; - } - } - out += ')) { '; - var $propertyPath = 'missing' + $lvl, - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should have '; - if ($deps.length == 1) { - out += 'property ' + (it.util.escapeQuotes($deps[0])); - } else { - out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); - } - out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - } else { - out += ' ) { '; - var arr2 = $deps; - if (arr2) { - var $reqProperty, i2 = -1, - l2 = arr2.length - 1; - while (i2 < l2) { - $reqProperty = arr2[i2 += 1]; - var $prop = it.util.getProperty($reqProperty), - $missingProperty = it.util.escapeQuotes($reqProperty); - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers); - } - out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should have '; - if ($deps.length == 1) { - out += 'property ' + (it.util.escapeQuotes($deps[0])); - } else { - out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); - } - out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; - } - } - } - out += ' } '; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - } - it.errorPath = $currentErrorPath; - var $currentBaseId = $it.baseId; - for (var $property in $schemaDeps) { - var $sch = $schemaDeps[$property]; - if (it.util.schemaHasRules($sch, it.RULES.all)) { - out += ' ' + ($nextValid) + ' = true; if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined) { '; - $it.schema = $sch; - $it.schemaPath = $schemaPath + it.util.getProperty($property); - $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; - } - out = it.util.cleanUpCode(out); - return out; -} + var tbsStart = der.offset; + der.readSequence(); + var sigOffset = der.offset + der.length; + var tbsEnd = sigOffset; + if (der.peek() === Local(0)) { + der.readSequence(Local(0)); + var version = der.readInt(); + assert.ok(version <= 3, + 'only x.509 versions up to v3 supported'); + } -/***/ }), -/* 298 */ -/***/ (function(module, exports, __webpack_require__) { + var cert = {}; + cert.signatures = {}; + var sig = (cert.signatures.x509 = {}); + sig.extras = {}; -"use strict"; + cert.serial = readMPInt(der, 'serial'); -module.exports = function generate_enum(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $i = 'i' + $lvl, - $vSchema = 'schema' + $lvl; - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; - } - out += 'var ' + ($valid) + ';'; - if ($isData) { - out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; - } - out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be equal to one of the allowed values\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' }'; - if ($breakOnError) { - out += ' else { '; - } - return out; -} + der.readSequence(); + var after = der.offset + der.length; + var certAlgOid = der.readOID(); + var certAlg = SIGN_ALGS[certAlgOid]; + if (certAlg === undefined) + throw (new Error('unknown signature algorithm ' + certAlgOid)); + der._offset = after; + cert.issuer = Identity.parseAsn1(der); -/***/ }), -/* 299 */ -/***/ (function(module, exports, __webpack_require__) { + der.readSequence(); + cert.validFrom = readDate(der); + cert.validUntil = readDate(der); -"use strict"; + cert.subjects = [Identity.parseAsn1(der)]; -module.exports = function generate_format(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - if (it.opts.format === false) { - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $unknownFormats = it.opts.unknownFormats, - $allowUnknown = Array.isArray($unknownFormats); - if ($isData) { - var $format = 'format' + $lvl; - out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { '; - if (it.async) { - out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; - } - out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; - } - out += ' ('; - if ($unknownFormats === true || $allowUnknown) { - out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; - if ($allowUnknown) { - out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; - } - out += ') || '; - } - out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? '; - if (it.async) { - out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; - } else { - out += ' ' + ($format) + '(' + ($data) + ') '; - } - out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; - } else { - var $format = it.formats[$schema]; - if (!$format) { - if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) { - throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); - } else { - if (!$allowUnknown) { - console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); - if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information'); - } - if ($breakOnError) { - out += ' if (true) { '; - } - return out; - } - } - var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; - if ($isObject) { - var $async = $format.async === true; - $format = $format.validate; - } - if ($async) { - if (!it.async) throw new Error('async format in sync schema'); - var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; - out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { '; - } else { - out += ' if (! '; - var $formatRef = 'formats' + it.util.getProperty($schema); - if ($isObject) $formatRef += '.validate'; - if (typeof $format == 'function') { - out += ' ' + ($formatRef) + '(' + ($data) + ') '; - } else { - out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; - } - out += ') { '; - } - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match format "'; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + (it.util.escapeQuotes($schema)); - } - out += '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - return out; -} + der.readSequence(); + after = der.offset + der.length; + cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der); + der._offset = after; + /* issuerUniqueID */ + if (der.peek() === Local(1)) { + der.readSequence(Local(1)); + sig.extras.issuerUniqueID = + buf.slice(der.offset, der.offset + der.length); + der._offset += der.length; + } -/***/ }), -/* 300 */ -/***/ (function(module, exports, __webpack_require__) { + /* subjectUniqueID */ + if (der.peek() === Local(2)) { + der.readSequence(Local(2)); + sig.extras.subjectUniqueID = + buf.slice(der.offset, der.offset + der.length); + der._offset += der.length; + } -"use strict"; + /* extensions */ + if (der.peek() === Local(3)) { + der.readSequence(Local(3)); + var extEnd = der.offset + der.length; + der.readSequence(); -module.exports = function generate_items(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $idx = 'i' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt, - $currentBaseId = it.baseId; - out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; - if (Array.isArray($schema)) { - var $additionalItems = it.schema.additionalItems; - if ($additionalItems === false) { - out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; - var $currErrSchemaPath = $errSchemaPath; - $errSchemaPath = it.errSchemaPath + '/additionalItems'; - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - } - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if (it.util.schemaHasRules($sch, it.RULES.all)) { - out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; - var $passData = $data + '[' + $i + ']'; - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); - $it.dataPathArr[$dataNxt] = $i; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) { - $it.schema = $additionalItems; - $it.schemaPath = it.schemaPath + '.additionalItems'; - $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; - out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + '[' + $idx + ']'; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } else if (it.util.schemaHasRules($schema, it.RULES.all)) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); - var $passData = $data + '[' + $idx + ']'; - $it.dataPathArr[$dataNxt] = $idx; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; - } - out = it.util.cleanUpCode(out); - return out; -} + while (der.offset < extEnd) + readExtension(cert, buf, der); + assert.strictEqual(der.offset, extEnd); + } -/***/ }), -/* 301 */ -/***/ (function(module, exports, __webpack_require__) { + assert.strictEqual(der.offset, sigOffset); -"use strict"; + der.readSequence(); + after = der.offset + der.length; + var sigAlgOid = der.readOID(); + var sigAlg = SIGN_ALGS[sigAlgOid]; + if (sigAlg === undefined) + throw (new Error('unknown signature algorithm ' + sigAlgOid)); + der._offset = after; -module.exports = function generate_multipleOf(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - out += 'var division' + ($lvl) + ';if ('; - if ($isData) { - out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; - } - out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; - if (it.opts.multipleOfPrecision) { - out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; - } else { - out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; - } - out += ' ) '; - if ($isData) { - out += ' ) '; - } - out += ' ) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should be multiple of '; - if ($isData) { - out += '\' + ' + ($schemaValue); - } else { - out += '' + ($schema) + '\''; - } - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; + var sigData = der.readString(asn1.Ber.BitString, true); + if (sigData[0] === 0) + sigData = sigData.slice(1); + var algParts = sigAlg.split('-'); + + sig.signature = Signature.parse(sigData, algParts[0], 'asn1'); + sig.signature.hashAlgorithm = algParts[1]; + sig.algo = sigAlg; + sig.cache = buf.slice(tbsStart, tbsEnd); + + return (new Certificate(cert)); } +function readDate(der) { + if (der.peek() === asn1.Ber.UTCTime) { + return (utcTimeToDate(der.readString(asn1.Ber.UTCTime))); + } else if (der.peek() === asn1.Ber.GeneralizedTime) { + return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime))); + } else { + throw (new Error('Unsupported date format')); + } +} -/***/ }), -/* 302 */ -/***/ (function(module, exports, __webpack_require__) { +/* RFC5280, section 4.2.1.6 (GeneralName type) */ +var ALTNAME = { + OtherName: Local(0), + RFC822Name: Context(1), + DNSName: Context(2), + X400Address: Local(3), + DirectoryName: Local(4), + EDIPartyName: Local(5), + URI: Context(6), + IPAddress: Context(7), + OID: Context(8) +}; -"use strict"; +/* RFC5280, section 4.2.1.12 (KeyPurposeId) */ +var EXTPURPOSE = { + 'serverAuth': '1.3.6.1.5.5.7.3.1', + 'clientAuth': '1.3.6.1.5.5.7.3.2', + 'codeSigning': '1.3.6.1.5.5.7.3.3', -module.exports = function generate_not(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - $it.level++; - var $nextValid = 'valid' + $it.level; - if (it.util.schemaHasRules($schema, it.RULES.all)) { - $it.schema = $schema; - $it.schemaPath = $schemaPath; - $it.errSchemaPath = $errSchemaPath; - out += ' var ' + ($errs) + ' = errors; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.createErrors = false; - var $allErrorsOption; - if ($it.opts.allErrors) { - $allErrorsOption = $it.opts.allErrors; - $it.opts.allErrors = false; - } - out += ' ' + (it.validate($it)) + ' '; - $it.createErrors = true; - if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' if (' + ($nextValid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT be valid\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; - if (it.opts.allErrors) { - out += ' } '; - } - } else { - out += ' var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT be valid\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - if ($breakOnError) { - out += ' if (false) { '; - } - } - return out; -} + /* See https://github.com/joyent/oid-docs/blob/master/root.md */ + 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1', + 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2' +}; +var EXTPURPOSE_REV = {}; +Object.keys(EXTPURPOSE).forEach(function (k) { + EXTPURPOSE_REV[EXTPURPOSE[k]] = k; +}); +var KEYUSEBITS = [ + 'signature', 'identity', 'keyEncryption', + 'encryption', 'keyAgreement', 'ca', 'crl' +]; -/***/ }), -/* 303 */ -/***/ (function(module, exports, __webpack_require__) { +function readExtension(cert, buf, der) { + der.readSequence(); + var after = der.offset + der.length; + var extId = der.readOID(); + var id; + var sig = cert.signatures.x509; + sig.extras.exts = []; -"use strict"; + var critical; + if (der.peek() === asn1.Ber.Boolean) + critical = der.readBoolean(); -module.exports = function generate_oneOf(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;'; - var $currentBaseId = $it.baseId; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - var arr1 = $schema; - if (arr1) { - var $sch, $i = -1, - l1 = arr1.length - 1; - while ($i < l1) { - $sch = arr1[$i += 1]; - if (it.util.schemaHasRules($sch, it.RULES.all)) { - $it.schema = $sch; - $it.schemaPath = $schemaPath + '[' + $i + ']'; - $it.errSchemaPath = $errSchemaPath + '/' + $i; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - } else { - out += ' var ' + ($nextValid) + ' = true; '; - } - if ($i) { - out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { '; - $closingBraces += '}'; - } - out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;'; - } - } - it.compositeRule = $it.compositeRule = $wasComposite; - out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; - if (it.opts.messages !== false) { - out += ' , message: \'should match exactly one schema in oneOf\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; - if (it.opts.allErrors) { - out += ' } '; - } - return out; + switch (extId) { + case (EXTS.basicConstraints): + der.readSequence(asn1.Ber.OctetString); + der.readSequence(); + var bcEnd = der.offset + der.length; + var ca = false; + if (der.peek() === asn1.Ber.Boolean) + ca = der.readBoolean(); + if (cert.purposes === undefined) + cert.purposes = []; + if (ca === true) + cert.purposes.push('ca'); + var bc = { oid: extId, critical: critical }; + if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer) + bc.pathLen = der.readInt(); + sig.extras.exts.push(bc); + break; + case (EXTS.extKeyUsage): + der.readSequence(asn1.Ber.OctetString); + der.readSequence(); + if (cert.purposes === undefined) + cert.purposes = []; + var ekEnd = der.offset + der.length; + while (der.offset < ekEnd) { + var oid = der.readOID(); + cert.purposes.push(EXTPURPOSE_REV[oid] || oid); + } + /* + * This is a bit of a hack: in the case where we have a cert + * that's only allowed to do serverAuth or clientAuth (and not + * the other), we want to make sure all our Subjects are of + * the right type. But we already parsed our Subjects and + * decided if they were hosts or users earlier (since it appears + * first in the cert). + * + * So we go through and mutate them into the right kind here if + * it doesn't match. This might not be hugely beneficial, as it + * seems that single-purpose certs are not often seen in the + * wild. + */ + if (cert.purposes.indexOf('serverAuth') !== -1 && + cert.purposes.indexOf('clientAuth') === -1) { + cert.subjects.forEach(function (ide) { + if (ide.type !== 'host') { + ide.type = 'host'; + ide.hostname = ide.uid || + ide.email || + ide.components[0].value; + } + }); + } else if (cert.purposes.indexOf('clientAuth') !== -1 && + cert.purposes.indexOf('serverAuth') === -1) { + cert.subjects.forEach(function (ide) { + if (ide.type !== 'user') { + ide.type = 'user'; + ide.uid = ide.hostname || + ide.email || + ide.components[0].value; + } + }); + } + sig.extras.exts.push({ oid: extId, critical: critical }); + break; + case (EXTS.keyUsage): + der.readSequence(asn1.Ber.OctetString); + var bits = der.readString(asn1.Ber.BitString, true); + var setBits = readBitField(bits, KEYUSEBITS); + setBits.forEach(function (bit) { + if (cert.purposes === undefined) + cert.purposes = []; + if (cert.purposes.indexOf(bit) === -1) + cert.purposes.push(bit); + }); + sig.extras.exts.push({ oid: extId, critical: critical, + bits: bits }); + break; + case (EXTS.altName): + der.readSequence(asn1.Ber.OctetString); + der.readSequence(); + var aeEnd = der.offset + der.length; + while (der.offset < aeEnd) { + switch (der.peek()) { + case ALTNAME.OtherName: + case ALTNAME.EDIPartyName: + der.readSequence(); + der._offset += der.length; + break; + case ALTNAME.OID: + der.readOID(ALTNAME.OID); + break; + case ALTNAME.RFC822Name: + /* RFC822 specifies email addresses */ + var email = der.readString(ALTNAME.RFC822Name); + id = Identity.forEmail(email); + if (!cert.subjects[0].equals(id)) + cert.subjects.push(id); + break; + case ALTNAME.DirectoryName: + der.readSequence(ALTNAME.DirectoryName); + id = Identity.parseAsn1(der); + if (!cert.subjects[0].equals(id)) + cert.subjects.push(id); + break; + case ALTNAME.DNSName: + var host = der.readString( + ALTNAME.DNSName); + id = Identity.forHost(host); + if (!cert.subjects[0].equals(id)) + cert.subjects.push(id); + break; + default: + der.readString(der.peek()); + break; + } + } + sig.extras.exts.push({ oid: extId, critical: critical }); + break; + default: + sig.extras.exts.push({ + oid: extId, + critical: critical, + data: der.readString(asn1.Ber.OctetString, true) + }); + break; + } + + der._offset = after; } +var UTCTIME_RE = + /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; +function utcTimeToDate(t) { + var m = t.match(UTCTIME_RE); + assert.ok(m, 'timestamps must be in UTC'); + var d = new Date(); -/***/ }), -/* 304 */ -/***/ (function(module, exports, __webpack_require__) { + var thisYear = d.getUTCFullYear(); + var century = Math.floor(thisYear / 100) * 100; -"use strict"; + var year = parseInt(m[1], 10); + if (thisYear % 100 < 50 && year >= 60) + year += (century - 1); + else + year += century; + d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10)); + d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); + if (m[6] && m[6].length > 0) + d.setUTCSeconds(parseInt(m[6], 10)); + return (d); +} -module.exports = function generate_pattern(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); - out += 'if ( '; - if ($isData) { - out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; - } - out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; - if ($isData) { - out += '' + ($schemaValue); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should match pattern "'; - if ($isData) { - out += '\' + ' + ($schemaValue) + ' + \''; - } else { - out += '' + (it.util.escapeQuotes($schema)); - } - out += '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + (it.util.toQuotedString($schema)); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += '} '; - if ($breakOnError) { - out += ' else { '; - } - return out; +var GTIME_RE = + /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/; +function gTimeToDate(t) { + var m = t.match(GTIME_RE); + assert.ok(m); + var d = new Date(); + + d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1, + parseInt(m[3], 10)); + d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10)); + if (m[6] && m[6].length > 0) + d.setUTCSeconds(parseInt(m[6], 10)); + return (d); } +function zeroPad(n) { + var s = '' + n; + while (s.length < 2) + s = '0' + s; + return (s); +} -/***/ }), -/* 305 */ -/***/ (function(module, exports, __webpack_require__) { +function dateToUTCTime(d) { + var s = ''; + s += zeroPad(d.getUTCFullYear() % 100); + s += zeroPad(d.getUTCMonth() + 1); + s += zeroPad(d.getUTCDate()); + s += zeroPad(d.getUTCHours()); + s += zeroPad(d.getUTCMinutes()); + s += zeroPad(d.getUTCSeconds()); + s += 'Z'; + return (s); +} -"use strict"; +function sign(cert, key) { + if (cert.signatures.x509 === undefined) + cert.signatures.x509 = {}; + var sig = cert.signatures.x509; -module.exports = function generate_patternRequired(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $key = 'key' + $lvl, - $matched = 'patternMatched' + $lvl, - $closingBraces = '', - $ownProperties = it.opts.ownProperties; - out += 'var ' + ($valid) + ' = true;'; - var arr1 = $schema; - if (arr1) { - var $pProperty, i1 = -1, - l1 = arr1.length - 1; - while (i1 < l1) { - $pProperty = arr1[i1 += 1]; - out += ' var ' + ($matched) + ' = false; for (var ' + ($key) + ' in ' + ($data) + ') { '; - if ($ownProperties) { - out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; - } - out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } '; - var $missingPattern = it.util.escapeQuotes($pProperty); - out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false; var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; - if ($breakOnError) { - $closingBraces += '}'; - out += ' else { '; - } - } - } - out += '' + ($closingBraces); - return out; + sig.algo = key.type + '-' + key.defaultHashAlgorithm(); + if (SIGN_ALGS[sig.algo] === undefined) + return (false); + + var der = new asn1.BerWriter(); + writeTBSCert(cert, der); + var blob = der.buffer; + sig.cache = blob; + + var signer = key.createSign(); + signer.write(blob); + cert.signatures.x509.signature = signer.sign(); + + return (true); } +function signAsync(cert, signer, done) { + if (cert.signatures.x509 === undefined) + cert.signatures.x509 = {}; + var sig = cert.signatures.x509; -/***/ }), -/* 306 */ -/***/ (function(module, exports, __webpack_require__) { + var der = new asn1.BerWriter(); + writeTBSCert(cert, der); + var blob = der.buffer; + sig.cache = blob; -"use strict"; + signer(blob, function (err, signature) { + if (err) { + done(err); + return; + } + sig.algo = signature.type + '-' + signature.hashAlgorithm; + if (SIGN_ALGS[sig.algo] === undefined) { + done(new Error('Invalid signing algorithm "' + + sig.algo + '"')); + return; + } + sig.signature = signature; + done(); + }); +} -module.exports = function generate_properties(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $key = 'key' + $lvl, - $dataNxt = $it.dataLevel = it.dataLevel + 1, - $nextData = 'data' + $dataNxt; - var $schemaKeys = Object.keys($schema || {}), - $pProperties = it.schema.patternProperties || {}, - $pPropertyKeys = Object.keys($pProperties), - $aProperties = it.schema.additionalProperties, - $someProperties = $schemaKeys.length || $pPropertyKeys.length, - $noAdditional = $aProperties === false, - $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, - $removeAdditional = it.opts.removeAdditional, - $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, - $ownProperties = it.opts.ownProperties, - $currentBaseId = it.baseId; - var $required = it.schema.required; - if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); - if (it.opts.v5) { - var $pgProperties = it.schema.patternGroups || {}, - $pgPropertyKeys = Object.keys($pgProperties); - } - out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; - if ($checkAdditional) { - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - if ($ownProperties) { - out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; - } - if ($someProperties) { - out += ' var isAdditional' + ($lvl) + ' = !(false '; - if ($schemaKeys.length) { - if ($schemaKeys.length > 5) { - out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] '; - } else { - var arr1 = $schemaKeys; - if (arr1) { - var $propertyKey, i1 = -1, - l1 = arr1.length - 1; - while (i1 < l1) { - $propertyKey = arr1[i1 += 1]; - out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; - } - } - } - } - if ($pPropertyKeys.length) { - var arr2 = $pPropertyKeys; - if (arr2) { - var $pProperty, $i = -1, - l2 = arr2.length - 1; - while ($i < l2) { - $pProperty = arr2[$i += 1]; - out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; - } - } - } - if (it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length) { - var arr3 = $pgPropertyKeys; - if (arr3) { - var $pgProperty, $i = -1, - l3 = arr3.length - 1; - while ($i < l3) { - $pgProperty = arr3[$i += 1]; - out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') '; - } - } - } - out += ' ); if (isAdditional' + ($lvl) + ') { '; - } - if ($removeAdditional == 'all') { - out += ' delete ' + ($data) + '[' + ($key) + ']; '; - } else { - var $currentErrorPath = it.errorPath; - var $additionalProperty = '\' + ' + $key + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - } - if ($noAdditional) { - if ($removeAdditional) { - out += ' delete ' + ($data) + '[' + ($key) + ']; '; - } else { - out += ' ' + ($nextValid) + ' = false; '; - var $currErrSchemaPath = $errSchemaPath; - $errSchemaPath = it.errSchemaPath + '/additionalProperties'; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have additional properties\' '; - } - if (it.opts.verbose) { - out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - out += ' break; '; - } - } - } else if ($additionalIsSchema) { - if ($removeAdditional == 'failing') { - out += ' var ' + ($errs) + ' = errors; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.schema = $aProperties; - $it.schemaPath = it.schemaPath + '.additionalProperties'; - $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; - $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + '[' + $key + ']'; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; - it.compositeRule = $it.compositeRule = $wasComposite; - } else { - $it.schema = $aProperties; - $it.schemaPath = it.schemaPath + '.additionalProperties'; - $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; - $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + '[' + $key + ']'; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - } - } - it.errorPath = $currentErrorPath; - } - if ($someProperties) { - out += ' } '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - var $useDefaults = it.opts.useDefaults && !it.compositeRule; - if ($schemaKeys.length) { - var arr4 = $schemaKeys; - if (arr4) { - var $propertyKey, i4 = -1, - l4 = arr4.length - 1; - while (i4 < l4) { - $propertyKey = arr4[i4 += 1]; - var $sch = $schema[$propertyKey]; - if (it.util.schemaHasRules($sch, it.RULES.all)) { - var $prop = it.util.getProperty($propertyKey), - $passData = $data + $prop, - $hasDefault = $useDefaults && $sch.default !== undefined; - $it.schema = $sch; - $it.schemaPath = $schemaPath + $prop; - $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); - $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); - $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - $code = it.util.varReplace($code, $nextData, $passData); - var $useData = $passData; - } else { - var $useData = $nextData; - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; - } - if ($hasDefault) { - out += ' ' + ($code) + ' '; - } else { - if ($requiredHash && $requiredHash[$propertyKey]) { - out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = false; '; - var $currentErrorPath = it.errorPath, - $currErrSchemaPath = $errSchemaPath, - $missingProperty = it.util.escapeQuotes($propertyKey); - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); - } - $errSchemaPath = it.errSchemaPath + '/required'; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - $errSchemaPath = $currErrSchemaPath; - it.errorPath = $currentErrorPath; - out += ' } else { '; - } else { - if ($breakOnError) { - out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = true; } else { '; - } else { - out += ' if (' + ($useData) + ' !== undefined) { '; - } - } - out += ' ' + ($code) + ' } '; - } - } - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - var arr5 = $pPropertyKeys; - if (arr5) { - var $pProperty, i5 = -1, - l5 = arr5.length - 1; - while (i5 < l5) { - $pProperty = arr5[i5 += 1]; - var $sch = $pProperties[$pProperty]; - if (it.util.schemaHasRules($sch, it.RULES.all)) { - $it.schema = $sch; - $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); - $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); - out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; - if ($ownProperties) { - out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; - } - out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + '[' + $key + ']'; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else ' + ($nextValid) + ' = true; '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - } - } - } - if (it.opts.v5) { - var arr6 = $pgPropertyKeys; - if (arr6) { - var $pgProperty, i6 = -1, - l6 = arr6.length - 1; - while (i6 < l6) { - $pgProperty = arr6[i6 += 1]; - var $pgSchema = $pgProperties[$pgProperty], - $sch = $pgSchema.schema; - if (it.util.schemaHasRules($sch, it.RULES.all)) { - $it.schema = $sch; - $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema'; - $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema'; - out += ' var pgPropCount' + ($lvl) + ' = 0; for (var ' + ($key) + ' in ' + ($data) + ') { '; - if ($ownProperties) { - out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; - } - out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; '; - $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); - var $passData = $data + '[' + $key + ']'; - $it.dataPathArr[$dataNxt] = $key; - var $code = it.validate($it); - $it.baseId = $currentBaseId; - if (it.util.varOccurences($code, $nextData) < 2) { - out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; - } else { - out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; - } - if ($breakOnError) { - out += ' if (!' + ($nextValid) + ') break; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else ' + ($nextValid) + ' = true; '; - } - out += ' } '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - $closingBraces += '}'; - } - var $pgMin = $pgSchema.minimum, - $pgMax = $pgSchema.maximum; - if ($pgMin !== undefined || $pgMax !== undefined) { - out += ' var ' + ($valid) + ' = true; '; - var $currErrSchemaPath = $errSchemaPath; - if ($pgMin !== undefined) { - var $limit = $pgMin, - $reason = 'minimum', - $moreOrLess = 'less'; - out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; '; - $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum'; - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - if ($pgMax !== undefined) { - out += ' else '; - } - } - if ($pgMax !== undefined) { - var $limit = $pgMax, - $reason = 'maximum', - $moreOrLess = 'more'; - out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; '; - $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum'; - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - } - $errSchemaPath = $currErrSchemaPath; - if ($breakOnError) { - out += ' if (' + ($valid) + ') { '; - $closingBraces += '}'; - } - } - } - } - } - } - if ($breakOnError) { - out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; - } - out = it.util.cleanUpCode(out); - return out; -} +function write(cert, options) { + var sig = cert.signatures.x509; + assert.object(sig, 'x509 signature'); + var der = new asn1.BerWriter(); + der.startSequence(); + if (sig.cache) { + der._ensure(sig.cache.length); + sig.cache.copy(der._buf, der._offset); + der._offset += sig.cache.length; + } else { + writeTBSCert(cert, der); + } -/***/ }), -/* 307 */ -/***/ (function(module, exports, __webpack_require__) { + der.startSequence(); + der.writeOID(SIGN_ALGS[sig.algo]); + if (sig.algo.match(/^rsa-/)) + der.writeNull(); + der.endSequence(); -"use strict"; + var sigData = sig.signature.toBuffer('asn1'); + var data = new Buffer(sigData.length + 1); + data[0] = 0; + sigData.copy(data, 1); + der.writeBuffer(data, asn1.Ber.BitString); + der.endSequence(); -module.exports = function generate_ref(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $async, $refCode; - if ($schema == '#' || $schema == '#/') { - if (it.isRoot) { - $async = it.async; - $refCode = 'validate'; - } else { - $async = it.root.schema.$async === true; - $refCode = 'root.refVal[0]'; - } - } else { - var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); - if ($refVal === undefined) { - var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId; - if (it.opts.missingRefs == 'fail') { - console.log($message); - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; - } - if (it.opts.verbose) { - out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - if ($breakOnError) { - out += ' if (false) { '; - } - } else if (it.opts.missingRefs == 'ignore') { - console.log($message); - if ($breakOnError) { - out += ' if (true) { '; - } - } else { - var $error = new Error($message); - $error.missingRef = it.resolve.url(it.baseId, $schema); - $error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef)); - throw $error; - } - } else if ($refVal.inline) { - var $it = it.util.copy(it); - $it.level++; - var $nextValid = 'valid' + $it.level; - $it.schema = $refVal.schema; - $it.schemaPath = ''; - $it.errSchemaPath = $schema; - var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); - out += ' ' + ($code) + ' '; - if ($breakOnError) { - out += ' if (' + ($nextValid) + ') { '; - } - } else { - $async = $refVal.$async === true; - $refCode = $refVal.code; - } - } - if ($refCode) { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; - if (it.opts.passContext) { - out += ' ' + ($refCode) + '.call(this, '; - } else { - out += ' ' + ($refCode) + '( '; - } - out += ' ' + ($data) + ', (dataPath || \'\')'; - if (it.errorPath != '""') { - out += ' + ' + (it.errorPath); - } - var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', - $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; - out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; - var __callValidate = out; - out = $$outStack.pop(); - if ($async) { - if (!it.async) throw new Error('async schema referenced by sync schema'); - out += ' try { '; - if ($breakOnError) { - out += 'var ' + ($valid) + ' ='; - } - out += ' ' + (it.yieldAwait) + ' ' + (__callValidate) + '; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } '; - if ($breakOnError) { - out += ' if (' + ($valid) + ') { '; - } - } else { - out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; - if ($breakOnError) { - out += ' else { '; - } - } - } - return out; + return (der.buffer); } +function writeTBSCert(cert, der) { + var sig = cert.signatures.x509; + assert.object(sig, 'x509 signature'); -/***/ }), -/* 308 */ -/***/ (function(module, exports, __webpack_require__) { + der.startSequence(); -"use strict"; - -module.exports = function generate_required(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - var $vSchema = 'schema' + $lvl; - if (!$isData) { - if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { - var $required = []; - var arr1 = $schema; - if (arr1) { - var $property, i1 = -1, - l1 = arr1.length - 1; - while (i1 < l1) { - $property = arr1[i1 += 1]; - var $propertySch = it.schema.properties[$property]; - if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) { - $required[$required.length] = $property; - } - } - } - } else { - var $required = $schema; - } - } - if ($isData || $required.length) { - var $currentErrorPath = it.errorPath, - $loopRequired = $isData || $required.length >= it.opts.loopRequired; - if ($breakOnError) { - out += ' var missing' + ($lvl) + '; '; - if ($loopRequired) { - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; - } - var $i = 'i' + $lvl, - $propertyPath = 'schema' + $lvl + '[' + $i + ']', - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - out += ' var ' + ($valid) + ' = true; '; - if ($isData) { - out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; - } - out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined; if (!' + ($valid) + ') break; } '; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { '; - } else { - out += ' if ( '; - var arr2 = $required; - if (arr2) { - var _$property, $i = -1, - l2 = arr2.length - 1; - while ($i < l2) { - _$property = arr2[$i += 1]; - if ($i) { - out += ' || '; - } - var $prop = it.util.getProperty(_$property); - out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) '; - } - } - out += ') { '; - var $propertyPath = 'missing' + $lvl, - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; - } - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } else { '; - } - } else { - if ($loopRequired) { - if (!$isData) { - out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; - } - var $i = 'i' + $lvl, - $propertyPath = 'schema' + $lvl + '[' + $i + ']', - $missingProperty = '\' + ' + $propertyPath + ' + \''; - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); - } - if ($isData) { - out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; - } - out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined) { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; - if ($isData) { - out += ' } '; - } - } else { - var arr3 = $required; - if (arr3) { - var $reqProperty, i3 = -1, - l3 = arr3.length - 1; - while (i3 < l3) { - $reqProperty = arr3[i3 += 1]; - var $prop = it.util.getProperty($reqProperty), - $missingProperty = it.util.escapeQuotes($reqProperty); - if (it.opts._errorDataPathProperty) { - it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers); - } - out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; - if (it.opts.messages !== false) { - out += ' , message: \''; - if (it.opts._errorDataPathProperty) { - out += 'is a required property'; - } else { - out += 'should have required property \\\'' + ($missingProperty) + '\\\''; - } - out += '\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; - } - } - } - } - it.errorPath = $currentErrorPath; - } else if ($breakOnError) { - out += ' if (true) {'; - } - return out; -} - - -/***/ }), -/* 309 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = function generate_switch(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $errs = 'errs__' + $lvl; - var $it = it.util.copy(it); - var $closingBraces = ''; - $it.level++; - var $nextValid = 'valid' + $it.level; - var $ifPassed = 'ifPassed' + it.level, - $currentBaseId = $it.baseId, - $shouldContinue; - out += 'var ' + ($ifPassed) + ';'; - var arr1 = $schema; - if (arr1) { - var $sch, $caseIndex = -1, - l1 = arr1.length - 1; - while ($caseIndex < l1) { - $sch = arr1[$caseIndex += 1]; - if ($caseIndex && !$shouldContinue) { - out += ' if (!' + ($ifPassed) + ') { '; - $closingBraces += '}'; - } - if ($sch.if && it.util.schemaHasRules($sch.if, it.RULES.all)) { - out += ' var ' + ($errs) + ' = errors; '; - var $wasComposite = it.compositeRule; - it.compositeRule = $it.compositeRule = true; - $it.createErrors = false; - $it.schema = $sch.if; - $it.schemaPath = $schemaPath + '[' + $caseIndex + '].if'; - $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if'; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - $it.createErrors = true; - it.compositeRule = $it.compositeRule = $wasComposite; - out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') { '; - if (typeof $sch.then == 'boolean') { - if ($sch.then === false) { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should pass "switch" keyword validation\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - } - out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; - } else { - $it.schema = $sch.then; - $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; - $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - } - out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } '; - } else { - out += ' ' + ($ifPassed) + ' = true; '; - if (typeof $sch.then == 'boolean') { - if ($sch.then === false) { - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; - if (it.opts.messages !== false) { - out += ' , message: \'should pass "switch" keyword validation\' '; - } - if (it.opts.verbose) { - out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - } - out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; - } else { - $it.schema = $sch.then; - $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; - $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; - out += ' ' + (it.validate($it)) + ' '; - $it.baseId = $currentBaseId; - } - } - $shouldContinue = $sch.continue - } - } - out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + '; '; - out = it.util.cleanUpCode(out); - return out; -} - - -/***/ }), -/* 310 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -module.exports = function generate_uniqueItems(it, $keyword) { - var out = ' '; - var $lvl = it.level; - var $dataLvl = it.dataLevel; - var $schema = it.schema[$keyword]; - var $schemaPath = it.schemaPath + it.util.getProperty($keyword); - var $errSchemaPath = it.errSchemaPath + '/' + $keyword; - var $breakOnError = !it.opts.allErrors; - var $data = 'data' + ($dataLvl || ''); - var $valid = 'valid' + $lvl; - var $isData = it.opts.v5 && $schema && $schema.$data, - $schemaValue; - if ($isData) { - out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; - $schemaValue = 'schema' + $lvl; - } else { - $schemaValue = $schema; - } - if (($schema || $isData) && it.opts.uniqueItems !== false) { - if ($isData) { - out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; - } - out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } '; - if ($isData) { - out += ' } '; - } - out += ' if (!' + ($valid) + ') { '; - var $$outStack = $$outStack || []; - $$outStack.push(out); - out = ''; /* istanbul ignore else */ - if (it.createErrors !== false) { - out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; - if (it.opts.messages !== false) { - out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; - } - if (it.opts.verbose) { - out += ' , schema: '; - if ($isData) { - out += 'validate.schema' + ($schemaPath); - } else { - out += '' + ($schema); - } - out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; - } - out += ' } '; - } else { - out += ' {} '; - } - var __err = out; - out = $$outStack.pop(); - if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ - if (it.async) { - out += ' throw new ValidationError([' + (__err) + ']); '; - } else { - out += ' validate.errors = [' + (__err) + ']; return false; '; - } - } else { - out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; - } - out += ' } '; - if ($breakOnError) { - out += ' else { '; - } - } else { - if ($breakOnError) { - out += ' if (true) { '; - } - } - return out; -} + der.startSequence(Local(0)); + der.writeInt(2); + der.endSequence(); + der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer); -/***/ }), -/* 311 */ -/***/ (function(module, exports, __webpack_require__) { + der.startSequence(); + der.writeOID(SIGN_ALGS[sig.algo]); + der.endSequence(); -"use strict"; + cert.issuer.toAsn1(der); + der.startSequence(); + der.writeString(dateToUTCTime(cert.validFrom), asn1.Ber.UTCTime); + der.writeString(dateToUTCTime(cert.validUntil), asn1.Ber.UTCTime); + der.endSequence(); -var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i; -var customRuleCode = __webpack_require__(296); + var subject = cert.subjects[0]; + var altNames = cert.subjects.slice(1); + subject.toAsn1(der); -module.exports = { - add: addKeyword, - get: getKeyword, - remove: removeKeyword -}; + pkcs8.writePkcs8(der, cert.subjectKey); -/** - * Define custom keyword - * @this Ajv - * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). - * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. - */ -function addKeyword(keyword, definition) { - /* jshint validthis: true */ - /* eslint no-shadow: 0 */ - var RULES = this.RULES; + if (sig.extras && sig.extras.issuerUniqueID) { + der.writeBuffer(sig.extras.issuerUniqueID, Local(1)); + } - if (RULES.keywords[keyword]) - throw new Error('Keyword ' + keyword + ' is already defined'); + if (sig.extras && sig.extras.subjectUniqueID) { + der.writeBuffer(sig.extras.subjectUniqueID, Local(2)); + } - if (!IDENTIFIER.test(keyword)) - throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + if (altNames.length > 0 || subject.type === 'host' || + (cert.purposes !== undefined && cert.purposes.length > 0) || + (sig.extras && sig.extras.exts)) { + der.startSequence(Local(3)); + der.startSequence(); - if (definition) { - if (definition.macro && definition.valid !== undefined) - throw new Error('"valid" option cannot be used with macro keywords'); + var exts = []; + if (cert.purposes !== undefined && cert.purposes.length > 0) { + exts.push({ + oid: EXTS.basicConstraints, + critical: true + }); + exts.push({ + oid: EXTS.keyUsage, + critical: true + }); + exts.push({ + oid: EXTS.extKeyUsage, + critical: true + }); + } + exts.push({ oid: EXTS.altName }); + if (sig.extras && sig.extras.exts) + exts = sig.extras.exts; - var dataType = definition.type; - if (Array.isArray(dataType)) { - var i, len = dataType.length; - for (i=0; i<len; i++) checkDataType(dataType[i]); - for (i=0; i<len; i++) _addRule(keyword, dataType[i], definition); - } else { - if (dataType) checkDataType(dataType); - _addRule(keyword, dataType, definition); - } + for (var i = 0; i < exts.length; ++i) { + der.startSequence(); + der.writeOID(exts[i].oid); - var $data = definition.$data === true && this._opts.v5; - if ($data && !definition.validate) - throw new Error('$data support: "validate" function is not defined'); + if (exts[i].critical !== undefined) + der.writeBoolean(exts[i].critical); - var metaSchema = definition.metaSchema; - if (metaSchema) { - if ($data) { - metaSchema = { - anyOf: [ - metaSchema, - { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#/definitions/$data' } - ] - }; - } - definition.validateSchema = this.compile(metaSchema, true); - } - } + if (exts[i].oid === EXTS.altName) { + der.startSequence(asn1.Ber.OctetString); + der.startSequence(); + if (subject.type === 'host') { + der.writeString(subject.hostname, + Context(2)); + } + for (var j = 0; j < altNames.length; ++j) { + if (altNames[j].type === 'host') { + der.writeString( + altNames[j].hostname, + ALTNAME.DNSName); + } else if (altNames[j].type === + 'email') { + der.writeString( + altNames[j].email, + ALTNAME.RFC822Name); + } else { + /* + * Encode anything else as a + * DN style name for now. + */ + der.startSequence( + ALTNAME.DirectoryName); + altNames[j].toAsn1(der); + der.endSequence(); + } + } + der.endSequence(); + der.endSequence(); + } else if (exts[i].oid === EXTS.basicConstraints) { + der.startSequence(asn1.Ber.OctetString); + der.startSequence(); + var ca = (cert.purposes.indexOf('ca') !== -1); + var pathLen = exts[i].pathLen; + der.writeBoolean(ca); + if (pathLen !== undefined) + der.writeInt(pathLen); + der.endSequence(); + der.endSequence(); + } else if (exts[i].oid === EXTS.extKeyUsage) { + der.startSequence(asn1.Ber.OctetString); + der.startSequence(); + cert.purposes.forEach(function (purpose) { + if (purpose === 'ca') + return; + if (KEYUSEBITS.indexOf(purpose) !== -1) + return; + var oid = purpose; + if (EXTPURPOSE[purpose] !== undefined) + oid = EXTPURPOSE[purpose]; + der.writeOID(oid); + }); + der.endSequence(); + der.endSequence(); + } else if (exts[i].oid === EXTS.keyUsage) { + der.startSequence(asn1.Ber.OctetString); + /* + * If we parsed this certificate from a byte + * stream (i.e. we didn't generate it in sshpk) + * then we'll have a ".bits" property on the + * ext with the original raw byte contents. + * + * If we have this, use it here instead of + * regenerating it. This guarantees we output + * the same data we parsed, so signatures still + * validate. + */ + if (exts[i].bits !== undefined) { + der.writeBuffer(exts[i].bits, + asn1.Ber.BitString); + } else { + var bits = writeBitField(cert.purposes, + KEYUSEBITS); + der.writeBuffer(bits, + asn1.Ber.BitString); + } + der.endSequence(); + } else { + der.writeBuffer(exts[i].data, + asn1.Ber.OctetString); + } - RULES.keywords[keyword] = RULES.all[keyword] = true; + der.endSequence(); + } + der.endSequence(); + der.endSequence(); + } - function _addRule(keyword, dataType, definition) { - var ruleGroup; - for (var i=0; i<RULES.length; i++) { - var rg = RULES[i]; - if (rg.type == dataType) { - ruleGroup = rg; - break; - } - } + der.endSequence(); +} - if (!ruleGroup) { - ruleGroup = { type: dataType, rules: [] }; - RULES.push(ruleGroup); - } +/* + * Reads an ASN.1 BER bitfield out of the Buffer produced by doing + * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw + * contents of the BitString tag, which is a count of unused bits followed by + * the bits as a right-padded byte string. + * + * `bits` is the Buffer, `bitIndex` should contain an array of string names + * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec. + * + * Returns an array of Strings, the names of the bits that were set to 1. + */ +function readBitField(bits, bitIndex) { + var bitLen = 8 * (bits.length - 1) - bits[0]; + var setBits = {}; + for (var i = 0; i < bitLen; ++i) { + var byteN = 1 + Math.floor(i / 8); + var bit = 7 - (i % 8); + var mask = 1 << bit; + var bitVal = ((bits[byteN] & mask) !== 0); + var name = bitIndex[i]; + if (bitVal && typeof (name) === 'string') { + setBits[name] = true; + } + } + return (Object.keys(setBits)); +} - var rule = { - keyword: keyword, - definition: definition, - custom: true, - code: customRuleCode - }; - ruleGroup.rules.push(rule); - RULES.custom[keyword] = rule; +/* + * `setBits` is an array of strings, containing the names for each bit that + * sould be set to 1. `bitIndex` is same as in `readBitField()`. + * + * Returns a Buffer, ready to be written out with `BerWriter#writeString()`. + */ +function writeBitField(setBits, bitIndex) { + var bitLen = bitIndex.length; + var blen = Math.ceil(bitLen / 8); + var unused = blen * 8 - bitLen; + var bits = new Buffer(1 + blen); + bits.fill(0); + bits[0] = unused; + for (var i = 0; i < bitLen; ++i) { + var byteN = 1 + Math.floor(i / 8); + var bit = 7 - (i % 8); + var mask = 1 << bit; + var name = bitIndex[i]; + if (name === undefined) + continue; + var bitVal = (setBits.indexOf(name) !== -1); + if (bitVal) { + bits[byteN] |= mask; + } + } + return (bits); +} + + +/***/ }), +/* 321 */ +/***/ (function(module, exports) { + +var ZEROS = '0000000000000000000' +var SEVENS = '7777777777777777777' +var ZERO_OFFSET = '0'.charCodeAt(0) +var USTAR = 'ustar\x0000' +var MASK = parseInt('7777', 8) + +var clamp = function (index, len, defaultValue) { + if (typeof index !== 'number') return defaultValue + index = ~~index // Coerce to integer. + if (index >= len) return len + if (index >= 0) return index + index += len + if (index >= 0) return index + return 0 +} + +var toType = function (flag) { + switch (flag) { + case 0: + return 'file' + case 1: + return 'link' + case 2: + return 'symlink' + case 3: + return 'character-device' + case 4: + return 'block-device' + case 5: + return 'directory' + case 6: + return 'fifo' + case 7: + return 'contiguous-file' + case 72: + return 'pax-header' + case 55: + return 'pax-global-header' + case 27: + return 'gnu-long-link-path' + case 28: + case 30: + return 'gnu-long-path' } + return null +} - function checkDataType(dataType) { - if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType); +var toTypeflag = function (flag) { + switch (flag) { + case 'file': + return 0 + case 'link': + return 1 + case 'symlink': + return 2 + case 'character-device': + return 3 + case 'block-device': + return 4 + case 'directory': + return 5 + case 'fifo': + return 6 + case 'contiguous-file': + return 7 + case 'pax-header': + return 72 } + + return 0 } +var alloc = function (size) { + var buf = new Buffer(size) + buf.fill(0) + return buf +} -/** - * Get keyword - * @this Ajv - * @param {String} keyword pre-defined or custom keyword. - * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. - */ -function getKeyword(keyword) { - /* jshint validthis: true */ - var rule = this.RULES.custom[keyword]; - return rule ? rule.definition : this.RULES.keywords[keyword] || false; +var indexOf = function (block, num, offset, end) { + for (; offset < end; offset++) { + if (block[offset] === num) return offset + } + return end } +var cksum = function (block) { + var sum = 8 * 32 + for (var i = 0; i < 148; i++) sum += block[i] + for (var j = 156; j < 512; j++) sum += block[j] + return sum +} -/** - * Remove keyword - * @this Ajv - * @param {String} keyword pre-defined or custom keyword. +var encodeOct = function (val, n) { + val = val.toString(8) + if (val.length > n) return SEVENS.slice(0, n) + ' ' + else return ZEROS.slice(0, n - val.length) + val + ' ' +} + +/* Copied from the node-tar repo and modified to meet + * tar-stream coding standard. + * + * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349 */ -function removeKeyword(keyword) { - /* jshint validthis: true */ - var RULES = this.RULES; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - delete RULES.custom[keyword]; - for (var i=0; i<RULES.length; i++) { - var rules = RULES[i].rules; - for (var j=0; j<rules.length; j++) { - if (rules[j].keyword == keyword) { - rules.splice(j, 1); - break; - } +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + var positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null + + // build up a base-256 tuple from the least sig to the highest + var zero = false + var tuple = [] + for (var i = buf.length - 1; i > 0; i--) { + var byte = buf[i] + if (positive) tuple.push(byte) + else if (zero && byte === 0) tuple.push(0) + else if (zero) { + zero = false + tuple.push(0x100 - byte) + } else tuple.push(0xFF - byte) + } + + var sum = 0 + var l = tuple.length + for (i = 0; i < l; i++) { + sum += tuple[i] * Math.pow(256, i) + } + + return positive ? sum : -1 * sum +} + +var decodeOct = function (val, offset, length) { + val = val.slice(offset, offset + length) + offset = 0 + + // If prefixed with 0x80 then parse as a base-256 integer + if (val[offset] & 0x80) { + return parse256(val) + } else { + // Older versions of tar can prefix with spaces + while (offset < val.length && val[offset] === 32) offset++ + var end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length) + while (offset < end && val[offset] === 0) offset++ + if (end === offset) return 0 + return parseInt(val.slice(offset, end).toString(), 8) + } +} + +var decodeStr = function (val, offset, length) { + return val.slice(offset, indexOf(val, 0, offset, offset + length)).toString() +} + +var addLength = function (str) { + var len = Buffer.byteLength(str) + var digits = Math.floor(Math.log(len) / Math.log(10)) + 1 + if (len + digits > Math.pow(10, digits)) digits++ + + return (len + digits) + str +} + +exports.decodeLongPath = function (buf) { + return decodeStr(buf, 0, buf.length) +} + +exports.encodePax = function (opts) { // TODO: encode more stuff in pax + var result = '' + if (opts.name) result += addLength(' path=' + opts.name + '\n') + if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\n') + var pax = opts.pax + if (pax) { + for (var key in pax) { + result += addLength(' ' + key + '=' + pax[key] + '\n') } } + return new Buffer(result) +} + +exports.decodePax = function (buf) { + var result = {} + + while (buf.length) { + var i = 0 + while (i < buf.length && buf[i] !== 32) i++ + var len = parseInt(buf.slice(0, i).toString(), 10) + if (!len) return result + + var b = buf.slice(i + 1, len - 1).toString() + var keyIndex = b.indexOf('=') + if (keyIndex === -1) return result + result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1) + + buf = buf.slice(len) + } + + return result +} + +exports.encode = function (opts) { + var buf = alloc(512) + var name = opts.name + var prefix = '' + + if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/' + if (Buffer.byteLength(name) !== name.length) return null // utf-8 + + while (Buffer.byteLength(name) > 100) { + var i = name.indexOf('/') + if (i === -1) return null + prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i) + name = name.slice(i + 1) + } + + if (Buffer.byteLength(name) > 100 || Buffer.byteLength(prefix) > 155) return null + if (opts.linkname && Buffer.byteLength(opts.linkname) > 100) return null + + buf.write(name) + buf.write(encodeOct(opts.mode & MASK, 6), 100) + buf.write(encodeOct(opts.uid, 6), 108) + buf.write(encodeOct(opts.gid, 6), 116) + buf.write(encodeOct(opts.size, 11), 124) + buf.write(encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136) + + buf[156] = ZERO_OFFSET + toTypeflag(opts.type) + + if (opts.linkname) buf.write(opts.linkname, 157) + + buf.write(USTAR, 257) + if (opts.uname) buf.write(opts.uname, 265) + if (opts.gname) buf.write(opts.gname, 297) + buf.write(encodeOct(opts.devmajor || 0, 6), 329) + buf.write(encodeOct(opts.devminor || 0, 6), 337) + + if (prefix) buf.write(prefix, 345) + + buf.write(encodeOct(cksum(buf), 6), 148) + + return buf +} + +exports.decode = function (buf) { + var typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET + + var name = decodeStr(buf, 0, 100) + var mode = decodeOct(buf, 100, 8) + var uid = decodeOct(buf, 108, 8) + var gid = decodeOct(buf, 116, 8) + var size = decodeOct(buf, 124, 12) + var mtime = decodeOct(buf, 136, 12) + var type = toType(typeflag) + var linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100) + var uname = decodeStr(buf, 265, 32) + var gname = decodeStr(buf, 297, 32) + var devmajor = decodeOct(buf, 329, 8) + var devminor = decodeOct(buf, 337, 8) + + if (buf[345]) name = decodeStr(buf, 345, 155) + '/' + name + + // to support old tar versions that use trailing / to indicate dirs + if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5 + + var c = cksum(buf) + + // checksum is still initial value if header was null. + if (c === 8 * 32) return null + + // valid checksum + if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?') + + return { + name: name, + mode: mode, + uid: uid, + gid: gid, + size: size, + mtime: new Date(1000 * mtime), + type: type, + linkname: linkname, + uname: uname, + gname: gname, + devmajor: devmajor, + devminor: devminor + } } /***/ }), -/* 312 */ -/***/ (function(module, exports) { +/* 322 */ +/***/ (function(module, exports, __webpack_require__) { + +exports.extract = __webpack_require__(639) +exports.pack = __webpack_require__(640) -module.exports = { - "id": "http://json-schema.org/draft-04/schema#", - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "Core schema meta-schema", - "definitions": { - "schemaArray": { - "type": "array", - "minItems": 1, - "items": { - "$ref": "#" - } - }, - "positiveInteger": { - "type": "integer", - "minimum": 0 - }, - "positiveIntegerDefault0": { - "allOf": [ - { - "$ref": "#/definitions/positiveInteger" - }, - { - "default": 0 - } - ] - }, - "simpleTypes": { - "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] - }, - "stringArray": { - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - } - }, - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uri" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "default": {}, - "multipleOf": { - "type": "number", - "minimum": 0, - "exclusiveMinimum": true - }, - "maximum": { - "type": "number" - }, - "exclusiveMaximum": { - "type": "boolean", - "default": false - }, - "minimum": { - "type": "number" - }, - "exclusiveMinimum": { - "type": "boolean", - "default": false - }, - "maxLength": { - "$ref": "#/definitions/positiveInteger" - }, - "minLength": { - "$ref": "#/definitions/positiveIntegerDefault0" - }, - "pattern": { - "type": "string", - "format": "regex" - }, - "additionalItems": { - "anyOf": [ - { - "type": "boolean" - }, - { - "$ref": "#" - } - ], - "default": {} - }, - "items": { - "anyOf": [ - { - "$ref": "#" - }, - { - "$ref": "#/definitions/schemaArray" - } - ], - "default": {} - }, - "maxItems": { - "$ref": "#/definitions/positiveInteger" - }, - "minItems": { - "$ref": "#/definitions/positiveIntegerDefault0" - }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxProperties": { - "$ref": "#/definitions/positiveInteger" - }, - "minProperties": { - "$ref": "#/definitions/positiveIntegerDefault0" - }, - "required": { - "$ref": "#/definitions/stringArray" - }, - "additionalProperties": { - "anyOf": [ - { - "type": "boolean" - }, - { - "$ref": "#" - } - ], - "default": {} - }, - "definitions": { - "type": "object", - "additionalProperties": { - "$ref": "#" - }, - "default": {} - }, - "properties": { - "type": "object", - "additionalProperties": { - "$ref": "#" - }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { - "$ref": "#" - }, - "default": {} - }, - "dependencies": { - "type": "object", - "additionalProperties": { - "anyOf": [ - { - "$ref": "#" - }, - { - "$ref": "#/definitions/stringArray" - } - ] - } - }, - "enum": { - "type": "array", - "minItems": 1, - "uniqueItems": true - }, - "type": { - "anyOf": [ - { - "$ref": "#/definitions/simpleTypes" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/simpleTypes" - }, - "minItems": 1, - "uniqueItems": true - } - ] - }, - "allOf": { - "$ref": "#/definitions/schemaArray" - }, - "anyOf": { - "$ref": "#/definitions/schemaArray" - }, - "oneOf": { - "$ref": "#/definitions/schemaArray" - }, - "not": { - "$ref": "#" - } - }, - "dependencies": { - "exclusiveMaximum": [ - "maximum" - ], - "exclusiveMinimum": [ - "minimum" - ] - }, - "default": {} -}; /***/ }), -/* 313 */ -/***/ (function(module, exports) { - -module.exports = { - "id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#", - "$schema": "http://json-schema.org/draft-04/schema#", - "description": "Core schema meta-schema (v5 proposals)", - "definitions": { - "schemaArray": { - "type": "array", - "minItems": 1, - "items": { - "$ref": "#" - } - }, - "positiveInteger": { - "type": "integer", - "minimum": 0 - }, - "positiveIntegerDefault0": { - "allOf": [ - { - "$ref": "#/definitions/positiveInteger" - }, - { - "default": 0 - } - ] - }, - "simpleTypes": { - "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] - }, - "stringArray": { - "type": "array", - "items": { - "type": "string" - }, - "minItems": 1, - "uniqueItems": true - }, - "$data": { - "type": "object", - "required": [ - "$data" - ], - "properties": { - "$data": { - "type": "string", - "anyOf": [ - { - "format": "relative-json-pointer" - }, - { - "format": "json-pointer" - } - ] - } - }, - "additionalProperties": false - } - }, - "type": "object", - "properties": { - "id": { - "type": "string", - "format": "uri" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "title": { - "type": "string" - }, - "description": { - "type": "string" - }, - "default": {}, - "multipleOf": { - "anyOf": [ - { - "type": "number", - "minimum": 0, - "exclusiveMinimum": true - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "maximum": { - "anyOf": [ - { - "type": "number" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "exclusiveMaximum": { - "anyOf": [ - { - "type": "boolean", - "default": false - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "minimum": { - "anyOf": [ - { - "type": "number" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "exclusiveMinimum": { - "anyOf": [ - { - "type": "boolean", - "default": false - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "maxLength": { - "anyOf": [ - { - "$ref": "#/definitions/positiveInteger" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "minLength": { - "anyOf": [ - { - "$ref": "#/definitions/positiveIntegerDefault0" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "pattern": { - "anyOf": [ - { - "type": "string", - "format": "regex" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "additionalItems": { - "anyOf": [ - { - "type": "boolean" - }, - { - "$ref": "#" - }, - { - "$ref": "#/definitions/$data" - } - ], - "default": {} - }, - "items": { - "anyOf": [ - { - "$ref": "#" - }, - { - "$ref": "#/definitions/schemaArray" - } - ], - "default": {} - }, - "maxItems": { - "anyOf": [ - { - "$ref": "#/definitions/positiveInteger" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "minItems": { - "anyOf": [ - { - "$ref": "#/definitions/positiveIntegerDefault0" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "uniqueItems": { - "anyOf": [ - { - "type": "boolean", - "default": false - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "maxProperties": { - "anyOf": [ - { - "$ref": "#/definitions/positiveInteger" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "minProperties": { - "anyOf": [ - { - "$ref": "#/definitions/positiveIntegerDefault0" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "required": { - "anyOf": [ - { - "$ref": "#/definitions/stringArray" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "additionalProperties": { - "anyOf": [ - { - "type": "boolean" - }, - { - "$ref": "#" - }, - { - "$ref": "#/definitions/$data" - } - ], - "default": {} - }, - "definitions": { - "type": "object", - "additionalProperties": { - "$ref": "#" - }, - "default": {} - }, - "properties": { - "type": "object", - "additionalProperties": { - "$ref": "#" - }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { - "$ref": "#" - }, - "default": {} - }, - "dependencies": { - "type": "object", - "additionalProperties": { - "anyOf": [ - { - "$ref": "#" - }, - { - "$ref": "#/definitions/stringArray" - } - ] - } - }, - "enum": { - "anyOf": [ - { - "type": "array", - "minItems": 1, - "uniqueItems": true - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "type": { - "anyOf": [ - { - "$ref": "#/definitions/simpleTypes" - }, - { - "type": "array", - "items": { - "$ref": "#/definitions/simpleTypes" - }, - "minItems": 1, - "uniqueItems": true - } - ] - }, - "allOf": { - "$ref": "#/definitions/schemaArray" - }, - "anyOf": { - "$ref": "#/definitions/schemaArray" - }, - "oneOf": { - "$ref": "#/definitions/schemaArray" - }, - "not": { - "$ref": "#" - }, - "format": { - "anyOf": [ - { - "type": "string" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "formatMaximum": { - "anyOf": [ - { - "type": "string" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "formatMinimum": { - "anyOf": [ - { - "type": "string" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "formatExclusiveMaximum": { - "anyOf": [ - { - "type": "boolean", - "default": false - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "formatExclusiveMinimum": { - "anyOf": [ - { - "type": "boolean", - "default": false - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "constant": { - "anyOf": [ - {}, - { - "$ref": "#/definitions/$data" - } - ] - }, - "contains": { - "$ref": "#" - }, - "patternGroups": { - "type": "object", - "additionalProperties": { - "type": "object", - "required": [ - "schema" - ], - "properties": { - "maximum": { - "anyOf": [ - { - "$ref": "#/definitions/positiveInteger" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "minimum": { - "anyOf": [ - { - "$ref": "#/definitions/positiveIntegerDefault0" - }, - { - "$ref": "#/definitions/$data" - } - ] - }, - "schema": { - "$ref": "#" - } - }, - "additionalProperties": false - }, - "default": {} - }, - "switch": { - "type": "array", - "items": { - "required": [ - "then" - ], - "properties": { - "if": { - "$ref": "#" - }, - "then": { - "anyOf": [ - { - "type": "boolean" - }, - { - "$ref": "#" - } - ] - }, - "continue": { - "type": "boolean" - } - }, - "additionalProperties": false, - "dependencies": { - "continue": [ - "if" - ] - } - } - } - }, - "dependencies": { - "exclusiveMaximum": [ - "maximum" - ], - "exclusiveMinimum": [ - "minimum" - ], - "formatMaximum": [ - "format" - ], - "formatMinimum": [ - "format" - ], - "formatExclusiveMaximum": [ - "formatMaximum" - ], - "formatExclusiveMinimum": [ - "formatMinimum" - ] - }, - "default": {} -}; - -/***/ }), -/* 314 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var META_SCHEMA_ID = 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json'; - -module.exports = { - enable: enableV5, - META_SCHEMA_ID: META_SCHEMA_ID -}; - - -function enableV5(ajv) { - var inlineFunctions = { - 'switch': __webpack_require__(309), - 'constant': __webpack_require__(295), - '_formatLimit': __webpack_require__(292), - 'patternRequired': __webpack_require__(305) - }; - - if (ajv._opts.meta !== false) { - var metaSchema = __webpack_require__(313); - ajv.addMetaSchema(metaSchema, META_SCHEMA_ID); - } - _addKeyword('constant'); - ajv.addKeyword('contains', { type: 'array', macro: containsMacro }); - - _addKeyword('formatMaximum', 'string', inlineFunctions._formatLimit); - _addKeyword('formatMinimum', 'string', inlineFunctions._formatLimit); - ajv.addKeyword('formatExclusiveMaximum'); - ajv.addKeyword('formatExclusiveMinimum'); - - ajv.addKeyword('patternGroups'); // implemented in properties.jst - _addKeyword('patternRequired', 'object'); - _addKeyword('switch'); +/* 323 */ +/***/ (function(module, exports, __webpack_require__) { +var Transform = __webpack_require__(597) + , inherits = __webpack_require__(2).inherits + , xtend = __webpack_require__(330) - function _addKeyword(keyword, types, inlineFunc) { - var definition = { - inline: inlineFunc || inlineFunctions[keyword], - statements: true, - errors: 'full' - }; - if (types) definition.type = types; - ajv.addKeyword(keyword, definition); - } +function DestroyableTransform(opts) { + Transform.call(this, opts) + this._destroyed = false } +inherits(DestroyableTransform, Transform) -function containsMacro(schema) { - return { - not: { items: { not: schema } } - }; +DestroyableTransform.prototype.destroy = function(err) { + if (this._destroyed) return + this._destroyed = true + + var self = this + process.nextTick(function() { + if (err) + self.emit('error', err) + self.emit('close') + }) } +// a noop _transform function +function noop (chunk, enc, callback) { + callback(null, chunk) +} -/***/ }), -/* 315 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var ESC = '\u001b['; -var x = module.exports; - -x.cursorTo = function (x, y) { - if (arguments.length === 0) { - return ESC + 'H'; - } - - if (arguments.length === 1) { - return ESC + (x + 1) + 'G'; - } - - return ESC + (y + 1) + ';' + (x + 1) + 'H'; -}; -x.cursorMove = function (x, y) { - var ret = ''; +// create a new export function, used by both the main export and +// the .ctor export, contains common logic for dealing with arguments +function through2 (construct) { + return function (options, transform, flush) { + if (typeof options == 'function') { + flush = transform + transform = options + options = {} + } - if (x < 0) { - ret += ESC + (-x) + 'D'; - } else if (x > 0) { - ret += ESC + x + 'C'; - } + if (typeof transform != 'function') + transform = noop - if (y < 0) { - ret += ESC + (-y) + 'A'; - } else if (y > 0) { - ret += ESC + y + 'B'; - } + if (typeof flush != 'function') + flush = null - return ret; -}; + return construct(options, transform, flush) + } +} -x.cursorUp = function (count) { - return ESC + (typeof count === 'number' ? count : 1) + 'A'; -}; -x.cursorDown = function (count) { - return ESC + (typeof count === 'number' ? count : 1) + 'B'; -}; +// main export, just make me a transform stream! +module.exports = through2(function (options, transform, flush) { + var t2 = new DestroyableTransform(options) -x.cursorForward = function (count) { - return ESC + (typeof count === 'number' ? count : 1) + 'C'; -}; + t2._transform = transform -x.cursorBackward = function (count) { - return ESC + (typeof count === 'number' ? count : 1) + 'D'; -}; + if (flush) + t2._flush = flush -x.cursorLeft = ESC + '1000D'; -x.cursorSavePosition = ESC + 's'; -x.cursorRestorePosition = ESC + 'u'; -x.cursorGetPosition = ESC + '6n'; -x.cursorNextLine = ESC + 'E'; -x.cursorPrevLine = ESC + 'F'; -x.cursorHide = ESC + '?25l'; -x.cursorShow = ESC + '?25h'; + return t2 +}) -x.eraseLines = function (count) { - var clear = ''; - for (var i = 0; i < count; i++) { - clear += x.cursorLeft + x.eraseEndLine + (i < count - 1 ? x.cursorUp() : ''); - } +// make me a reusable prototype that I can `new`, or implicitly `new` +// with a constructor call +module.exports.ctor = through2(function (options, transform, flush) { + function Through2 (override) { + if (!(this instanceof Through2)) + return new Through2(override) - return clear; -}; + this.options = xtend(options, override) -x.eraseEndLine = ESC + 'K'; -x.eraseStartLine = ESC + '1K'; -x.eraseLine = ESC + '2K'; -x.eraseDown = ESC + 'J'; -x.eraseUp = ESC + '1J'; -x.eraseScreen = ESC + '2J'; -x.scrollUp = ESC + 'S'; -x.scrollDown = ESC + 'T'; + DestroyableTransform.call(this, this.options) + } -x.clearScreen = '\u001bc'; -x.beep = '\u0007'; + inherits(Through2, DestroyableTransform) -x.image = function (buf, opts) { - opts = opts || {}; + Through2.prototype._transform = transform - var ret = '\u001b]1337;File=inline=1'; + if (flush) + Through2.prototype._flush = flush - if (opts.width) { - ret += ';width=' + opts.width; - } + return Through2 +}) - if (opts.height) { - ret += ';height=' + opts.height; - } - if (opts.preserveAspectRatio === false) { - ret += ';preserveAspectRatio=0'; - } +module.exports.obj = through2(function (options, transform, flush) { + var t2 = new DestroyableTransform(xtend({ objectMode: true, highWaterMark: 16 }, options)) - return ret + ':' + buf.toString('base64') + '\u0007'; -}; + t2._transform = transform -x.iTerm = {}; + if (flush) + t2._flush = flush -x.iTerm.setCwd = function (cwd) { - return '\u001b]50;CurrentDir=' + (cwd || process.cwd()) + '\u0007'; -}; + return t2 +}) /***/ }), -/* 316 */ +/* 324 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(module) { - -function assembleStyles () { - var styles = { - modifiers: { - reset: [0, 0], - bold: [1, 22], // 21 isn't widely supported and 22 does the same thing - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - colors: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39] - }, - bgColors: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49] - } - }; - - // fix humans - styles.colors.grey = styles.colors.gray; - - Object.keys(styles).forEach(function (groupName) { - var group = styles[groupName]; +/*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ - Object.keys(group).forEach(function (styleName) { - var style = group[styleName]; +/* + * "A request-path path-matches a given cookie-path if at least one of the + * following conditions holds:" + */ +function pathMatch (reqPath, cookiePath) { + // "o The cookie-path and the request-path are identical." + if (cookiePath === reqPath) { + return true; + } - styles[styleName] = group[styleName] = { - open: '\u001b[' + style[0] + 'm', - close: '\u001b[' + style[1] + 'm' - }; - }); + var idx = reqPath.indexOf(cookiePath); + if (idx === 0) { + // "o The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/")." + if (cookiePath.substr(-1) === "/") { + return true; + } - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - }); + // " o The cookie-path is a prefix of the request-path, and the first + // character of the request-path that is not included in the cookie- path + // is a %x2F ("/") character." + if (reqPath.substr(cookiePath.length, 1) === "/") { + return true; + } + } - return styles; + return false; } -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); +exports.pathMatch = pathMatch; -/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 317 */ +/* 325 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * arr-diff <https://github.com/jonschlinkert/arr-diff> + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. * - * Copyright (c) 2014 Jon Schlinkert, contributors. - * Licensed under the MIT License - */ - - - -var flatten = __webpack_require__(318); -var slice = [].slice; - -/** - * Return the difference between the first array and - * additional arrays. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * ```js - * var diff = require('{%= name %}'); + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. * - * var a = ['a', 'b', 'c', 'd']; - * var b = ['b', 'c']; + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. * - * console.log(diff(a, b)) - * //=> ['a', 'd'] - * ``` + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. * - * @param {Array} `a` - * @param {Array} `b` - * @return {Array} - * @api public + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ -function diff(arr, arrays) { - var argsLen = arguments.length; - var len = arr.length, i = -1; - var res = [], arrays; +var pubsuffix = __webpack_require__(326); - if (argsLen === 1) { - return arr; +// Gives the permutation of all possible domainMatch()es of a given domain. The +// array is in shortest-to-longest order. Handy for indexing. +function permuteDomain (domain) { + var pubSuf = pubsuffix.getPublicSuffix(domain); + if (!pubSuf) { + return null; } - - if (argsLen > 2) { - arrays = flatten(slice.call(arguments, 1)); + if (pubSuf == domain) { + return [domain]; } - while (++i < len) { - if (!~arrays.indexOf(arr[i])) { - res.push(arr[i]); - } + var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com" + var parts = prefix.split('.').reverse(); + var cur = pubSuf; + var permutations = [cur]; + while (parts.length) { + cur = parts.shift() + '.' + cur; + permutations.push(cur); } - return res; + return permutations; } -/** - * Expose `diff` - */ - -module.exports = diff; +exports.permuteDomain = permuteDomain; /***/ }), -/* 318 */ +/* 326 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * arr-flatten <https://github.com/jonschlinkert/arr-flatten> - * - * Copyright (c) 2014-2015, 2017, Jon Schlinkert. - * Released under the MIT License. - */ - +/**************************************************** + * AUTOMATICALLY GENERATED by generate-pubsuffix.js * + * DO NOT EDIT! * + ****************************************************/ -module.exports = function flatten(arr) { - return flat(arr, []); -}; -function flat(arr, acc) { - var len = arr.length; - var idx = -1; +var punycode = __webpack_require__(228); - while (++idx < len) { - var cur = arr[idx]; - if (Array.isArray(cur)) { - flat(cur, acc); - } else { - acc.push(cur); - } +module.exports.getPublicSuffix = function getPublicSuffix(domain) { + /*! + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + if (!domain) { + return null; + } + if (domain.match(/^\./)) { + return null; + } + var asciiDomain = punycode.toASCII(domain); + var converted = false; + if (asciiDomain !== domain) { + domain = asciiDomain; + converted = true; + } + if (index[domain]) { + return null; } - return acc; -} + domain = domain.toLowerCase(); + var parts = domain.split('.').reverse(); -/***/ }), -/* 319 */ -/***/ (function(module, exports, __webpack_require__) { + var suffix = ''; + var suffixLen = 0; + for (var i=0; i<parts.length; i++) { + var part = parts[i]; + var starstr = '*'+suffix; + var partstr = part+suffix; -"use strict"; + if (index[starstr]) { // star rule matches + suffixLen = i+1; + if (index[partstr] === false) { // exception rule matches (NB: false, not undefined) + suffixLen--; + } + } else if (index[partstr]) { // exact match, not exception + suffixLen = i+1; + } -module.exports = function (arr, predicate, ctx) { - if (typeof Array.prototype.findIndex === 'function') { - return arr.findIndex(predicate, ctx); - } + suffix = '.'+partstr; + } - if (typeof predicate !== 'function') { - throw new TypeError('predicate must be a function'); - } + if (index['*'+suffix]) { // *.domain exists (e.g. *.kyoto.jp for domain='kyoto.jp'); + return null; + } - var list = Object(arr); - var len = list.length; + suffixLen = suffixLen || 1; + if (parts.length > suffixLen) { + var publicSuffix = parts.slice(0,suffixLen+1).reverse().join('.'); + return converted ? punycode.toUnicode(publicSuffix) : publicSuffix; + } - if (len === 0) { - return -1; - } + return null; +}; - for (var i = 0; i < len; i++) { - if (predicate.call(ctx, list[i], i, list)) { - return i; - } - } +// The following generated structure is used under the MPL version 2.0 +// See public-suffix.txt for more information - return -1; -}; +var index = module.exports.index = Object.freeze( +{"ac":true,"com.ac":true,"edu.ac":true,"gov.ac":true,"net.ac":true,"mil.ac":true,"org.ac":true,"ad":true,"nom.ad":true,"ae":true,"co.ae":true,"net.ae":true,"org.ae":true,"sch.ae":true,"ac.ae":true,"gov.ae":true,"mil.ae":true,"aero":true,"accident-investigation.aero":true,"accident-prevention.aero":true,"aerobatic.aero":true,"aeroclub.aero":true,"aerodrome.aero":true,"agents.aero":true,"aircraft.aero":true,"airline.aero":true,"airport.aero":true,"air-surveillance.aero":true,"airtraffic.aero":true,"air-traffic-control.aero":true,"ambulance.aero":true,"amusement.aero":true,"association.aero":true,"author.aero":true,"ballooning.aero":true,"broker.aero":true,"caa.aero":true,"cargo.aero":true,"catering.aero":true,"certification.aero":true,"championship.aero":true,"charter.aero":true,"civilaviation.aero":true,"club.aero":true,"conference.aero":true,"consultant.aero":true,"consulting.aero":true,"control.aero":true,"council.aero":true,"crew.aero":true,"design.aero":true,"dgca.aero":true,"educator.aero":true,"emergency.aero":true,"engine.aero":true,"engineer.aero":true,"entertainment.aero":true,"equipment.aero":true,"exchange.aero":true,"express.aero":true,"federation.aero":true,"flight.aero":true,"freight.aero":true,"fuel.aero":true,"gliding.aero":true,"government.aero":true,"groundhandling.aero":true,"group.aero":true,"hanggliding.aero":true,"homebuilt.aero":true,"insurance.aero":true,"journal.aero":true,"journalist.aero":true,"leasing.aero":true,"logistics.aero":true,"magazine.aero":true,"maintenance.aero":true,"marketplace.aero":true,"media.aero":true,"microlight.aero":true,"modelling.aero":true,"navigation.aero":true,"parachuting.aero":true,"paragliding.aero":true,"passenger-association.aero":true,"pilot.aero":true,"press.aero":true,"production.aero":true,"recreation.aero":true,"repbody.aero":true,"res.aero":true,"research.aero":true,"rotorcraft.aero":true,"safety.aero":true,"scientist.aero":true,"services.aero":true,"show.aero":true,"skydiving.aero":true,"software.aero":true,"student.aero":true,"taxi.aero":true,"trader.aero":true,"trading.aero":true,"trainer.aero":true,"union.aero":true,"workinggroup.aero":true,"works.aero":true,"af":true,"gov.af":true,"com.af":true,"org.af":true,"net.af":true,"edu.af":true,"ag":true,"com.ag":true,"org.ag":true,"net.ag":true,"co.ag":true,"nom.ag":true,"ai":true,"off.ai":true,"com.ai":true,"net.ai":true,"org.ai":true,"al":true,"com.al":true,"edu.al":true,"gov.al":true,"mil.al":true,"net.al":true,"org.al":true,"am":true,"an":true,"com.an":true,"net.an":true,"org.an":true,"edu.an":true,"ao":true,"ed.ao":true,"gv.ao":true,"og.ao":true,"co.ao":true,"pb.ao":true,"it.ao":true,"aq":true,"ar":true,"com.ar":true,"edu.ar":true,"gob.ar":true,"gov.ar":true,"int.ar":true,"mil.ar":true,"net.ar":true,"org.ar":true,"tur.ar":true,"arpa":true,"e164.arpa":true,"in-addr.arpa":true,"ip6.arpa":true,"iris.arpa":true,"uri.arpa":true,"urn.arpa":true,"as":true,"gov.as":true,"asia":true,"at":true,"ac.at":true,"co.at":true,"gv.at":true,"or.at":true,"au":true,"com.au":true,"net.au":true,"org.au":true,"edu.au":true,"gov.au":true,"asn.au":true,"id.au":true,"info.au":true,"conf.au":true,"oz.au":true,"act.au":true,"nsw.au":true,"nt.au":true,"qld.au":true,"sa.au":true,"tas.au":true,"vic.au":true,"wa.au":true,"act.edu.au":true,"nsw.edu.au":true,"nt.edu.au":true,"qld.edu.au":true,"sa.edu.au":true,"tas.edu.au":true,"vic.edu.au":true,"wa.edu.au":true,"qld.gov.au":true,"sa.gov.au":true,"tas.gov.au":true,"vic.gov.au":true,"wa.gov.au":true,"aw":true,"com.aw":true,"ax":true,"az":true,"com.az":true,"net.az":true,"int.az":true,"gov.az":true,"org.az":true,"edu.az":true,"info.az":true,"pp.az":true,"mil.az":true,"name.az":true,"pro.az":true,"biz.az":true,"ba":true,"org.ba":true,"net.ba":true,"edu.ba":true,"gov.ba":true,"mil.ba":true,"unsa.ba":true,"unbi.ba":true,"co.ba":true,"com.ba":true,"rs.ba":true,"bb":true,"biz.bb":true,"co.bb":true,"com.bb":true,"edu.bb":true,"gov.bb":true,"info.bb":true,"net.bb":true,"org.bb":true,"store.bb":true,"tv.bb":true,"*.bd":true,"be":true,"ac.be":true,"bf":true,"gov.bf":true,"bg":true,"a.bg":true,"b.bg":true,"c.bg":true,"d.bg":true,"e.bg":true,"f.bg":true,"g.bg":true,"h.bg":true,"i.bg":true,"j.bg":true,"k.bg":true,"l.bg":true,"m.bg":true,"n.bg":true,"o.bg":true,"p.bg":true,"q.bg":true,"r.bg":true,"s.bg":true,"t.bg":true,"u.bg":true,"v.bg":true,"w.bg":true,"x.bg":true,"y.bg":true,"z.bg":true,"0.bg":true,"1.bg":true,"2.bg":true,"3.bg":true,"4.bg":true,"5.bg":true,"6.bg":true,"7.bg":true,"8.bg":true,"9.bg":true,"bh":true,"com.bh":true,"edu.bh":true,"net.bh":true,"org.bh":true,"gov.bh":true,"bi":true,"co.bi":true,"com.bi":true,"edu.bi":true,"or.bi":true,"org.bi":true,"biz":true,"bj":true,"asso.bj":true,"barreau.bj":true,"gouv.bj":true,"bm":true,"com.bm":true,"edu.bm":true,"gov.bm":true,"net.bm":true,"org.bm":true,"*.bn":true,"bo":true,"com.bo":true,"edu.bo":true,"gov.bo":true,"gob.bo":true,"int.bo":true,"org.bo":true,"net.bo":true,"mil.bo":true,"tv.bo":true,"br":true,"adm.br":true,"adv.br":true,"agr.br":true,"am.br":true,"arq.br":true,"art.br":true,"ato.br":true,"b.br":true,"bio.br":true,"blog.br":true,"bmd.br":true,"cim.br":true,"cng.br":true,"cnt.br":true,"com.br":true,"coop.br":true,"ecn.br":true,"eco.br":true,"edu.br":true,"emp.br":true,"eng.br":true,"esp.br":true,"etc.br":true,"eti.br":true,"far.br":true,"flog.br":true,"fm.br":true,"fnd.br":true,"fot.br":true,"fst.br":true,"g12.br":true,"ggf.br":true,"gov.br":true,"imb.br":true,"ind.br":true,"inf.br":true,"jor.br":true,"jus.br":true,"leg.br":true,"lel.br":true,"mat.br":true,"med.br":true,"mil.br":true,"mp.br":true,"mus.br":true,"net.br":true,"*.nom.br":true,"not.br":true,"ntr.br":true,"odo.br":true,"org.br":true,"ppg.br":true,"pro.br":true,"psc.br":true,"psi.br":true,"qsl.br":true,"radio.br":true,"rec.br":true,"slg.br":true,"srv.br":true,"taxi.br":true,"teo.br":true,"tmp.br":true,"trd.br":true,"tur.br":true,"tv.br":true,"vet.br":true,"vlog.br":true,"wiki.br":true,"zlg.br":true,"bs":true,"com.bs":true,"net.bs":true,"org.bs":true,"edu.bs":true,"gov.bs":true,"bt":true,"com.bt":true,"edu.bt":true,"gov.bt":true,"net.bt":true,"org.bt":true,"bv":true,"bw":true,"co.bw":true,"org.bw":true,"by":true,"gov.by":true,"mil.by":true,"com.by":true,"of.by":true,"bz":true,"com.bz":true,"net.bz":true,"org.bz":true,"edu.bz":true,"gov.bz":true,"ca":true,"ab.ca":true,"bc.ca":true,"mb.ca":true,"nb.ca":true,"nf.ca":true,"nl.ca":true,"ns.ca":true,"nt.ca":true,"nu.ca":true,"on.ca":true,"pe.ca":true,"qc.ca":true,"sk.ca":true,"yk.ca":true,"gc.ca":true,"cat":true,"cc":true,"cd":true,"gov.cd":true,"cf":true,"cg":true,"ch":true,"ci":true,"org.ci":true,"or.ci":true,"com.ci":true,"co.ci":true,"edu.ci":true,"ed.ci":true,"ac.ci":true,"net.ci":true,"go.ci":true,"asso.ci":true,"xn--aroport-bya.ci":true,"int.ci":true,"presse.ci":true,"md.ci":true,"gouv.ci":true,"*.ck":true,"www.ck":false,"cl":true,"gov.cl":true,"gob.cl":true,"co.cl":true,"mil.cl":true,"cm":true,"co.cm":true,"com.cm":true,"gov.cm":true,"net.cm":true,"cn":true,"ac.cn":true,"com.cn":true,"edu.cn":true,"gov.cn":true,"net.cn":true,"org.cn":true,"mil.cn":true,"xn--55qx5d.cn":true,"xn--io0a7i.cn":true,"xn--od0alg.cn":true,"ah.cn":true,"bj.cn":true,"cq.cn":true,"fj.cn":true,"gd.cn":true,"gs.cn":true,"gz.cn":true,"gx.cn":true,"ha.cn":true,"hb.cn":true,"he.cn":true,"hi.cn":true,"hl.cn":true,"hn.cn":true,"jl.cn":true,"js.cn":true,"jx.cn":true,"ln.cn":true,"nm.cn":true,"nx.cn":true,"qh.cn":true,"sc.cn":true,"sd.cn":true,"sh.cn":true,"sn.cn":true,"sx.cn":true,"tj.cn":true,"xj.cn":true,"xz.cn":true,"yn.cn":true,"zj.cn":true,"hk.cn":true,"mo.cn":true,"tw.cn":true,"co":true,"arts.co":true,"com.co":true,"edu.co":true,"firm.co":true,"gov.co":true,"info.co":true,"int.co":true,"mil.co":true,"net.co":true,"nom.co":true,"org.co":true,"rec.co":true,"web.co":true,"com":true,"coop":true,"cr":true,"ac.cr":true,"co.cr":true,"ed.cr":true,"fi.cr":true,"go.cr":true,"or.cr":true,"sa.cr":true,"cu":true,"com.cu":true,"edu.cu":true,"org.cu":true,"net.cu":true,"gov.cu":true,"inf.cu":true,"cv":true,"cw":true,"com.cw":true,"edu.cw":true,"net.cw":true,"org.cw":true,"cx":true,"gov.cx":true,"ac.cy":true,"biz.cy":true,"com.cy":true,"ekloges.cy":true,"gov.cy":true,"ltd.cy":true,"name.cy":true,"net.cy":true,"org.cy":true,"parliament.cy":true,"press.cy":true,"pro.cy":true,"tm.cy":true,"cz":true,"de":true,"dj":true,"dk":true,"dm":true,"com.dm":true,"net.dm":true,"org.dm":true,"edu.dm":true,"gov.dm":true,"do":true,"art.do":true,"com.do":true,"edu.do":true,"gob.do":true,"gov.do":true,"mil.do":true,"net.do":true,"org.do":true,"sld.do":true,"web.do":true,"dz":true,"com.dz":true,"org.dz":true,"net.dz":true,"gov.dz":true,"edu.dz":true,"asso.dz":true,"pol.dz":true,"art.dz":true,"ec":true,"com.ec":true,"info.ec":true,"net.ec":true,"fin.ec":true,"k12.ec":true,"med.ec":true,"pro.ec":true,"org.ec":true,"edu.ec":true,"gov.ec":true,"gob.ec":true,"mil.ec":true,"edu":true,"ee":true,"edu.ee":true,"gov.ee":true,"riik.ee":true,"lib.ee":true,"med.ee":true,"com.ee":true,"pri.ee":true,"aip.ee":true,"org.ee":true,"fie.ee":true,"eg":true,"com.eg":true,"edu.eg":true,"eun.eg":true,"gov.eg":true,"mil.eg":true,"name.eg":true,"net.eg":true,"org.eg":true,"sci.eg":true,"*.er":true,"es":true,"com.es":true,"nom.es":true,"org.es":true,"gob.es":true,"edu.es":true,"et":true,"com.et":true,"gov.et":true,"org.et":true,"edu.et":true,"biz.et":true,"name.et":true,"info.et":true,"net.et":true,"eu":true,"fi":true,"aland.fi":true,"*.fj":true,"*.fk":true,"fm":true,"fo":true,"fr":true,"com.fr":true,"asso.fr":true,"nom.fr":true,"prd.fr":true,"presse.fr":true,"tm.fr":true,"aeroport.fr":true,"assedic.fr":true,"avocat.fr":true,"avoues.fr":true,"cci.fr":true,"chambagri.fr":true,"chirurgiens-dentistes.fr":true,"experts-comptables.fr":true,"geometre-expert.fr":true,"gouv.fr":true,"greta.fr":true,"huissier-justice.fr":true,"medecin.fr":true,"notaires.fr":true,"pharmacien.fr":true,"port.fr":true,"veterinaire.fr":true,"ga":true,"gb":true,"gd":true,"ge":true,"com.ge":true,"edu.ge":true,"gov.ge":true,"org.ge":true,"mil.ge":true,"net.ge":true,"pvt.ge":true,"gf":true,"gg":true,"co.gg":true,"net.gg":true,"org.gg":true,"gh":true,"com.gh":true,"edu.gh":true,"gov.gh":true,"org.gh":true,"mil.gh":true,"gi":true,"com.gi":true,"ltd.gi":true,"gov.gi":true,"mod.gi":true,"edu.gi":true,"org.gi":true,"gl":true,"co.gl":true,"com.gl":true,"edu.gl":true,"net.gl":true,"org.gl":true,"gm":true,"gn":true,"ac.gn":true,"com.gn":true,"edu.gn":true,"gov.gn":true,"org.gn":true,"net.gn":true,"gov":true,"gp":true,"com.gp":true,"net.gp":true,"mobi.gp":true,"edu.gp":true,"org.gp":true,"asso.gp":true,"gq":true,"gr":true,"com.gr":true,"edu.gr":true,"net.gr":true,"org.gr":true,"gov.gr":true,"gs":true,"gt":true,"com.gt":true,"edu.gt":true,"gob.gt":true,"ind.gt":true,"mil.gt":true,"net.gt":true,"org.gt":true,"*.gu":true,"gw":true,"gy":true,"co.gy":true,"com.gy":true,"net.gy":true,"hk":true,"com.hk":true,"edu.hk":true,"gov.hk":true,"idv.hk":true,"net.hk":true,"org.hk":true,"xn--55qx5d.hk":true,"xn--wcvs22d.hk":true,"xn--lcvr32d.hk":true,"xn--mxtq1m.hk":true,"xn--gmqw5a.hk":true,"xn--ciqpn.hk":true,"xn--gmq050i.hk":true,"xn--zf0avx.hk":true,"xn--io0a7i.hk":true,"xn--mk0axi.hk":true,"xn--od0alg.hk":true,"xn--od0aq3b.hk":true,"xn--tn0ag.hk":true,"xn--uc0atv.hk":true,"xn--uc0ay4a.hk":true,"hm":true,"hn":true,"com.hn":true,"edu.hn":true,"org.hn":true,"net.hn":true,"mil.hn":true,"gob.hn":true,"hr":true,"iz.hr":true,"from.hr":true,"name.hr":true,"com.hr":true,"ht":true,"com.ht":true,"shop.ht":true,"firm.ht":true,"info.ht":true,"adult.ht":true,"net.ht":true,"pro.ht":true,"org.ht":true,"med.ht":true,"art.ht":true,"coop.ht":true,"pol.ht":true,"asso.ht":true,"edu.ht":true,"rel.ht":true,"gouv.ht":true,"perso.ht":true,"hu":true,"co.hu":true,"info.hu":true,"org.hu":true,"priv.hu":true,"sport.hu":true,"tm.hu":true,"2000.hu":true,"agrar.hu":true,"bolt.hu":true,"casino.hu":true,"city.hu":true,"erotica.hu":true,"erotika.hu":true,"film.hu":true,"forum.hu":true,"games.hu":true,"hotel.hu":true,"ingatlan.hu":true,"jogasz.hu":true,"konyvelo.hu":true,"lakas.hu":true,"media.hu":true,"news.hu":true,"reklam.hu":true,"sex.hu":true,"shop.hu":true,"suli.hu":true,"szex.hu":true,"tozsde.hu":true,"utazas.hu":true,"video.hu":true,"id":true,"ac.id":true,"biz.id":true,"co.id":true,"desa.id":true,"go.id":true,"mil.id":true,"my.id":true,"net.id":true,"or.id":true,"sch.id":true,"web.id":true,"ie":true,"gov.ie":true,"il":true,"ac.il":true,"co.il":true,"gov.il":true,"idf.il":true,"k12.il":true,"muni.il":true,"net.il":true,"org.il":true,"im":true,"ac.im":true,"co.im":true,"com.im":true,"ltd.co.im":true,"net.im":true,"org.im":true,"plc.co.im":true,"tt.im":true,"tv.im":true,"in":true,"co.in":true,"firm.in":true,"net.in":true,"org.in":true,"gen.in":true,"ind.in":true,"nic.in":true,"ac.in":true,"edu.in":true,"res.in":true,"gov.in":true,"mil.in":true,"info":true,"int":true,"eu.int":true,"io":true,"com.io":true,"iq":true,"gov.iq":true,"edu.iq":true,"mil.iq":true,"com.iq":true,"org.iq":true,"net.iq":true,"ir":true,"ac.ir":true,"co.ir":true,"gov.ir":true,"id.ir":true,"net.ir":true,"org.ir":true,"sch.ir":true,"xn--mgba3a4f16a.ir":true,"xn--mgba3a4fra.ir":true,"is":true,"net.is":true,"com.is":true,"edu.is":true,"gov.is":true,"org.is":true,"int.is":true,"it":true,"gov.it":true,"edu.it":true,"abr.it":true,"abruzzo.it":true,"aosta-valley.it":true,"aostavalley.it":true,"bas.it":true,"basilicata.it":true,"cal.it":true,"calabria.it":true,"cam.it":true,"campania.it":true,"emilia-romagna.it":true,"emiliaromagna.it":true,"emr.it":true,"friuli-v-giulia.it":true,"friuli-ve-giulia.it":true,"friuli-vegiulia.it":true,"friuli-venezia-giulia.it":true,"friuli-veneziagiulia.it":true,"friuli-vgiulia.it":true,"friuliv-giulia.it":true,"friulive-giulia.it":true,"friulivegiulia.it":true,"friulivenezia-giulia.it":true,"friuliveneziagiulia.it":true,"friulivgiulia.it":true,"fvg.it":true,"laz.it":true,"lazio.it":true,"lig.it":true,"liguria.it":true,"lom.it":true,"lombardia.it":true,"lombardy.it":true,"lucania.it":true,"mar.it":true,"marche.it":true,"mol.it":true,"molise.it":true,"piedmont.it":true,"piemonte.it":true,"pmn.it":true,"pug.it":true,"puglia.it":true,"sar.it":true,"sardegna.it":true,"sardinia.it":true,"sic.it":true,"sicilia.it":true,"sicily.it":true,"taa.it":true,"tos.it":true,"toscana.it":true,"trentino-a-adige.it":true,"trentino-aadige.it":true,"trentino-alto-adige.it":true,"trentino-altoadige.it":true,"trentino-s-tirol.it":true,"trentino-stirol.it":true,"trentino-sud-tirol.it":true,"trentino-sudtirol.it":true,"trentino-sued-tirol.it":true,"trentino-suedtirol.it":true,"trentinoa-adige.it":true,"trentinoaadige.it":true,"trentinoalto-adige.it":true,"trentinoaltoadige.it":true,"trentinos-tirol.it":true,"trentinostirol.it":true,"trentinosud-tirol.it":true,"trentinosudtirol.it":true,"trentinosued-tirol.it":true,"trentinosuedtirol.it":true,"tuscany.it":true,"umb.it":true,"umbria.it":true,"val-d-aosta.it":true,"val-daosta.it":true,"vald-aosta.it":true,"valdaosta.it":true,"valle-aosta.it":true,"valle-d-aosta.it":true,"valle-daosta.it":true,"valleaosta.it":true,"valled-aosta.it":true,"valledaosta.it":true,"vallee-aoste.it":true,"valleeaoste.it":true,"vao.it":true,"vda.it":true,"ven.it":true,"veneto.it":true,"ag.it":true,"agrigento.it":true,"al.it":true,"alessandria.it":true,"alto-adige.it":true,"altoadige.it":true,"an.it":true,"ancona.it":true,"andria-barletta-trani.it":true,"andria-trani-barletta.it":true,"andriabarlettatrani.it":true,"andriatranibarletta.it":true,"ao.it":true,"aosta.it":true,"aoste.it":true,"ap.it":true,"aq.it":true,"aquila.it":true,"ar.it":true,"arezzo.it":true,"ascoli-piceno.it":true,"ascolipiceno.it":true,"asti.it":true,"at.it":true,"av.it":true,"avellino.it":true,"ba.it":true,"balsan.it":true,"bari.it":true,"barletta-trani-andria.it":true,"barlettatraniandria.it":true,"belluno.it":true,"benevento.it":true,"bergamo.it":true,"bg.it":true,"bi.it":true,"biella.it":true,"bl.it":true,"bn.it":true,"bo.it":true,"bologna.it":true,"bolzano.it":true,"bozen.it":true,"br.it":true,"brescia.it":true,"brindisi.it":true,"bs.it":true,"bt.it":true,"bz.it":true,"ca.it":true,"cagliari.it":true,"caltanissetta.it":true,"campidano-medio.it":true,"campidanomedio.it":true,"campobasso.it":true,"carbonia-iglesias.it":true,"carboniaiglesias.it":true,"carrara-massa.it":true,"carraramassa.it":true,"caserta.it":true,"catania.it":true,"catanzaro.it":true,"cb.it":true,"ce.it":true,"cesena-forli.it":true,"cesenaforli.it":true,"ch.it":true,"chieti.it":true,"ci.it":true,"cl.it":true,"cn.it":true,"co.it":true,"como.it":true,"cosenza.it":true,"cr.it":true,"cremona.it":true,"crotone.it":true,"cs.it":true,"ct.it":true,"cuneo.it":true,"cz.it":true,"dell-ogliastra.it":true,"dellogliastra.it":true,"en.it":true,"enna.it":true,"fc.it":true,"fe.it":true,"fermo.it":true,"ferrara.it":true,"fg.it":true,"fi.it":true,"firenze.it":true,"florence.it":true,"fm.it":true,"foggia.it":true,"forli-cesena.it":true,"forlicesena.it":true,"fr.it":true,"frosinone.it":true,"ge.it":true,"genoa.it":true,"genova.it":true,"go.it":true,"gorizia.it":true,"gr.it":true,"grosseto.it":true,"iglesias-carbonia.it":true,"iglesiascarbonia.it":true,"im.it":true,"imperia.it":true,"is.it":true,"isernia.it":true,"kr.it":true,"la-spezia.it":true,"laquila.it":true,"laspezia.it":true,"latina.it":true,"lc.it":true,"le.it":true,"lecce.it":true,"lecco.it":true,"li.it":true,"livorno.it":true,"lo.it":true,"lodi.it":true,"lt.it":true,"lu.it":true,"lucca.it":true,"macerata.it":true,"mantova.it":true,"massa-carrara.it":true,"massacarrara.it":true,"matera.it":true,"mb.it":true,"mc.it":true,"me.it":true,"medio-campidano.it":true,"mediocampidano.it":true,"messina.it":true,"mi.it":true,"milan.it":true,"milano.it":true,"mn.it":true,"mo.it":true,"modena.it":true,"monza-brianza.it":true,"monza-e-della-brianza.it":true,"monza.it":true,"monzabrianza.it":true,"monzaebrianza.it":true,"monzaedellabrianza.it":true,"ms.it":true,"mt.it":true,"na.it":true,"naples.it":true,"napoli.it":true,"no.it":true,"novara.it":true,"nu.it":true,"nuoro.it":true,"og.it":true,"ogliastra.it":true,"olbia-tempio.it":true,"olbiatempio.it":true,"or.it":true,"oristano.it":true,"ot.it":true,"pa.it":true,"padova.it":true,"padua.it":true,"palermo.it":true,"parma.it":true,"pavia.it":true,"pc.it":true,"pd.it":true,"pe.it":true,"perugia.it":true,"pesaro-urbino.it":true,"pesarourbino.it":true,"pescara.it":true,"pg.it":true,"pi.it":true,"piacenza.it":true,"pisa.it":true,"pistoia.it":true,"pn.it":true,"po.it":true,"pordenone.it":true,"potenza.it":true,"pr.it":true,"prato.it":true,"pt.it":true,"pu.it":true,"pv.it":true,"pz.it":true,"ra.it":true,"ragusa.it":true,"ravenna.it":true,"rc.it":true,"re.it":true,"reggio-calabria.it":true,"reggio-emilia.it":true,"reggiocalabria.it":true,"reggioemilia.it":true,"rg.it":true,"ri.it":true,"rieti.it":true,"rimini.it":true,"rm.it":true,"rn.it":true,"ro.it":true,"roma.it":true,"rome.it":true,"rovigo.it":true,"sa.it":true,"salerno.it":true,"sassari.it":true,"savona.it":true,"si.it":true,"siena.it":true,"siracusa.it":true,"so.it":true,"sondrio.it":true,"sp.it":true,"sr.it":true,"ss.it":true,"suedtirol.it":true,"sv.it":true,"ta.it":true,"taranto.it":true,"te.it":true,"tempio-olbia.it":true,"tempioolbia.it":true,"teramo.it":true,"terni.it":true,"tn.it":true,"to.it":true,"torino.it":true,"tp.it":true,"tr.it":true,"trani-andria-barletta.it":true,"trani-barletta-andria.it":true,"traniandriabarletta.it":true,"tranibarlettaandria.it":true,"trapani.it":true,"trentino.it":true,"trento.it":true,"treviso.it":true,"trieste.it":true,"ts.it":true,"turin.it":true,"tv.it":true,"ud.it":true,"udine.it":true,"urbino-pesaro.it":true,"urbinopesaro.it":true,"va.it":true,"varese.it":true,"vb.it":true,"vc.it":true,"ve.it":true,"venezia.it":true,"venice.it":true,"verbania.it":true,"vercelli.it":true,"verona.it":true,"vi.it":true,"vibo-valentia.it":true,"vibovalentia.it":true,"vicenza.it":true,"viterbo.it":true,"vr.it":true,"vs.it":true,"vt.it":true,"vv.it":true,"je":true,"co.je":true,"net.je":true,"org.je":true,"*.jm":true,"jo":true,"com.jo":true,"org.jo":true,"net.jo":true,"edu.jo":true,"sch.jo":true,"gov.jo":true,"mil.jo":true,"name.jo":true,"jobs":true,"jp":true,"ac.jp":true,"ad.jp":true,"co.jp":true,"ed.jp":true,"go.jp":true,"gr.jp":true,"lg.jp":true,"ne.jp":true,"or.jp":true,"aichi.jp":true,"akita.jp":true,"aomori.jp":true,"chiba.jp":true,"ehime.jp":true,"fukui.jp":true,"fukuoka.jp":true,"fukushima.jp":true,"gifu.jp":true,"gunma.jp":true,"hiroshima.jp":true,"hokkaido.jp":true,"hyogo.jp":true,"ibaraki.jp":true,"ishikawa.jp":true,"iwate.jp":true,"kagawa.jp":true,"kagoshima.jp":true,"kanagawa.jp":true,"kochi.jp":true,"kumamoto.jp":true,"kyoto.jp":true,"mie.jp":true,"miyagi.jp":true,"miyazaki.jp":true,"nagano.jp":true,"nagasaki.jp":true,"nara.jp":true,"niigata.jp":true,"oita.jp":true,"okayama.jp":true,"okinawa.jp":true,"osaka.jp":true,"saga.jp":true,"saitama.jp":true,"shiga.jp":true,"shimane.jp":true,"shizuoka.jp":true,"tochigi.jp":true,"tokushima.jp":true,"tokyo.jp":true,"tottori.jp":true,"toyama.jp":true,"wakayama.jp":true,"yamagata.jp":true,"yamaguchi.jp":true,"yamanashi.jp":true,"xn--4pvxs.jp":true,"xn--vgu402c.jp":true,"xn--c3s14m.jp":true,"xn--f6qx53a.jp":true,"xn--8pvr4u.jp":true,"xn--uist22h.jp":true,"xn--djrs72d6uy.jp":true,"xn--mkru45i.jp":true,"xn--0trq7p7nn.jp":true,"xn--8ltr62k.jp":true,"xn--2m4a15e.jp":true,"xn--efvn9s.jp":true,"xn--32vp30h.jp":true,"xn--4it797k.jp":true,"xn--1lqs71d.jp":true,"xn--5rtp49c.jp":true,"xn--5js045d.jp":true,"xn--ehqz56n.jp":true,"xn--1lqs03n.jp":true,"xn--qqqt11m.jp":true,"xn--kbrq7o.jp":true,"xn--pssu33l.jp":true,"xn--ntsq17g.jp":true,"xn--uisz3g.jp":true,"xn--6btw5a.jp":true,"xn--1ctwo.jp":true,"xn--6orx2r.jp":true,"xn--rht61e.jp":true,"xn--rht27z.jp":true,"xn--djty4k.jp":true,"xn--nit225k.jp":true,"xn--rht3d.jp":true,"xn--klty5x.jp":true,"xn--kltx9a.jp":true,"xn--kltp7d.jp":true,"xn--uuwu58a.jp":true,"xn--zbx025d.jp":true,"xn--ntso0iqx3a.jp":true,"xn--elqq16h.jp":true,"xn--4it168d.jp":true,"xn--klt787d.jp":true,"xn--rny31h.jp":true,"xn--7t0a264c.jp":true,"xn--5rtq34k.jp":true,"xn--k7yn95e.jp":true,"xn--tor131o.jp":true,"xn--d5qv7z876c.jp":true,"*.kawasaki.jp":true,"*.kitakyushu.jp":true,"*.kobe.jp":true,"*.nagoya.jp":true,"*.sapporo.jp":true,"*.sendai.jp":true,"*.yokohama.jp":true,"city.kawasaki.jp":false,"city.kitakyushu.jp":false,"city.kobe.jp":false,"city.nagoya.jp":false,"city.sapporo.jp":false,"city.sendai.jp":false,"city.yokohama.jp":false,"aisai.aichi.jp":true,"ama.aichi.jp":true,"anjo.aichi.jp":true,"asuke.aichi.jp":true,"chiryu.aichi.jp":true,"chita.aichi.jp":true,"fuso.aichi.jp":true,"gamagori.aichi.jp":true,"handa.aichi.jp":true,"hazu.aichi.jp":true,"hekinan.aichi.jp":true,"higashiura.aichi.jp":true,"ichinomiya.aichi.jp":true,"inazawa.aichi.jp":true,"inuyama.aichi.jp":true,"isshiki.aichi.jp":true,"iwakura.aichi.jp":true,"kanie.aichi.jp":true,"kariya.aichi.jp":true,"kasugai.aichi.jp":true,"kira.aichi.jp":true,"kiyosu.aichi.jp":true,"komaki.aichi.jp":true,"konan.aichi.jp":true,"kota.aichi.jp":true,"mihama.aichi.jp":true,"miyoshi.aichi.jp":true,"nishio.aichi.jp":true,"nisshin.aichi.jp":true,"obu.aichi.jp":true,"oguchi.aichi.jp":true,"oharu.aichi.jp":true,"okazaki.aichi.jp":true,"owariasahi.aichi.jp":true,"seto.aichi.jp":true,"shikatsu.aichi.jp":true,"shinshiro.aichi.jp":true,"shitara.aichi.jp":true,"tahara.aichi.jp":true,"takahama.aichi.jp":true,"tobishima.aichi.jp":true,"toei.aichi.jp":true,"togo.aichi.jp":true,"tokai.aichi.jp":true,"tokoname.aichi.jp":true,"toyoake.aichi.jp":true,"toyohashi.aichi.jp":true,"toyokawa.aichi.jp":true,"toyone.aichi.jp":true,"toyota.aichi.jp":true,"tsushima.aichi.jp":true,"yatomi.aichi.jp":true,"akita.akita.jp":true,"daisen.akita.jp":true,"fujisato.akita.jp":true,"gojome.akita.jp":true,"hachirogata.akita.jp":true,"happou.akita.jp":true,"higashinaruse.akita.jp":true,"honjo.akita.jp":true,"honjyo.akita.jp":true,"ikawa.akita.jp":true,"kamikoani.akita.jp":true,"kamioka.akita.jp":true,"katagami.akita.jp":true,"kazuno.akita.jp":true,"kitaakita.akita.jp":true,"kosaka.akita.jp":true,"kyowa.akita.jp":true,"misato.akita.jp":true,"mitane.akita.jp":true,"moriyoshi.akita.jp":true,"nikaho.akita.jp":true,"noshiro.akita.jp":true,"odate.akita.jp":true,"oga.akita.jp":true,"ogata.akita.jp":true,"semboku.akita.jp":true,"yokote.akita.jp":true,"yurihonjo.akita.jp":true,"aomori.aomori.jp":true,"gonohe.aomori.jp":true,"hachinohe.aomori.jp":true,"hashikami.aomori.jp":true,"hiranai.aomori.jp":true,"hirosaki.aomori.jp":true,"itayanagi.aomori.jp":true,"kuroishi.aomori.jp":true,"misawa.aomori.jp":true,"mutsu.aomori.jp":true,"nakadomari.aomori.jp":true,"noheji.aomori.jp":true,"oirase.aomori.jp":true,"owani.aomori.jp":true,"rokunohe.aomori.jp":true,"sannohe.aomori.jp":true,"shichinohe.aomori.jp":true,"shingo.aomori.jp":true,"takko.aomori.jp":true,"towada.aomori.jp":true,"tsugaru.aomori.jp":true,"tsuruta.aomori.jp":true,"abiko.chiba.jp":true,"asahi.chiba.jp":true,"chonan.chiba.jp":true,"chosei.chiba.jp":true,"choshi.chiba.jp":true,"chuo.chiba.jp":true,"funabashi.chiba.jp":true,"futtsu.chiba.jp":true,"hanamigawa.chiba.jp":true,"ichihara.chiba.jp":true,"ichikawa.chiba.jp":true,"ichinomiya.chiba.jp":true,"inzai.chiba.jp":true,"isumi.chiba.jp":true,"kamagaya.chiba.jp":true,"kamogawa.chiba.jp":true,"kashiwa.chiba.jp":true,"katori.chiba.jp":true,"katsuura.chiba.jp":true,"kimitsu.chiba.jp":true,"kisarazu.chiba.jp":true,"kozaki.chiba.jp":true,"kujukuri.chiba.jp":true,"kyonan.chiba.jp":true,"matsudo.chiba.jp":true,"midori.chiba.jp":true,"mihama.chiba.jp":true,"minamiboso.chiba.jp":true,"mobara.chiba.jp":true,"mutsuzawa.chiba.jp":true,"nagara.chiba.jp":true,"nagareyama.chiba.jp":true,"narashino.chiba.jp":true,"narita.chiba.jp":true,"noda.chiba.jp":true,"oamishirasato.chiba.jp":true,"omigawa.chiba.jp":true,"onjuku.chiba.jp":true,"otaki.chiba.jp":true,"sakae.chiba.jp":true,"sakura.chiba.jp":true,"shimofusa.chiba.jp":true,"shirako.chiba.jp":true,"shiroi.chiba.jp":true,"shisui.chiba.jp":true,"sodegaura.chiba.jp":true,"sosa.chiba.jp":true,"tako.chiba.jp":true,"tateyama.chiba.jp":true,"togane.chiba.jp":true,"tohnosho.chiba.jp":true,"tomisato.chiba.jp":true,"urayasu.chiba.jp":true,"yachimata.chiba.jp":true,"yachiyo.chiba.jp":true,"yokaichiba.chiba.jp":true,"yokoshibahikari.chiba.jp":true,"yotsukaido.chiba.jp":true,"ainan.ehime.jp":true,"honai.ehime.jp":true,"ikata.ehime.jp":true,"imabari.ehime.jp":true,"iyo.ehime.jp":true,"kamijima.ehime.jp":true,"kihoku.ehime.jp":true,"kumakogen.ehime.jp":true,"masaki.ehime.jp":true,"matsuno.ehime.jp":true,"matsuyama.ehime.jp":true,"namikata.ehime.jp":true,"niihama.ehime.jp":true,"ozu.ehime.jp":true,"saijo.ehime.jp":true,"seiyo.ehime.jp":true,"shikokuchuo.ehime.jp":true,"tobe.ehime.jp":true,"toon.ehime.jp":true,"uchiko.ehime.jp":true,"uwajima.ehime.jp":true,"yawatahama.ehime.jp":true,"echizen.fukui.jp":true,"eiheiji.fukui.jp":true,"fukui.fukui.jp":true,"ikeda.fukui.jp":true,"katsuyama.fukui.jp":true,"mihama.fukui.jp":true,"minamiechizen.fukui.jp":true,"obama.fukui.jp":true,"ohi.fukui.jp":true,"ono.fukui.jp":true,"sabae.fukui.jp":true,"sakai.fukui.jp":true,"takahama.fukui.jp":true,"tsuruga.fukui.jp":true,"wakasa.fukui.jp":true,"ashiya.fukuoka.jp":true,"buzen.fukuoka.jp":true,"chikugo.fukuoka.jp":true,"chikuho.fukuoka.jp":true,"chikujo.fukuoka.jp":true,"chikushino.fukuoka.jp":true,"chikuzen.fukuoka.jp":true,"chuo.fukuoka.jp":true,"dazaifu.fukuoka.jp":true,"fukuchi.fukuoka.jp":true,"hakata.fukuoka.jp":true,"higashi.fukuoka.jp":true,"hirokawa.fukuoka.jp":true,"hisayama.fukuoka.jp":true,"iizuka.fukuoka.jp":true,"inatsuki.fukuoka.jp":true,"kaho.fukuoka.jp":true,"kasuga.fukuoka.jp":true,"kasuya.fukuoka.jp":true,"kawara.fukuoka.jp":true,"keisen.fukuoka.jp":true,"koga.fukuoka.jp":true,"kurate.fukuoka.jp":true,"kurogi.fukuoka.jp":true,"kurume.fukuoka.jp":true,"minami.fukuoka.jp":true,"miyako.fukuoka.jp":true,"miyama.fukuoka.jp":true,"miyawaka.fukuoka.jp":true,"mizumaki.fukuoka.jp":true,"munakata.fukuoka.jp":true,"nakagawa.fukuoka.jp":true,"nakama.fukuoka.jp":true,"nishi.fukuoka.jp":true,"nogata.fukuoka.jp":true,"ogori.fukuoka.jp":true,"okagaki.fukuoka.jp":true,"okawa.fukuoka.jp":true,"oki.fukuoka.jp":true,"omuta.fukuoka.jp":true,"onga.fukuoka.jp":true,"onojo.fukuoka.jp":true,"oto.fukuoka.jp":true,"saigawa.fukuoka.jp":true,"sasaguri.fukuoka.jp":true,"shingu.fukuoka.jp":true,"shinyoshitomi.fukuoka.jp":true,"shonai.fukuoka.jp":true,"soeda.fukuoka.jp":true,"sue.fukuoka.jp":true,"tachiarai.fukuoka.jp":true,"tagawa.fukuoka.jp":true,"takata.fukuoka.jp":true,"toho.fukuoka.jp":true,"toyotsu.fukuoka.jp":true,"tsuiki.fukuoka.jp":true,"ukiha.fukuoka.jp":true,"umi.fukuoka.jp":true,"usui.fukuoka.jp":true,"yamada.fukuoka.jp":true,"yame.fukuoka.jp":true,"yanagawa.fukuoka.jp":true,"yukuhashi.fukuoka.jp":true,"aizubange.fukushima.jp":true,"aizumisato.fukushima.jp":true,"aizuwakamatsu.fukushima.jp":true,"asakawa.fukushima.jp":true,"bandai.fukushima.jp":true,"date.fukushima.jp":true,"fukushima.fukushima.jp":true,"furudono.fukushima.jp":true,"futaba.fukushima.jp":true,"hanawa.fukushima.jp":true,"higashi.fukushima.jp":true,"hirata.fukushima.jp":true,"hirono.fukushima.jp":true,"iitate.fukushima.jp":true,"inawashiro.fukushima.jp":true,"ishikawa.fukushima.jp":true,"iwaki.fukushima.jp":true,"izumizaki.fukushima.jp":true,"kagamiishi.fukushima.jp":true,"kaneyama.fukushima.jp":true,"kawamata.fukushima.jp":true,"kitakata.fukushima.jp":true,"kitashiobara.fukushima.jp":true,"koori.fukushima.jp":true,"koriyama.fukushima.jp":true,"kunimi.fukushima.jp":true,"miharu.fukushima.jp":true,"mishima.fukushima.jp":true,"namie.fukushima.jp":true,"nango.fukushima.jp":true,"nishiaizu.fukushima.jp":true,"nishigo.fukushima.jp":true,"okuma.fukushima.jp":true,"omotego.fukushima.jp":true,"ono.fukushima.jp":true,"otama.fukushima.jp":true,"samegawa.fukushima.jp":true,"shimogo.fukushima.jp":true,"shirakawa.fukushima.jp":true,"showa.fukushima.jp":true,"soma.fukushima.jp":true,"sukagawa.fukushima.jp":true,"taishin.fukushima.jp":true,"tamakawa.fukushima.jp":true,"tanagura.fukushima.jp":true,"tenei.fukushima.jp":true,"yabuki.fukushima.jp":true,"yamato.fukushima.jp":true,"yamatsuri.fukushima.jp":true,"yanaizu.fukushima.jp":true,"yugawa.fukushima.jp":true,"anpachi.gifu.jp":true,"ena.gifu.jp":true,"gifu.gifu.jp":true,"ginan.gifu.jp":true,"godo.gifu.jp":true,"gujo.gifu.jp":true,"hashima.gifu.jp":true,"hichiso.gifu.jp":true,"hida.gifu.jp":true,"higashishirakawa.gifu.jp":true,"ibigawa.gifu.jp":true,"ikeda.gifu.jp":true,"kakamigahara.gifu.jp":true,"kani.gifu.jp":true,"kasahara.gifu.jp":true,"kasamatsu.gifu.jp":true,"kawaue.gifu.jp":true,"kitagata.gifu.jp":true,"mino.gifu.jp":true,"minokamo.gifu.jp":true,"mitake.gifu.jp":true,"mizunami.gifu.jp":true,"motosu.gifu.jp":true,"nakatsugawa.gifu.jp":true,"ogaki.gifu.jp":true,"sakahogi.gifu.jp":true,"seki.gifu.jp":true,"sekigahara.gifu.jp":true,"shirakawa.gifu.jp":true,"tajimi.gifu.jp":true,"takayama.gifu.jp":true,"tarui.gifu.jp":true,"toki.gifu.jp":true,"tomika.gifu.jp":true,"wanouchi.gifu.jp":true,"yamagata.gifu.jp":true,"yaotsu.gifu.jp":true,"yoro.gifu.jp":true,"annaka.gunma.jp":true,"chiyoda.gunma.jp":true,"fujioka.gunma.jp":true,"higashiagatsuma.gunma.jp":true,"isesaki.gunma.jp":true,"itakura.gunma.jp":true,"kanna.gunma.jp":true,"kanra.gunma.jp":true,"katashina.gunma.jp":true,"kawaba.gunma.jp":true,"kiryu.gunma.jp":true,"kusatsu.gunma.jp":true,"maebashi.gunma.jp":true,"meiwa.gunma.jp":true,"midori.gunma.jp":true,"minakami.gunma.jp":true,"naganohara.gunma.jp":true,"nakanojo.gunma.jp":true,"nanmoku.gunma.jp":true,"numata.gunma.jp":true,"oizumi.gunma.jp":true,"ora.gunma.jp":true,"ota.gunma.jp":true,"shibukawa.gunma.jp":true,"shimonita.gunma.jp":true,"shinto.gunma.jp":true,"showa.gunma.jp":true,"takasaki.gunma.jp":true,"takayama.gunma.jp":true,"tamamura.gunma.jp":true,"tatebayashi.gunma.jp":true,"tomioka.gunma.jp":true,"tsukiyono.gunma.jp":true,"tsumagoi.gunma.jp":true,"ueno.gunma.jp":true,"yoshioka.gunma.jp":true,"asaminami.hiroshima.jp":true,"daiwa.hiroshima.jp":true,"etajima.hiroshima.jp":true,"fuchu.hiroshima.jp":true,"fukuyama.hiroshima.jp":true,"hatsukaichi.hiroshima.jp":true,"higashihiroshima.hiroshima.jp":true,"hongo.hiroshima.jp":true,"jinsekikogen.hiroshima.jp":true,"kaita.hiroshima.jp":true,"kui.hiroshima.jp":true,"kumano.hiroshima.jp":true,"kure.hiroshima.jp":true,"mihara.hiroshima.jp":true,"miyoshi.hiroshima.jp":true,"naka.hiroshima.jp":true,"onomichi.hiroshima.jp":true,"osakikamijima.hiroshima.jp":true,"otake.hiroshima.jp":true,"saka.hiroshima.jp":true,"sera.hiroshima.jp":true,"seranishi.hiroshima.jp":true,"shinichi.hiroshima.jp":true,"shobara.hiroshima.jp":true,"takehara.hiroshima.jp":true,"abashiri.hokkaido.jp":true,"abira.hokkaido.jp":true,"aibetsu.hokkaido.jp":true,"akabira.hokkaido.jp":true,"akkeshi.hokkaido.jp":true,"asahikawa.hokkaido.jp":true,"ashibetsu.hokkaido.jp":true,"ashoro.hokkaido.jp":true,"assabu.hokkaido.jp":true,"atsuma.hokkaido.jp":true,"bibai.hokkaido.jp":true,"biei.hokkaido.jp":true,"bifuka.hokkaido.jp":true,"bihoro.hokkaido.jp":true,"biratori.hokkaido.jp":true,"chippubetsu.hokkaido.jp":true,"chitose.hokkaido.jp":true,"date.hokkaido.jp":true,"ebetsu.hokkaido.jp":true,"embetsu.hokkaido.jp":true,"eniwa.hokkaido.jp":true,"erimo.hokkaido.jp":true,"esan.hokkaido.jp":true,"esashi.hokkaido.jp":true,"fukagawa.hokkaido.jp":true,"fukushima.hokkaido.jp":true,"furano.hokkaido.jp":true,"furubira.hokkaido.jp":true,"haboro.hokkaido.jp":true,"hakodate.hokkaido.jp":true,"hamatonbetsu.hokkaido.jp":true,"hidaka.hokkaido.jp":true,"higashikagura.hokkaido.jp":true,"higashikawa.hokkaido.jp":true,"hiroo.hokkaido.jp":true,"hokuryu.hokkaido.jp":true,"hokuto.hokkaido.jp":true,"honbetsu.hokkaido.jp":true,"horokanai.hokkaido.jp":true,"horonobe.hokkaido.jp":true,"ikeda.hokkaido.jp":true,"imakane.hokkaido.jp":true,"ishikari.hokkaido.jp":true,"iwamizawa.hokkaido.jp":true,"iwanai.hokkaido.jp":true,"kamifurano.hokkaido.jp":true,"kamikawa.hokkaido.jp":true,"kamishihoro.hokkaido.jp":true,"kamisunagawa.hokkaido.jp":true,"kamoenai.hokkaido.jp":true,"kayabe.hokkaido.jp":true,"kembuchi.hokkaido.jp":true,"kikonai.hokkaido.jp":true,"kimobetsu.hokkaido.jp":true,"kitahiroshima.hokkaido.jp":true,"kitami.hokkaido.jp":true,"kiyosato.hokkaido.jp":true,"koshimizu.hokkaido.jp":true,"kunneppu.hokkaido.jp":true,"kuriyama.hokkaido.jp":true,"kuromatsunai.hokkaido.jp":true,"kushiro.hokkaido.jp":true,"kutchan.hokkaido.jp":true,"kyowa.hokkaido.jp":true,"mashike.hokkaido.jp":true,"matsumae.hokkaido.jp":true,"mikasa.hokkaido.jp":true,"minamifurano.hokkaido.jp":true,"mombetsu.hokkaido.jp":true,"moseushi.hokkaido.jp":true,"mukawa.hokkaido.jp":true,"muroran.hokkaido.jp":true,"naie.hokkaido.jp":true,"nakagawa.hokkaido.jp":true,"nakasatsunai.hokkaido.jp":true,"nakatombetsu.hokkaido.jp":true,"nanae.hokkaido.jp":true,"nanporo.hokkaido.jp":true,"nayoro.hokkaido.jp":true,"nemuro.hokkaido.jp":true,"niikappu.hokkaido.jp":true,"niki.hokkaido.jp":true,"nishiokoppe.hokkaido.jp":true,"noboribetsu.hokkaido.jp":true,"numata.hokkaido.jp":true,"obihiro.hokkaido.jp":true,"obira.hokkaido.jp":true,"oketo.hokkaido.jp":true,"okoppe.hokkaido.jp":true,"otaru.hokkaido.jp":true,"otobe.hokkaido.jp":true,"otofuke.hokkaido.jp":true,"otoineppu.hokkaido.jp":true,"oumu.hokkaido.jp":true,"ozora.hokkaido.jp":true,"pippu.hokkaido.jp":true,"rankoshi.hokkaido.jp":true,"rebun.hokkaido.jp":true,"rikubetsu.hokkaido.jp":true,"rishiri.hokkaido.jp":true,"rishirifuji.hokkaido.jp":true,"saroma.hokkaido.jp":true,"sarufutsu.hokkaido.jp":true,"shakotan.hokkaido.jp":true,"shari.hokkaido.jp":true,"shibecha.hokkaido.jp":true,"shibetsu.hokkaido.jp":true,"shikabe.hokkaido.jp":true,"shikaoi.hokkaido.jp":true,"shimamaki.hokkaido.jp":true,"shimizu.hokkaido.jp":true,"shimokawa.hokkaido.jp":true,"shinshinotsu.hokkaido.jp":true,"shintoku.hokkaido.jp":true,"shiranuka.hokkaido.jp":true,"shiraoi.hokkaido.jp":true,"shiriuchi.hokkaido.jp":true,"sobetsu.hokkaido.jp":true,"sunagawa.hokkaido.jp":true,"taiki.hokkaido.jp":true,"takasu.hokkaido.jp":true,"takikawa.hokkaido.jp":true,"takinoue.hokkaido.jp":true,"teshikaga.hokkaido.jp":true,"tobetsu.hokkaido.jp":true,"tohma.hokkaido.jp":true,"tomakomai.hokkaido.jp":true,"tomari.hokkaido.jp":true,"toya.hokkaido.jp":true,"toyako.hokkaido.jp":true,"toyotomi.hokkaido.jp":true,"toyoura.hokkaido.jp":true,"tsubetsu.hokkaido.jp":true,"tsukigata.hokkaido.jp":true,"urakawa.hokkaido.jp":true,"urausu.hokkaido.jp":true,"uryu.hokkaido.jp":true,"utashinai.hokkaido.jp":true,"wakkanai.hokkaido.jp":true,"wassamu.hokkaido.jp":true,"yakumo.hokkaido.jp":true,"yoichi.hokkaido.jp":true,"aioi.hyogo.jp":true,"akashi.hyogo.jp":true,"ako.hyogo.jp":true,"amagasaki.hyogo.jp":true,"aogaki.hyogo.jp":true,"asago.hyogo.jp":true,"ashiya.hyogo.jp":true,"awaji.hyogo.jp":true,"fukusaki.hyogo.jp":true,"goshiki.hyogo.jp":true,"harima.hyogo.jp":true,"himeji.hyogo.jp":true,"ichikawa.hyogo.jp":true,"inagawa.hyogo.jp":true,"itami.hyogo.jp":true,"kakogawa.hyogo.jp":true,"kamigori.hyogo.jp":true,"kamikawa.hyogo.jp":true,"kasai.hyogo.jp":true,"kasuga.hyogo.jp":true,"kawanishi.hyogo.jp":true,"miki.hyogo.jp":true,"minamiawaji.hyogo.jp":true,"nishinomiya.hyogo.jp":true,"nishiwaki.hyogo.jp":true,"ono.hyogo.jp":true,"sanda.hyogo.jp":true,"sannan.hyogo.jp":true,"sasayama.hyogo.jp":true,"sayo.hyogo.jp":true,"shingu.hyogo.jp":true,"shinonsen.hyogo.jp":true,"shiso.hyogo.jp":true,"sumoto.hyogo.jp":true,"taishi.hyogo.jp":true,"taka.hyogo.jp":true,"takarazuka.hyogo.jp":true,"takasago.hyogo.jp":true,"takino.hyogo.jp":true,"tamba.hyogo.jp":true,"tatsuno.hyogo.jp":true,"toyooka.hyogo.jp":true,"yabu.hyogo.jp":true,"yashiro.hyogo.jp":true,"yoka.hyogo.jp":true,"yokawa.hyogo.jp":true,"ami.ibaraki.jp":true,"asahi.ibaraki.jp":true,"bando.ibaraki.jp":true,"chikusei.ibaraki.jp":true,"daigo.ibaraki.jp":true,"fujishiro.ibaraki.jp":true,"hitachi.ibaraki.jp":true,"hitachinaka.ibaraki.jp":true,"hitachiomiya.ibaraki.jp":true,"hitachiota.ibaraki.jp":true,"ibaraki.ibaraki.jp":true,"ina.ibaraki.jp":true,"inashiki.ibaraki.jp":true,"itako.ibaraki.jp":true,"iwama.ibaraki.jp":true,"joso.ibaraki.jp":true,"kamisu.ibaraki.jp":true,"kasama.ibaraki.jp":true,"kashima.ibaraki.jp":true,"kasumigaura.ibaraki.jp":true,"koga.ibaraki.jp":true,"miho.ibaraki.jp":true,"mito.ibaraki.jp":true,"moriya.ibaraki.jp":true,"naka.ibaraki.jp":true,"namegata.ibaraki.jp":true,"oarai.ibaraki.jp":true,"ogawa.ibaraki.jp":true,"omitama.ibaraki.jp":true,"ryugasaki.ibaraki.jp":true,"sakai.ibaraki.jp":true,"sakuragawa.ibaraki.jp":true,"shimodate.ibaraki.jp":true,"shimotsuma.ibaraki.jp":true,"shirosato.ibaraki.jp":true,"sowa.ibaraki.jp":true,"suifu.ibaraki.jp":true,"takahagi.ibaraki.jp":true,"tamatsukuri.ibaraki.jp":true,"tokai.ibaraki.jp":true,"tomobe.ibaraki.jp":true,"tone.ibaraki.jp":true,"toride.ibaraki.jp":true,"tsuchiura.ibaraki.jp":true,"tsukuba.ibaraki.jp":true,"uchihara.ibaraki.jp":true,"ushiku.ibaraki.jp":true,"yachiyo.ibaraki.jp":true,"yamagata.ibaraki.jp":true,"yawara.ibaraki.jp":true,"yuki.ibaraki.jp":true,"anamizu.ishikawa.jp":true,"hakui.ishikawa.jp":true,"hakusan.ishikawa.jp":true,"kaga.ishikawa.jp":true,"kahoku.ishikawa.jp":true,"kanazawa.ishikawa.jp":true,"kawakita.ishikawa.jp":true,"komatsu.ishikawa.jp":true,"nakanoto.ishikawa.jp":true,"nanao.ishikawa.jp":true,"nomi.ishikawa.jp":true,"nonoichi.ishikawa.jp":true,"noto.ishikawa.jp":true,"shika.ishikawa.jp":true,"suzu.ishikawa.jp":true,"tsubata.ishikawa.jp":true,"tsurugi.ishikawa.jp":true,"uchinada.ishikawa.jp":true,"wajima.ishikawa.jp":true,"fudai.iwate.jp":true,"fujisawa.iwate.jp":true,"hanamaki.iwate.jp":true,"hiraizumi.iwate.jp":true,"hirono.iwate.jp":true,"ichinohe.iwate.jp":true,"ichinoseki.iwate.jp":true,"iwaizumi.iwate.jp":true,"iwate.iwate.jp":true,"joboji.iwate.jp":true,"kamaishi.iwate.jp":true,"kanegasaki.iwate.jp":true,"karumai.iwate.jp":true,"kawai.iwate.jp":true,"kitakami.iwate.jp":true,"kuji.iwate.jp":true,"kunohe.iwate.jp":true,"kuzumaki.iwate.jp":true,"miyako.iwate.jp":true,"mizusawa.iwate.jp":true,"morioka.iwate.jp":true,"ninohe.iwate.jp":true,"noda.iwate.jp":true,"ofunato.iwate.jp":true,"oshu.iwate.jp":true,"otsuchi.iwate.jp":true,"rikuzentakata.iwate.jp":true,"shiwa.iwate.jp":true,"shizukuishi.iwate.jp":true,"sumita.iwate.jp":true,"tanohata.iwate.jp":true,"tono.iwate.jp":true,"yahaba.iwate.jp":true,"yamada.iwate.jp":true,"ayagawa.kagawa.jp":true,"higashikagawa.kagawa.jp":true,"kanonji.kagawa.jp":true,"kotohira.kagawa.jp":true,"manno.kagawa.jp":true,"marugame.kagawa.jp":true,"mitoyo.kagawa.jp":true,"naoshima.kagawa.jp":true,"sanuki.kagawa.jp":true,"tadotsu.kagawa.jp":true,"takamatsu.kagawa.jp":true,"tonosho.kagawa.jp":true,"uchinomi.kagawa.jp":true,"utazu.kagawa.jp":true,"zentsuji.kagawa.jp":true,"akune.kagoshima.jp":true,"amami.kagoshima.jp":true,"hioki.kagoshima.jp":true,"isa.kagoshima.jp":true,"isen.kagoshima.jp":true,"izumi.kagoshima.jp":true,"kagoshima.kagoshima.jp":true,"kanoya.kagoshima.jp":true,"kawanabe.kagoshima.jp":true,"kinko.kagoshima.jp":true,"kouyama.kagoshima.jp":true,"makurazaki.kagoshima.jp":true,"matsumoto.kagoshima.jp":true,"minamitane.kagoshima.jp":true,"nakatane.kagoshima.jp":true,"nishinoomote.kagoshima.jp":true,"satsumasendai.kagoshima.jp":true,"soo.kagoshima.jp":true,"tarumizu.kagoshima.jp":true,"yusui.kagoshima.jp":true,"aikawa.kanagawa.jp":true,"atsugi.kanagawa.jp":true,"ayase.kanagawa.jp":true,"chigasaki.kanagawa.jp":true,"ebina.kanagawa.jp":true,"fujisawa.kanagawa.jp":true,"hadano.kanagawa.jp":true,"hakone.kanagawa.jp":true,"hiratsuka.kanagawa.jp":true,"isehara.kanagawa.jp":true,"kaisei.kanagawa.jp":true,"kamakura.kanagawa.jp":true,"kiyokawa.kanagawa.jp":true,"matsuda.kanagawa.jp":true,"minamiashigara.kanagawa.jp":true,"miura.kanagawa.jp":true,"nakai.kanagawa.jp":true,"ninomiya.kanagawa.jp":true,"odawara.kanagawa.jp":true,"oi.kanagawa.jp":true,"oiso.kanagawa.jp":true,"sagamihara.kanagawa.jp":true,"samukawa.kanagawa.jp":true,"tsukui.kanagawa.jp":true,"yamakita.kanagawa.jp":true,"yamato.kanagawa.jp":true,"yokosuka.kanagawa.jp":true,"yugawara.kanagawa.jp":true,"zama.kanagawa.jp":true,"zushi.kanagawa.jp":true,"aki.kochi.jp":true,"geisei.kochi.jp":true,"hidaka.kochi.jp":true,"higashitsuno.kochi.jp":true,"ino.kochi.jp":true,"kagami.kochi.jp":true,"kami.kochi.jp":true,"kitagawa.kochi.jp":true,"kochi.kochi.jp":true,"mihara.kochi.jp":true,"motoyama.kochi.jp":true,"muroto.kochi.jp":true,"nahari.kochi.jp":true,"nakamura.kochi.jp":true,"nankoku.kochi.jp":true,"nishitosa.kochi.jp":true,"niyodogawa.kochi.jp":true,"ochi.kochi.jp":true,"okawa.kochi.jp":true,"otoyo.kochi.jp":true,"otsuki.kochi.jp":true,"sakawa.kochi.jp":true,"sukumo.kochi.jp":true,"susaki.kochi.jp":true,"tosa.kochi.jp":true,"tosashimizu.kochi.jp":true,"toyo.kochi.jp":true,"tsuno.kochi.jp":true,"umaji.kochi.jp":true,"yasuda.kochi.jp":true,"yusuhara.kochi.jp":true,"amakusa.kumamoto.jp":true,"arao.kumamoto.jp":true,"aso.kumamoto.jp":true,"choyo.kumamoto.jp":true,"gyokuto.kumamoto.jp":true,"hitoyoshi.kumamoto.jp":true,"kamiamakusa.kumamoto.jp":true,"kashima.kumamoto.jp":true,"kikuchi.kumamoto.jp":true,"kosa.kumamoto.jp":true,"kumamoto.kumamoto.jp":true,"mashiki.kumamoto.jp":true,"mifune.kumamoto.jp":true,"minamata.kumamoto.jp":true,"minamioguni.kumamoto.jp":true,"nagasu.kumamoto.jp":true,"nishihara.kumamoto.jp":true,"oguni.kumamoto.jp":true,"ozu.kumamoto.jp":true,"sumoto.kumamoto.jp":true,"takamori.kumamoto.jp":true,"uki.kumamoto.jp":true,"uto.kumamoto.jp":true,"yamaga.kumamoto.jp":true,"yamato.kumamoto.jp":true,"yatsushiro.kumamoto.jp":true,"ayabe.kyoto.jp":true,"fukuchiyama.kyoto.jp":true,"higashiyama.kyoto.jp":true,"ide.kyoto.jp":true,"ine.kyoto.jp":true,"joyo.kyoto.jp":true,"kameoka.kyoto.jp":true,"kamo.kyoto.jp":true,"kita.kyoto.jp":true,"kizu.kyoto.jp":true,"kumiyama.kyoto.jp":true,"kyotamba.kyoto.jp":true,"kyotanabe.kyoto.jp":true,"kyotango.kyoto.jp":true,"maizuru.kyoto.jp":true,"minami.kyoto.jp":true,"minamiyamashiro.kyoto.jp":true,"miyazu.kyoto.jp":true,"muko.kyoto.jp":true,"nagaokakyo.kyoto.jp":true,"nakagyo.kyoto.jp":true,"nantan.kyoto.jp":true,"oyamazaki.kyoto.jp":true,"sakyo.kyoto.jp":true,"seika.kyoto.jp":true,"tanabe.kyoto.jp":true,"uji.kyoto.jp":true,"ujitawara.kyoto.jp":true,"wazuka.kyoto.jp":true,"yamashina.kyoto.jp":true,"yawata.kyoto.jp":true,"asahi.mie.jp":true,"inabe.mie.jp":true,"ise.mie.jp":true,"kameyama.mie.jp":true,"kawagoe.mie.jp":true,"kiho.mie.jp":true,"kisosaki.mie.jp":true,"kiwa.mie.jp":true,"komono.mie.jp":true,"kumano.mie.jp":true,"kuwana.mie.jp":true,"matsusaka.mie.jp":true,"meiwa.mie.jp":true,"mihama.mie.jp":true,"minamiise.mie.jp":true,"misugi.mie.jp":true,"miyama.mie.jp":true,"nabari.mie.jp":true,"shima.mie.jp":true,"suzuka.mie.jp":true,"tado.mie.jp":true,"taiki.mie.jp":true,"taki.mie.jp":true,"tamaki.mie.jp":true,"toba.mie.jp":true,"tsu.mie.jp":true,"udono.mie.jp":true,"ureshino.mie.jp":true,"watarai.mie.jp":true,"yokkaichi.mie.jp":true,"furukawa.miyagi.jp":true,"higashimatsushima.miyagi.jp":true,"ishinomaki.miyagi.jp":true,"iwanuma.miyagi.jp":true,"kakuda.miyagi.jp":true,"kami.miyagi.jp":true,"kawasaki.miyagi.jp":true,"kesennuma.miyagi.jp":true,"marumori.miyagi.jp":true,"matsushima.miyagi.jp":true,"minamisanriku.miyagi.jp":true,"misato.miyagi.jp":true,"murata.miyagi.jp":true,"natori.miyagi.jp":true,"ogawara.miyagi.jp":true,"ohira.miyagi.jp":true,"onagawa.miyagi.jp":true,"osaki.miyagi.jp":true,"rifu.miyagi.jp":true,"semine.miyagi.jp":true,"shibata.miyagi.jp":true,"shichikashuku.miyagi.jp":true,"shikama.miyagi.jp":true,"shiogama.miyagi.jp":true,"shiroishi.miyagi.jp":true,"tagajo.miyagi.jp":true,"taiwa.miyagi.jp":true,"tome.miyagi.jp":true,"tomiya.miyagi.jp":true,"wakuya.miyagi.jp":true,"watari.miyagi.jp":true,"yamamoto.miyagi.jp":true,"zao.miyagi.jp":true,"aya.miyazaki.jp":true,"ebino.miyazaki.jp":true,"gokase.miyazaki.jp":true,"hyuga.miyazaki.jp":true,"kadogawa.miyazaki.jp":true,"kawaminami.miyazaki.jp":true,"kijo.miyazaki.jp":true,"kitagawa.miyazaki.jp":true,"kitakata.miyazaki.jp":true,"kitaura.miyazaki.jp":true,"kobayashi.miyazaki.jp":true,"kunitomi.miyazaki.jp":true,"kushima.miyazaki.jp":true,"mimata.miyazaki.jp":true,"miyakonojo.miyazaki.jp":true,"miyazaki.miyazaki.jp":true,"morotsuka.miyazaki.jp":true,"nichinan.miyazaki.jp":true,"nishimera.miyazaki.jp":true,"nobeoka.miyazaki.jp":true,"saito.miyazaki.jp":true,"shiiba.miyazaki.jp":true,"shintomi.miyazaki.jp":true,"takaharu.miyazaki.jp":true,"takanabe.miyazaki.jp":true,"takazaki.miyazaki.jp":true,"tsuno.miyazaki.jp":true,"achi.nagano.jp":true,"agematsu.nagano.jp":true,"anan.nagano.jp":true,"aoki.nagano.jp":true,"asahi.nagano.jp":true,"azumino.nagano.jp":true,"chikuhoku.nagano.jp":true,"chikuma.nagano.jp":true,"chino.nagano.jp":true,"fujimi.nagano.jp":true,"hakuba.nagano.jp":true,"hara.nagano.jp":true,"hiraya.nagano.jp":true,"iida.nagano.jp":true,"iijima.nagano.jp":true,"iiyama.nagano.jp":true,"iizuna.nagano.jp":true,"ikeda.nagano.jp":true,"ikusaka.nagano.jp":true,"ina.nagano.jp":true,"karuizawa.nagano.jp":true,"kawakami.nagano.jp":true,"kiso.nagano.jp":true,"kisofukushima.nagano.jp":true,"kitaaiki.nagano.jp":true,"komagane.nagano.jp":true,"komoro.nagano.jp":true,"matsukawa.nagano.jp":true,"matsumoto.nagano.jp":true,"miasa.nagano.jp":true,"minamiaiki.nagano.jp":true,"minamimaki.nagano.jp":true,"minamiminowa.nagano.jp":true,"minowa.nagano.jp":true,"miyada.nagano.jp":true,"miyota.nagano.jp":true,"mochizuki.nagano.jp":true,"nagano.nagano.jp":true,"nagawa.nagano.jp":true,"nagiso.nagano.jp":true,"nakagawa.nagano.jp":true,"nakano.nagano.jp":true,"nozawaonsen.nagano.jp":true,"obuse.nagano.jp":true,"ogawa.nagano.jp":true,"okaya.nagano.jp":true,"omachi.nagano.jp":true,"omi.nagano.jp":true,"ookuwa.nagano.jp":true,"ooshika.nagano.jp":true,"otaki.nagano.jp":true,"otari.nagano.jp":true,"sakae.nagano.jp":true,"sakaki.nagano.jp":true,"saku.nagano.jp":true,"sakuho.nagano.jp":true,"shimosuwa.nagano.jp":true,"shinanomachi.nagano.jp":true,"shiojiri.nagano.jp":true,"suwa.nagano.jp":true,"suzaka.nagano.jp":true,"takagi.nagano.jp":true,"takamori.nagano.jp":true,"takayama.nagano.jp":true,"tateshina.nagano.jp":true,"tatsuno.nagano.jp":true,"togakushi.nagano.jp":true,"togura.nagano.jp":true,"tomi.nagano.jp":true,"ueda.nagano.jp":true,"wada.nagano.jp":true,"yamagata.nagano.jp":true,"yamanouchi.nagano.jp":true,"yasaka.nagano.jp":true,"yasuoka.nagano.jp":true,"chijiwa.nagasaki.jp":true,"futsu.nagasaki.jp":true,"goto.nagasaki.jp":true,"hasami.nagasaki.jp":true,"hirado.nagasaki.jp":true,"iki.nagasaki.jp":true,"isahaya.nagasaki.jp":true,"kawatana.nagasaki.jp":true,"kuchinotsu.nagasaki.jp":true,"matsuura.nagasaki.jp":true,"nagasaki.nagasaki.jp":true,"obama.nagasaki.jp":true,"omura.nagasaki.jp":true,"oseto.nagasaki.jp":true,"saikai.nagasaki.jp":true,"sasebo.nagasaki.jp":true,"seihi.nagasaki.jp":true,"shimabara.nagasaki.jp":true,"shinkamigoto.nagasaki.jp":true,"togitsu.nagasaki.jp":true,"tsushima.nagasaki.jp":true,"unzen.nagasaki.jp":true,"ando.nara.jp":true,"gose.nara.jp":true,"heguri.nara.jp":true,"higashiyoshino.nara.jp":true,"ikaruga.nara.jp":true,"ikoma.nara.jp":true,"kamikitayama.nara.jp":true,"kanmaki.nara.jp":true,"kashiba.nara.jp":true,"kashihara.nara.jp":true,"katsuragi.nara.jp":true,"kawai.nara.jp":true,"kawakami.nara.jp":true,"kawanishi.nara.jp":true,"koryo.nara.jp":true,"kurotaki.nara.jp":true,"mitsue.nara.jp":true,"miyake.nara.jp":true,"nara.nara.jp":true,"nosegawa.nara.jp":true,"oji.nara.jp":true,"ouda.nara.jp":true,"oyodo.nara.jp":true,"sakurai.nara.jp":true,"sango.nara.jp":true,"shimoichi.nara.jp":true,"shimokitayama.nara.jp":true,"shinjo.nara.jp":true,"soni.nara.jp":true,"takatori.nara.jp":true,"tawaramoto.nara.jp":true,"tenkawa.nara.jp":true,"tenri.nara.jp":true,"uda.nara.jp":true,"yamatokoriyama.nara.jp":true,"yamatotakada.nara.jp":true,"yamazoe.nara.jp":true,"yoshino.nara.jp":true,"aga.niigata.jp":true,"agano.niigata.jp":true,"gosen.niigata.jp":true,"itoigawa.niigata.jp":true,"izumozaki.niigata.jp":true,"joetsu.niigata.jp":true,"kamo.niigata.jp":true,"kariwa.niigata.jp":true,"kashiwazaki.niigata.jp":true,"minamiuonuma.niigata.jp":true,"mitsuke.niigata.jp":true,"muika.niigata.jp":true,"murakami.niigata.jp":true,"myoko.niigata.jp":true,"nagaoka.niigata.jp":true,"niigata.niigata.jp":true,"ojiya.niigata.jp":true,"omi.niigata.jp":true,"sado.niigata.jp":true,"sanjo.niigata.jp":true,"seiro.niigata.jp":true,"seirou.niigata.jp":true,"sekikawa.niigata.jp":true,"shibata.niigata.jp":true,"tagami.niigata.jp":true,"tainai.niigata.jp":true,"tochio.niigata.jp":true,"tokamachi.niigata.jp":true,"tsubame.niigata.jp":true,"tsunan.niigata.jp":true,"uonuma.niigata.jp":true,"yahiko.niigata.jp":true,"yoita.niigata.jp":true,"yuzawa.niigata.jp":true,"beppu.oita.jp":true,"bungoono.oita.jp":true,"bungotakada.oita.jp":true,"hasama.oita.jp":true,"hiji.oita.jp":true,"himeshima.oita.jp":true,"hita.oita.jp":true,"kamitsue.oita.jp":true,"kokonoe.oita.jp":true,"kuju.oita.jp":true,"kunisaki.oita.jp":true,"kusu.oita.jp":true,"oita.oita.jp":true,"saiki.oita.jp":true,"taketa.oita.jp":true,"tsukumi.oita.jp":true,"usa.oita.jp":true,"usuki.oita.jp":true,"yufu.oita.jp":true,"akaiwa.okayama.jp":true,"asakuchi.okayama.jp":true,"bizen.okayama.jp":true,"hayashima.okayama.jp":true,"ibara.okayama.jp":true,"kagamino.okayama.jp":true,"kasaoka.okayama.jp":true,"kibichuo.okayama.jp":true,"kumenan.okayama.jp":true,"kurashiki.okayama.jp":true,"maniwa.okayama.jp":true,"misaki.okayama.jp":true,"nagi.okayama.jp":true,"niimi.okayama.jp":true,"nishiawakura.okayama.jp":true,"okayama.okayama.jp":true,"satosho.okayama.jp":true,"setouchi.okayama.jp":true,"shinjo.okayama.jp":true,"shoo.okayama.jp":true,"soja.okayama.jp":true,"takahashi.okayama.jp":true,"tamano.okayama.jp":true,"tsuyama.okayama.jp":true,"wake.okayama.jp":true,"yakage.okayama.jp":true,"aguni.okinawa.jp":true,"ginowan.okinawa.jp":true,"ginoza.okinawa.jp":true,"gushikami.okinawa.jp":true,"haebaru.okinawa.jp":true,"higashi.okinawa.jp":true,"hirara.okinawa.jp":true,"iheya.okinawa.jp":true,"ishigaki.okinawa.jp":true,"ishikawa.okinawa.jp":true,"itoman.okinawa.jp":true,"izena.okinawa.jp":true,"kadena.okinawa.jp":true,"kin.okinawa.jp":true,"kitadaito.okinawa.jp":true,"kitanakagusuku.okinawa.jp":true,"kumejima.okinawa.jp":true,"kunigami.okinawa.jp":true,"minamidaito.okinawa.jp":true,"motobu.okinawa.jp":true,"nago.okinawa.jp":true,"naha.okinawa.jp":true,"nakagusuku.okinawa.jp":true,"nakijin.okinawa.jp":true,"nanjo.okinawa.jp":true,"nishihara.okinawa.jp":true,"ogimi.okinawa.jp":true,"okinawa.okinawa.jp":true,"onna.okinawa.jp":true,"shimoji.okinawa.jp":true,"taketomi.okinawa.jp":true,"tarama.okinawa.jp":true,"tokashiki.okinawa.jp":true,"tomigusuku.okinawa.jp":true,"tonaki.okinawa.jp":true,"urasoe.okinawa.jp":true,"uruma.okinawa.jp":true,"yaese.okinawa.jp":true,"yomitan.okinawa.jp":true,"yonabaru.okinawa.jp":true,"yonaguni.okinawa.jp":true,"zamami.okinawa.jp":true,"abeno.osaka.jp":true,"chihayaakasaka.osaka.jp":true,"chuo.osaka.jp":true,"daito.osaka.jp":true,"fujiidera.osaka.jp":true,"habikino.osaka.jp":true,"hannan.osaka.jp":true,"higashiosaka.osaka.jp":true,"higashisumiyoshi.osaka.jp":true,"higashiyodogawa.osaka.jp":true,"hirakata.osaka.jp":true,"ibaraki.osaka.jp":true,"ikeda.osaka.jp":true,"izumi.osaka.jp":true,"izumiotsu.osaka.jp":true,"izumisano.osaka.jp":true,"kadoma.osaka.jp":true,"kaizuka.osaka.jp":true,"kanan.osaka.jp":true,"kashiwara.osaka.jp":true,"katano.osaka.jp":true,"kawachinagano.osaka.jp":true,"kishiwada.osaka.jp":true,"kita.osaka.jp":true,"kumatori.osaka.jp":true,"matsubara.osaka.jp":true,"minato.osaka.jp":true,"minoh.osaka.jp":true,"misaki.osaka.jp":true,"moriguchi.osaka.jp":true,"neyagawa.osaka.jp":true,"nishi.osaka.jp":true,"nose.osaka.jp":true,"osakasayama.osaka.jp":true,"sakai.osaka.jp":true,"sayama.osaka.jp":true,"sennan.osaka.jp":true,"settsu.osaka.jp":true,"shijonawate.osaka.jp":true,"shimamoto.osaka.jp":true,"suita.osaka.jp":true,"tadaoka.osaka.jp":true,"taishi.osaka.jp":true,"tajiri.osaka.jp":true,"takaishi.osaka.jp":true,"takatsuki.osaka.jp":true,"tondabayashi.osaka.jp":true,"toyonaka.osaka.jp":true,"toyono.osaka.jp":true,"yao.osaka.jp":true,"ariake.saga.jp":true,"arita.saga.jp":true,"fukudomi.saga.jp":true,"genkai.saga.jp":true,"hamatama.saga.jp":true,"hizen.saga.jp":true,"imari.saga.jp":true,"kamimine.saga.jp":true,"kanzaki.saga.jp":true,"karatsu.saga.jp":true,"kashima.saga.jp":true,"kitagata.saga.jp":true,"kitahata.saga.jp":true,"kiyama.saga.jp":true,"kouhoku.saga.jp":true,"kyuragi.saga.jp":true,"nishiarita.saga.jp":true,"ogi.saga.jp":true,"omachi.saga.jp":true,"ouchi.saga.jp":true,"saga.saga.jp":true,"shiroishi.saga.jp":true,"taku.saga.jp":true,"tara.saga.jp":true,"tosu.saga.jp":true,"yoshinogari.saga.jp":true,"arakawa.saitama.jp":true,"asaka.saitama.jp":true,"chichibu.saitama.jp":true,"fujimi.saitama.jp":true,"fujimino.saitama.jp":true,"fukaya.saitama.jp":true,"hanno.saitama.jp":true,"hanyu.saitama.jp":true,"hasuda.saitama.jp":true,"hatogaya.saitama.jp":true,"hatoyama.saitama.jp":true,"hidaka.saitama.jp":true,"higashichichibu.saitama.jp":true,"higashimatsuyama.saitama.jp":true,"honjo.saitama.jp":true,"ina.saitama.jp":true,"iruma.saitama.jp":true,"iwatsuki.saitama.jp":true,"kamiizumi.saitama.jp":true,"kamikawa.saitama.jp":true,"kamisato.saitama.jp":true,"kasukabe.saitama.jp":true,"kawagoe.saitama.jp":true,"kawaguchi.saitama.jp":true,"kawajima.saitama.jp":true,"kazo.saitama.jp":true,"kitamoto.saitama.jp":true,"koshigaya.saitama.jp":true,"kounosu.saitama.jp":true,"kuki.saitama.jp":true,"kumagaya.saitama.jp":true,"matsubushi.saitama.jp":true,"minano.saitama.jp":true,"misato.saitama.jp":true,"miyashiro.saitama.jp":true,"miyoshi.saitama.jp":true,"moroyama.saitama.jp":true,"nagatoro.saitama.jp":true,"namegawa.saitama.jp":true,"niiza.saitama.jp":true,"ogano.saitama.jp":true,"ogawa.saitama.jp":true,"ogose.saitama.jp":true,"okegawa.saitama.jp":true,"omiya.saitama.jp":true,"otaki.saitama.jp":true,"ranzan.saitama.jp":true,"ryokami.saitama.jp":true,"saitama.saitama.jp":true,"sakado.saitama.jp":true,"satte.saitama.jp":true,"sayama.saitama.jp":true,"shiki.saitama.jp":true,"shiraoka.saitama.jp":true,"soka.saitama.jp":true,"sugito.saitama.jp":true,"toda.saitama.jp":true,"tokigawa.saitama.jp":true,"tokorozawa.saitama.jp":true,"tsurugashima.saitama.jp":true,"urawa.saitama.jp":true,"warabi.saitama.jp":true,"yashio.saitama.jp":true,"yokoze.saitama.jp":true,"yono.saitama.jp":true,"yorii.saitama.jp":true,"yoshida.saitama.jp":true,"yoshikawa.saitama.jp":true,"yoshimi.saitama.jp":true,"aisho.shiga.jp":true,"gamo.shiga.jp":true,"higashiomi.shiga.jp":true,"hikone.shiga.jp":true,"koka.shiga.jp":true,"konan.shiga.jp":true,"kosei.shiga.jp":true,"koto.shiga.jp":true,"kusatsu.shiga.jp":true,"maibara.shiga.jp":true,"moriyama.shiga.jp":true,"nagahama.shiga.jp":true,"nishiazai.shiga.jp":true,"notogawa.shiga.jp":true,"omihachiman.shiga.jp":true,"otsu.shiga.jp":true,"ritto.shiga.jp":true,"ryuoh.shiga.jp":true,"takashima.shiga.jp":true,"takatsuki.shiga.jp":true,"torahime.shiga.jp":true,"toyosato.shiga.jp":true,"yasu.shiga.jp":true,"akagi.shimane.jp":true,"ama.shimane.jp":true,"gotsu.shimane.jp":true,"hamada.shimane.jp":true,"higashiizumo.shimane.jp":true,"hikawa.shimane.jp":true,"hikimi.shimane.jp":true,"izumo.shimane.jp":true,"kakinoki.shimane.jp":true,"masuda.shimane.jp":true,"matsue.shimane.jp":true,"misato.shimane.jp":true,"nishinoshima.shimane.jp":true,"ohda.shimane.jp":true,"okinoshima.shimane.jp":true,"okuizumo.shimane.jp":true,"shimane.shimane.jp":true,"tamayu.shimane.jp":true,"tsuwano.shimane.jp":true,"unnan.shimane.jp":true,"yakumo.shimane.jp":true,"yasugi.shimane.jp":true,"yatsuka.shimane.jp":true,"arai.shizuoka.jp":true,"atami.shizuoka.jp":true,"fuji.shizuoka.jp":true,"fujieda.shizuoka.jp":true,"fujikawa.shizuoka.jp":true,"fujinomiya.shizuoka.jp":true,"fukuroi.shizuoka.jp":true,"gotemba.shizuoka.jp":true,"haibara.shizuoka.jp":true,"hamamatsu.shizuoka.jp":true,"higashiizu.shizuoka.jp":true,"ito.shizuoka.jp":true,"iwata.shizuoka.jp":true,"izu.shizuoka.jp":true,"izunokuni.shizuoka.jp":true,"kakegawa.shizuoka.jp":true,"kannami.shizuoka.jp":true,"kawanehon.shizuoka.jp":true,"kawazu.shizuoka.jp":true,"kikugawa.shizuoka.jp":true,"kosai.shizuoka.jp":true,"makinohara.shizuoka.jp":true,"matsuzaki.shizuoka.jp":true,"minamiizu.shizuoka.jp":true,"mishima.shizuoka.jp":true,"morimachi.shizuoka.jp":true,"nishiizu.shizuoka.jp":true,"numazu.shizuoka.jp":true,"omaezaki.shizuoka.jp":true,"shimada.shizuoka.jp":true,"shimizu.shizuoka.jp":true,"shimoda.shizuoka.jp":true,"shizuoka.shizuoka.jp":true,"susono.shizuoka.jp":true,"yaizu.shizuoka.jp":true,"yoshida.shizuoka.jp":true,"ashikaga.tochigi.jp":true,"bato.tochigi.jp":true,"haga.tochigi.jp":true,"ichikai.tochigi.jp":true,"iwafune.tochigi.jp":true,"kaminokawa.tochigi.jp":true,"kanuma.tochigi.jp":true,"karasuyama.tochigi.jp":true,"kuroiso.tochigi.jp":true,"mashiko.tochigi.jp":true,"mibu.tochigi.jp":true,"moka.tochigi.jp":true,"motegi.tochigi.jp":true,"nasu.tochigi.jp":true,"nasushiobara.tochigi.jp":true,"nikko.tochigi.jp":true,"nishikata.tochigi.jp":true,"nogi.tochigi.jp":true,"ohira.tochigi.jp":true,"ohtawara.tochigi.jp":true,"oyama.tochigi.jp":true,"sakura.tochigi.jp":true,"sano.tochigi.jp":true,"shimotsuke.tochigi.jp":true,"shioya.tochigi.jp":true,"takanezawa.tochigi.jp":true,"tochigi.tochigi.jp":true,"tsuga.tochigi.jp":true,"ujiie.tochigi.jp":true,"utsunomiya.tochigi.jp":true,"yaita.tochigi.jp":true,"aizumi.tokushima.jp":true,"anan.tokushima.jp":true,"ichiba.tokushima.jp":true,"itano.tokushima.jp":true,"kainan.tokushima.jp":true,"komatsushima.tokushima.jp":true,"matsushige.tokushima.jp":true,"mima.tokushima.jp":true,"minami.tokushima.jp":true,"miyoshi.tokushima.jp":true,"mugi.tokushima.jp":true,"nakagawa.tokushima.jp":true,"naruto.tokushima.jp":true,"sanagochi.tokushima.jp":true,"shishikui.tokushima.jp":true,"tokushima.tokushima.jp":true,"wajiki.tokushima.jp":true,"adachi.tokyo.jp":true,"akiruno.tokyo.jp":true,"akishima.tokyo.jp":true,"aogashima.tokyo.jp":true,"arakawa.tokyo.jp":true,"bunkyo.tokyo.jp":true,"chiyoda.tokyo.jp":true,"chofu.tokyo.jp":true,"chuo.tokyo.jp":true,"edogawa.tokyo.jp":true,"fuchu.tokyo.jp":true,"fussa.tokyo.jp":true,"hachijo.tokyo.jp":true,"hachioji.tokyo.jp":true,"hamura.tokyo.jp":true,"higashikurume.tokyo.jp":true,"higashimurayama.tokyo.jp":true,"higashiyamato.tokyo.jp":true,"hino.tokyo.jp":true,"hinode.tokyo.jp":true,"hinohara.tokyo.jp":true,"inagi.tokyo.jp":true,"itabashi.tokyo.jp":true,"katsushika.tokyo.jp":true,"kita.tokyo.jp":true,"kiyose.tokyo.jp":true,"kodaira.tokyo.jp":true,"koganei.tokyo.jp":true,"kokubunji.tokyo.jp":true,"komae.tokyo.jp":true,"koto.tokyo.jp":true,"kouzushima.tokyo.jp":true,"kunitachi.tokyo.jp":true,"machida.tokyo.jp":true,"meguro.tokyo.jp":true,"minato.tokyo.jp":true,"mitaka.tokyo.jp":true,"mizuho.tokyo.jp":true,"musashimurayama.tokyo.jp":true,"musashino.tokyo.jp":true,"nakano.tokyo.jp":true,"nerima.tokyo.jp":true,"ogasawara.tokyo.jp":true,"okutama.tokyo.jp":true,"ome.tokyo.jp":true,"oshima.tokyo.jp":true,"ota.tokyo.jp":true,"setagaya.tokyo.jp":true,"shibuya.tokyo.jp":true,"shinagawa.tokyo.jp":true,"shinjuku.tokyo.jp":true,"suginami.tokyo.jp":true,"sumida.tokyo.jp":true,"tachikawa.tokyo.jp":true,"taito.tokyo.jp":true,"tama.tokyo.jp":true,"toshima.tokyo.jp":true,"chizu.tottori.jp":true,"hino.tottori.jp":true,"kawahara.tottori.jp":true,"koge.tottori.jp":true,"kotoura.tottori.jp":true,"misasa.tottori.jp":true,"nanbu.tottori.jp":true,"nichinan.tottori.jp":true,"sakaiminato.tottori.jp":true,"tottori.tottori.jp":true,"wakasa.tottori.jp":true,"yazu.tottori.jp":true,"yonago.tottori.jp":true,"asahi.toyama.jp":true,"fuchu.toyama.jp":true,"fukumitsu.toyama.jp":true,"funahashi.toyama.jp":true,"himi.toyama.jp":true,"imizu.toyama.jp":true,"inami.toyama.jp":true,"johana.toyama.jp":true,"kamiichi.toyama.jp":true,"kurobe.toyama.jp":true,"nakaniikawa.toyama.jp":true,"namerikawa.toyama.jp":true,"nanto.toyama.jp":true,"nyuzen.toyama.jp":true,"oyabe.toyama.jp":true,"taira.toyama.jp":true,"takaoka.toyama.jp":true,"tateyama.toyama.jp":true,"toga.toyama.jp":true,"tonami.toyama.jp":true,"toyama.toyama.jp":true,"unazuki.toyama.jp":true,"uozu.toyama.jp":true,"yamada.toyama.jp":true,"arida.wakayama.jp":true,"aridagawa.wakayama.jp":true,"gobo.wakayama.jp":true,"hashimoto.wakayama.jp":true,"hidaka.wakayama.jp":true,"hirogawa.wakayama.jp":true,"inami.wakayama.jp":true,"iwade.wakayama.jp":true,"kainan.wakayama.jp":true,"kamitonda.wakayama.jp":true,"katsuragi.wakayama.jp":true,"kimino.wakayama.jp":true,"kinokawa.wakayama.jp":true,"kitayama.wakayama.jp":true,"koya.wakayama.jp":true,"koza.wakayama.jp":true,"kozagawa.wakayama.jp":true,"kudoyama.wakayama.jp":true,"kushimoto.wakayama.jp":true,"mihama.wakayama.jp":true,"misato.wakayama.jp":true,"nachikatsuura.wakayama.jp":true,"shingu.wakayama.jp":true,"shirahama.wakayama.jp":true,"taiji.wakayama.jp":true,"tanabe.wakayama.jp":true,"wakayama.wakayama.jp":true,"yuasa.wakayama.jp":true,"yura.wakayama.jp":true,"asahi.yamagata.jp":true,"funagata.yamagata.jp":true,"higashine.yamagata.jp":true,"iide.yamagata.jp":true,"kahoku.yamagata.jp":true,"kaminoyama.yamagata.jp":true,"kaneyama.yamagata.jp":true,"kawanishi.yamagata.jp":true,"mamurogawa.yamagata.jp":true,"mikawa.yamagata.jp":true,"murayama.yamagata.jp":true,"nagai.yamagata.jp":true,"nakayama.yamagata.jp":true,"nanyo.yamagata.jp":true,"nishikawa.yamagata.jp":true,"obanazawa.yamagata.jp":true,"oe.yamagata.jp":true,"oguni.yamagata.jp":true,"ohkura.yamagata.jp":true,"oishida.yamagata.jp":true,"sagae.yamagata.jp":true,"sakata.yamagata.jp":true,"sakegawa.yamagata.jp":true,"shinjo.yamagata.jp":true,"shirataka.yamagata.jp":true,"shonai.yamagata.jp":true,"takahata.yamagata.jp":true,"tendo.yamagata.jp":true,"tozawa.yamagata.jp":true,"tsuruoka.yamagata.jp":true,"yamagata.yamagata.jp":true,"yamanobe.yamagata.jp":true,"yonezawa.yamagata.jp":true,"yuza.yamagata.jp":true,"abu.yamaguchi.jp":true,"hagi.yamaguchi.jp":true,"hikari.yamaguchi.jp":true,"hofu.yamaguchi.jp":true,"iwakuni.yamaguchi.jp":true,"kudamatsu.yamaguchi.jp":true,"mitou.yamaguchi.jp":true,"nagato.yamaguchi.jp":true,"oshima.yamaguchi.jp":true,"shimonoseki.yamaguchi.jp":true,"shunan.yamaguchi.jp":true,"tabuse.yamaguchi.jp":true,"tokuyama.yamaguchi.jp":true,"toyota.yamaguchi.jp":true,"ube.yamaguchi.jp":true,"yuu.yamaguchi.jp":true,"chuo.yamanashi.jp":true,"doshi.yamanashi.jp":true,"fuefuki.yamanashi.jp":true,"fujikawa.yamanashi.jp":true,"fujikawaguchiko.yamanashi.jp":true,"fujiyoshida.yamanashi.jp":true,"hayakawa.yamanashi.jp":true,"hokuto.yamanashi.jp":true,"ichikawamisato.yamanashi.jp":true,"kai.yamanashi.jp":true,"kofu.yamanashi.jp":true,"koshu.yamanashi.jp":true,"kosuge.yamanashi.jp":true,"minami-alps.yamanashi.jp":true,"minobu.yamanashi.jp":true,"nakamichi.yamanashi.jp":true,"nanbu.yamanashi.jp":true,"narusawa.yamanashi.jp":true,"nirasaki.yamanashi.jp":true,"nishikatsura.yamanashi.jp":true,"oshino.yamanashi.jp":true,"otsuki.yamanashi.jp":true,"showa.yamanashi.jp":true,"tabayama.yamanashi.jp":true,"tsuru.yamanashi.jp":true,"uenohara.yamanashi.jp":true,"yamanakako.yamanashi.jp":true,"yamanashi.yamanashi.jp":true,"*.ke":true,"kg":true,"org.kg":true,"net.kg":true,"com.kg":true,"edu.kg":true,"gov.kg":true,"mil.kg":true,"*.kh":true,"ki":true,"edu.ki":true,"biz.ki":true,"net.ki":true,"org.ki":true,"gov.ki":true,"info.ki":true,"com.ki":true,"km":true,"org.km":true,"nom.km":true,"gov.km":true,"prd.km":true,"tm.km":true,"edu.km":true,"mil.km":true,"ass.km":true,"com.km":true,"coop.km":true,"asso.km":true,"presse.km":true,"medecin.km":true,"notaires.km":true,"pharmaciens.km":true,"veterinaire.km":true,"gouv.km":true,"kn":true,"net.kn":true,"org.kn":true,"edu.kn":true,"gov.kn":true,"kp":true,"com.kp":true,"edu.kp":true,"gov.kp":true,"org.kp":true,"rep.kp":true,"tra.kp":true,"kr":true,"ac.kr":true,"co.kr":true,"es.kr":true,"go.kr":true,"hs.kr":true,"kg.kr":true,"mil.kr":true,"ms.kr":true,"ne.kr":true,"or.kr":true,"pe.kr":true,"re.kr":true,"sc.kr":true,"busan.kr":true,"chungbuk.kr":true,"chungnam.kr":true,"daegu.kr":true,"daejeon.kr":true,"gangwon.kr":true,"gwangju.kr":true,"gyeongbuk.kr":true,"gyeonggi.kr":true,"gyeongnam.kr":true,"incheon.kr":true,"jeju.kr":true,"jeonbuk.kr":true,"jeonnam.kr":true,"seoul.kr":true,"ulsan.kr":true,"*.kw":true,"ky":true,"edu.ky":true,"gov.ky":true,"com.ky":true,"org.ky":true,"net.ky":true,"kz":true,"org.kz":true,"edu.kz":true,"net.kz":true,"gov.kz":true,"mil.kz":true,"com.kz":true,"la":true,"int.la":true,"net.la":true,"info.la":true,"edu.la":true,"gov.la":true,"per.la":true,"com.la":true,"org.la":true,"lb":true,"com.lb":true,"edu.lb":true,"gov.lb":true,"net.lb":true,"org.lb":true,"lc":true,"com.lc":true,"net.lc":true,"co.lc":true,"org.lc":true,"edu.lc":true,"gov.lc":true,"li":true,"lk":true,"gov.lk":true,"sch.lk":true,"net.lk":true,"int.lk":true,"com.lk":true,"org.lk":true,"edu.lk":true,"ngo.lk":true,"soc.lk":true,"web.lk":true,"ltd.lk":true,"assn.lk":true,"grp.lk":true,"hotel.lk":true,"ac.lk":true,"lr":true,"com.lr":true,"edu.lr":true,"gov.lr":true,"org.lr":true,"net.lr":true,"ls":true,"co.ls":true,"org.ls":true,"lt":true,"gov.lt":true,"lu":true,"lv":true,"com.lv":true,"edu.lv":true,"gov.lv":true,"org.lv":true,"mil.lv":true,"id.lv":true,"net.lv":true,"asn.lv":true,"conf.lv":true,"ly":true,"com.ly":true,"net.ly":true,"gov.ly":true,"plc.ly":true,"edu.ly":true,"sch.ly":true,"med.ly":true,"org.ly":true,"id.ly":true,"ma":true,"co.ma":true,"net.ma":true,"gov.ma":true,"org.ma":true,"ac.ma":true,"press.ma":true,"mc":true,"tm.mc":true,"asso.mc":true,"md":true,"me":true,"co.me":true,"net.me":true,"org.me":true,"edu.me":true,"ac.me":true,"gov.me":true,"its.me":true,"priv.me":true,"mg":true,"org.mg":true,"nom.mg":true,"gov.mg":true,"prd.mg":true,"tm.mg":true,"edu.mg":true,"mil.mg":true,"com.mg":true,"co.mg":true,"mh":true,"mil":true,"mk":true,"com.mk":true,"org.mk":true,"net.mk":true,"edu.mk":true,"gov.mk":true,"inf.mk":true,"name.mk":true,"ml":true,"com.ml":true,"edu.ml":true,"gouv.ml":true,"gov.ml":true,"net.ml":true,"org.ml":true,"presse.ml":true,"*.mm":true,"mn":true,"gov.mn":true,"edu.mn":true,"org.mn":true,"mo":true,"com.mo":true,"net.mo":true,"org.mo":true,"edu.mo":true,"gov.mo":true,"mobi":true,"mp":true,"mq":true,"mr":true,"gov.mr":true,"ms":true,"com.ms":true,"edu.ms":true,"gov.ms":true,"net.ms":true,"org.ms":true,"mt":true,"com.mt":true,"edu.mt":true,"net.mt":true,"org.mt":true,"mu":true,"com.mu":true,"net.mu":true,"org.mu":true,"gov.mu":true,"ac.mu":true,"co.mu":true,"or.mu":true,"museum":true,"academy.museum":true,"agriculture.museum":true,"air.museum":true,"airguard.museum":true,"alabama.museum":true,"alaska.museum":true,"amber.museum":true,"ambulance.museum":true,"american.museum":true,"americana.museum":true,"americanantiques.museum":true,"americanart.museum":true,"amsterdam.museum":true,"and.museum":true,"annefrank.museum":true,"anthro.museum":true,"anthropology.museum":true,"antiques.museum":true,"aquarium.museum":true,"arboretum.museum":true,"archaeological.museum":true,"archaeology.museum":true,"architecture.museum":true,"art.museum":true,"artanddesign.museum":true,"artcenter.museum":true,"artdeco.museum":true,"arteducation.museum":true,"artgallery.museum":true,"arts.museum":true,"artsandcrafts.museum":true,"asmatart.museum":true,"assassination.museum":true,"assisi.museum":true,"association.museum":true,"astronomy.museum":true,"atlanta.museum":true,"austin.museum":true,"australia.museum":true,"automotive.museum":true,"aviation.museum":true,"axis.museum":true,"badajoz.museum":true,"baghdad.museum":true,"bahn.museum":true,"bale.museum":true,"baltimore.museum":true,"barcelona.museum":true,"baseball.museum":true,"basel.museum":true,"baths.museum":true,"bauern.museum":true,"beauxarts.museum":true,"beeldengeluid.museum":true,"bellevue.museum":true,"bergbau.museum":true,"berkeley.museum":true,"berlin.museum":true,"bern.museum":true,"bible.museum":true,"bilbao.museum":true,"bill.museum":true,"birdart.museum":true,"birthplace.museum":true,"bonn.museum":true,"boston.museum":true,"botanical.museum":true,"botanicalgarden.museum":true,"botanicgarden.museum":true,"botany.museum":true,"brandywinevalley.museum":true,"brasil.museum":true,"bristol.museum":true,"british.museum":true,"britishcolumbia.museum":true,"broadcast.museum":true,"brunel.museum":true,"brussel.museum":true,"brussels.museum":true,"bruxelles.museum":true,"building.museum":true,"burghof.museum":true,"bus.museum":true,"bushey.museum":true,"cadaques.museum":true,"california.museum":true,"cambridge.museum":true,"can.museum":true,"canada.museum":true,"capebreton.museum":true,"carrier.museum":true,"cartoonart.museum":true,"casadelamoneda.museum":true,"castle.museum":true,"castres.museum":true,"celtic.museum":true,"center.museum":true,"chattanooga.museum":true,"cheltenham.museum":true,"chesapeakebay.museum":true,"chicago.museum":true,"children.museum":true,"childrens.museum":true,"childrensgarden.museum":true,"chiropractic.museum":true,"chocolate.museum":true,"christiansburg.museum":true,"cincinnati.museum":true,"cinema.museum":true,"circus.museum":true,"civilisation.museum":true,"civilization.museum":true,"civilwar.museum":true,"clinton.museum":true,"clock.museum":true,"coal.museum":true,"coastaldefence.museum":true,"cody.museum":true,"coldwar.museum":true,"collection.museum":true,"colonialwilliamsburg.museum":true,"coloradoplateau.museum":true,"columbia.museum":true,"columbus.museum":true,"communication.museum":true,"communications.museum":true,"community.museum":true,"computer.museum":true,"computerhistory.museum":true,"xn--comunicaes-v6a2o.museum":true,"contemporary.museum":true,"contemporaryart.museum":true,"convent.museum":true,"copenhagen.museum":true,"corporation.museum":true,"xn--correios-e-telecomunicaes-ghc29a.museum":true,"corvette.museum":true,"costume.museum":true,"countryestate.museum":true,"county.museum":true,"crafts.museum":true,"cranbrook.museum":true,"creation.museum":true,"cultural.museum":true,"culturalcenter.museum":true,"culture.museum":true,"cyber.museum":true,"cymru.museum":true,"dali.museum":true,"dallas.museum":true,"database.museum":true,"ddr.museum":true,"decorativearts.museum":true,"delaware.museum":true,"delmenhorst.museum":true,"denmark.museum":true,"depot.museum":true,"design.museum":true,"detroit.museum":true,"dinosaur.museum":true,"discovery.museum":true,"dolls.museum":true,"donostia.museum":true,"durham.museum":true,"eastafrica.museum":true,"eastcoast.museum":true,"education.museum":true,"educational.museum":true,"egyptian.museum":true,"eisenbahn.museum":true,"elburg.museum":true,"elvendrell.museum":true,"embroidery.museum":true,"encyclopedic.museum":true,"england.museum":true,"entomology.museum":true,"environment.museum":true,"environmentalconservation.museum":true,"epilepsy.museum":true,"essex.museum":true,"estate.museum":true,"ethnology.museum":true,"exeter.museum":true,"exhibition.museum":true,"family.museum":true,"farm.museum":true,"farmequipment.museum":true,"farmers.museum":true,"farmstead.museum":true,"field.museum":true,"figueres.museum":true,"filatelia.museum":true,"film.museum":true,"fineart.museum":true,"finearts.museum":true,"finland.museum":true,"flanders.museum":true,"florida.museum":true,"force.museum":true,"fortmissoula.museum":true,"fortworth.museum":true,"foundation.museum":true,"francaise.museum":true,"frankfurt.museum":true,"franziskaner.museum":true,"freemasonry.museum":true,"freiburg.museum":true,"fribourg.museum":true,"frog.museum":true,"fundacio.museum":true,"furniture.museum":true,"gallery.museum":true,"garden.museum":true,"gateway.museum":true,"geelvinck.museum":true,"gemological.museum":true,"geology.museum":true,"georgia.museum":true,"giessen.museum":true,"glas.museum":true,"glass.museum":true,"gorge.museum":true,"grandrapids.museum":true,"graz.museum":true,"guernsey.museum":true,"halloffame.museum":true,"hamburg.museum":true,"handson.museum":true,"harvestcelebration.museum":true,"hawaii.museum":true,"health.museum":true,"heimatunduhren.museum":true,"hellas.museum":true,"helsinki.museum":true,"hembygdsforbund.museum":true,"heritage.museum":true,"histoire.museum":true,"historical.museum":true,"historicalsociety.museum":true,"historichouses.museum":true,"historisch.museum":true,"historisches.museum":true,"history.museum":true,"historyofscience.museum":true,"horology.museum":true,"house.museum":true,"humanities.museum":true,"illustration.museum":true,"imageandsound.museum":true,"indian.museum":true,"indiana.museum":true,"indianapolis.museum":true,"indianmarket.museum":true,"intelligence.museum":true,"interactive.museum":true,"iraq.museum":true,"iron.museum":true,"isleofman.museum":true,"jamison.museum":true,"jefferson.museum":true,"jerusalem.museum":true,"jewelry.museum":true,"jewish.museum":true,"jewishart.museum":true,"jfk.museum":true,"journalism.museum":true,"judaica.museum":true,"judygarland.museum":true,"juedisches.museum":true,"juif.museum":true,"karate.museum":true,"karikatur.museum":true,"kids.museum":true,"koebenhavn.museum":true,"koeln.museum":true,"kunst.museum":true,"kunstsammlung.museum":true,"kunstunddesign.museum":true,"labor.museum":true,"labour.museum":true,"lajolla.museum":true,"lancashire.museum":true,"landes.museum":true,"lans.museum":true,"xn--lns-qla.museum":true,"larsson.museum":true,"lewismiller.museum":true,"lincoln.museum":true,"linz.museum":true,"living.museum":true,"livinghistory.museum":true,"localhistory.museum":true,"london.museum":true,"losangeles.museum":true,"louvre.museum":true,"loyalist.museum":true,"lucerne.museum":true,"luxembourg.museum":true,"luzern.museum":true,"mad.museum":true,"madrid.museum":true,"mallorca.museum":true,"manchester.museum":true,"mansion.museum":true,"mansions.museum":true,"manx.museum":true,"marburg.museum":true,"maritime.museum":true,"maritimo.museum":true,"maryland.museum":true,"marylhurst.museum":true,"media.museum":true,"medical.museum":true,"medizinhistorisches.museum":true,"meeres.museum":true,"memorial.museum":true,"mesaverde.museum":true,"michigan.museum":true,"midatlantic.museum":true,"military.museum":true,"mill.museum":true,"miners.museum":true,"mining.museum":true,"minnesota.museum":true,"missile.museum":true,"missoula.museum":true,"modern.museum":true,"moma.museum":true,"money.museum":true,"monmouth.museum":true,"monticello.museum":true,"montreal.museum":true,"moscow.museum":true,"motorcycle.museum":true,"muenchen.museum":true,"muenster.museum":true,"mulhouse.museum":true,"muncie.museum":true,"museet.museum":true,"museumcenter.museum":true,"museumvereniging.museum":true,"music.museum":true,"national.museum":true,"nationalfirearms.museum":true,"nationalheritage.museum":true,"nativeamerican.museum":true,"naturalhistory.museum":true,"naturalhistorymuseum.museum":true,"naturalsciences.museum":true,"nature.museum":true,"naturhistorisches.museum":true,"natuurwetenschappen.museum":true,"naumburg.museum":true,"naval.museum":true,"nebraska.museum":true,"neues.museum":true,"newhampshire.museum":true,"newjersey.museum":true,"newmexico.museum":true,"newport.museum":true,"newspaper.museum":true,"newyork.museum":true,"niepce.museum":true,"norfolk.museum":true,"north.museum":true,"nrw.museum":true,"nuernberg.museum":true,"nuremberg.museum":true,"nyc.museum":true,"nyny.museum":true,"oceanographic.museum":true,"oceanographique.museum":true,"omaha.museum":true,"online.museum":true,"ontario.museum":true,"openair.museum":true,"oregon.museum":true,"oregontrail.museum":true,"otago.museum":true,"oxford.museum":true,"pacific.museum":true,"paderborn.museum":true,"palace.museum":true,"paleo.museum":true,"palmsprings.museum":true,"panama.museum":true,"paris.museum":true,"pasadena.museum":true,"pharmacy.museum":true,"philadelphia.museum":true,"philadelphiaarea.museum":true,"philately.museum":true,"phoenix.museum":true,"photography.museum":true,"pilots.museum":true,"pittsburgh.museum":true,"planetarium.museum":true,"plantation.museum":true,"plants.museum":true,"plaza.museum":true,"portal.museum":true,"portland.museum":true,"portlligat.museum":true,"posts-and-telecommunications.museum":true,"preservation.museum":true,"presidio.museum":true,"press.museum":true,"project.museum":true,"public.museum":true,"pubol.museum":true,"quebec.museum":true,"railroad.museum":true,"railway.museum":true,"research.museum":true,"resistance.museum":true,"riodejaneiro.museum":true,"rochester.museum":true,"rockart.museum":true,"roma.museum":true,"russia.museum":true,"saintlouis.museum":true,"salem.museum":true,"salvadordali.museum":true,"salzburg.museum":true,"sandiego.museum":true,"sanfrancisco.museum":true,"santabarbara.museum":true,"santacruz.museum":true,"santafe.museum":true,"saskatchewan.museum":true,"satx.museum":true,"savannahga.museum":true,"schlesisches.museum":true,"schoenbrunn.museum":true,"schokoladen.museum":true,"school.museum":true,"schweiz.museum":true,"science.museum":true,"scienceandhistory.museum":true,"scienceandindustry.museum":true,"sciencecenter.museum":true,"sciencecenters.museum":true,"science-fiction.museum":true,"sciencehistory.museum":true,"sciences.museum":true,"sciencesnaturelles.museum":true,"scotland.museum":true,"seaport.museum":true,"settlement.museum":true,"settlers.museum":true,"shell.museum":true,"sherbrooke.museum":true,"sibenik.museum":true,"silk.museum":true,"ski.museum":true,"skole.museum":true,"society.museum":true,"sologne.museum":true,"soundandvision.museum":true,"southcarolina.museum":true,"southwest.museum":true,"space.museum":true,"spy.museum":true,"square.museum":true,"stadt.museum":true,"stalbans.museum":true,"starnberg.museum":true,"state.museum":true,"stateofdelaware.museum":true,"station.museum":true,"steam.museum":true,"steiermark.museum":true,"stjohn.museum":true,"stockholm.museum":true,"stpetersburg.museum":true,"stuttgart.museum":true,"suisse.museum":true,"surgeonshall.museum":true,"surrey.museum":true,"svizzera.museum":true,"sweden.museum":true,"sydney.museum":true,"tank.museum":true,"tcm.museum":true,"technology.museum":true,"telekommunikation.museum":true,"television.museum":true,"texas.museum":true,"textile.museum":true,"theater.museum":true,"time.museum":true,"timekeeping.museum":true,"topology.museum":true,"torino.museum":true,"touch.museum":true,"town.museum":true,"transport.museum":true,"tree.museum":true,"trolley.museum":true,"trust.museum":true,"trustee.museum":true,"uhren.museum":true,"ulm.museum":true,"undersea.museum":true,"university.museum":true,"usa.museum":true,"usantiques.museum":true,"usarts.museum":true,"uscountryestate.museum":true,"usculture.museum":true,"usdecorativearts.museum":true,"usgarden.museum":true,"ushistory.museum":true,"ushuaia.museum":true,"uslivinghistory.museum":true,"utah.museum":true,"uvic.museum":true,"valley.museum":true,"vantaa.museum":true,"versailles.museum":true,"viking.museum":true,"village.museum":true,"virginia.museum":true,"virtual.museum":true,"virtuel.museum":true,"vlaanderen.museum":true,"volkenkunde.museum":true,"wales.museum":true,"wallonie.museum":true,"war.museum":true,"washingtondc.museum":true,"watchandclock.museum":true,"watch-and-clock.museum":true,"western.museum":true,"westfalen.museum":true,"whaling.museum":true,"wildlife.museum":true,"williamsburg.museum":true,"windmill.museum":true,"workshop.museum":true,"york.museum":true,"yorkshire.museum":true,"yosemite.museum":true,"youth.museum":true,"zoological.museum":true,"zoology.museum":true,"xn--9dbhblg6di.museum":true,"xn--h1aegh.museum":true,"mv":true,"aero.mv":true,"biz.mv":true,"com.mv":true,"coop.mv":true,"edu.mv":true,"gov.mv":true,"info.mv":true,"int.mv":true,"mil.mv":true,"museum.mv":true,"name.mv":true,"net.mv":true,"org.mv":true,"pro.mv":true,"mw":true,"ac.mw":true,"biz.mw":true,"co.mw":true,"com.mw":true,"coop.mw":true,"edu.mw":true,"gov.mw":true,"int.mw":true,"museum.mw":true,"net.mw":true,"org.mw":true,"mx":true,"com.mx":true,"org.mx":true,"gob.mx":true,"edu.mx":true,"net.mx":true,"my":true,"com.my":true,"net.my":true,"org.my":true,"gov.my":true,"edu.my":true,"mil.my":true,"name.my":true,"*.mz":true,"teledata.mz":false,"na":true,"info.na":true,"pro.na":true,"name.na":true,"school.na":true,"or.na":true,"dr.na":true,"us.na":true,"mx.na":true,"ca.na":true,"in.na":true,"cc.na":true,"tv.na":true,"ws.na":true,"mobi.na":true,"co.na":true,"com.na":true,"org.na":true,"name":true,"nc":true,"asso.nc":true,"ne":true,"net":true,"nf":true,"com.nf":true,"net.nf":true,"per.nf":true,"rec.nf":true,"web.nf":true,"arts.nf":true,"firm.nf":true,"info.nf":true,"other.nf":true,"store.nf":true,"ng":true,"com.ng":true,"edu.ng":true,"name.ng":true,"net.ng":true,"org.ng":true,"sch.ng":true,"gov.ng":true,"mil.ng":true,"mobi.ng":true,"*.ni":true,"nl":true,"bv.nl":true,"no":true,"fhs.no":true,"vgs.no":true,"fylkesbibl.no":true,"folkebibl.no":true,"museum.no":true,"idrett.no":true,"priv.no":true,"mil.no":true,"stat.no":true,"dep.no":true,"kommune.no":true,"herad.no":true,"aa.no":true,"ah.no":true,"bu.no":true,"fm.no":true,"hl.no":true,"hm.no":true,"jan-mayen.no":true,"mr.no":true,"nl.no":true,"nt.no":true,"of.no":true,"ol.no":true,"oslo.no":true,"rl.no":true,"sf.no":true,"st.no":true,"svalbard.no":true,"tm.no":true,"tr.no":true,"va.no":true,"vf.no":true,"gs.aa.no":true,"gs.ah.no":true,"gs.bu.no":true,"gs.fm.no":true,"gs.hl.no":true,"gs.hm.no":true,"gs.jan-mayen.no":true,"gs.mr.no":true,"gs.nl.no":true,"gs.nt.no":true,"gs.of.no":true,"gs.ol.no":true,"gs.oslo.no":true,"gs.rl.no":true,"gs.sf.no":true,"gs.st.no":true,"gs.svalbard.no":true,"gs.tm.no":true,"gs.tr.no":true,"gs.va.no":true,"gs.vf.no":true,"akrehamn.no":true,"xn--krehamn-dxa.no":true,"algard.no":true,"xn--lgrd-poac.no":true,"arna.no":true,"brumunddal.no":true,"bryne.no":true,"bronnoysund.no":true,"xn--brnnysund-m8ac.no":true,"drobak.no":true,"xn--drbak-wua.no":true,"egersund.no":true,"fetsund.no":true,"floro.no":true,"xn--flor-jra.no":true,"fredrikstad.no":true,"hokksund.no":true,"honefoss.no":true,"xn--hnefoss-q1a.no":true,"jessheim.no":true,"jorpeland.no":true,"xn--jrpeland-54a.no":true,"kirkenes.no":true,"kopervik.no":true,"krokstadelva.no":true,"langevag.no":true,"xn--langevg-jxa.no":true,"leirvik.no":true,"mjondalen.no":true,"xn--mjndalen-64a.no":true,"mo-i-rana.no":true,"mosjoen.no":true,"xn--mosjen-eya.no":true,"nesoddtangen.no":true,"orkanger.no":true,"osoyro.no":true,"xn--osyro-wua.no":true,"raholt.no":true,"xn--rholt-mra.no":true,"sandnessjoen.no":true,"xn--sandnessjen-ogb.no":true,"skedsmokorset.no":true,"slattum.no":true,"spjelkavik.no":true,"stathelle.no":true,"stavern.no":true,"stjordalshalsen.no":true,"xn--stjrdalshalsen-sqb.no":true,"tananger.no":true,"tranby.no":true,"vossevangen.no":true,"afjord.no":true,"xn--fjord-lra.no":true,"agdenes.no":true,"al.no":true,"xn--l-1fa.no":true,"alesund.no":true,"xn--lesund-hua.no":true,"alstahaug.no":true,"alta.no":true,"xn--lt-liac.no":true,"alaheadju.no":true,"xn--laheadju-7ya.no":true,"alvdal.no":true,"amli.no":true,"xn--mli-tla.no":true,"amot.no":true,"xn--mot-tla.no":true,"andebu.no":true,"andoy.no":true,"xn--andy-ira.no":true,"andasuolo.no":true,"ardal.no":true,"xn--rdal-poa.no":true,"aremark.no":true,"arendal.no":true,"xn--s-1fa.no":true,"aseral.no":true,"xn--seral-lra.no":true,"asker.no":true,"askim.no":true,"askvoll.no":true,"askoy.no":true,"xn--asky-ira.no":true,"asnes.no":true,"xn--snes-poa.no":true,"audnedaln.no":true,"aukra.no":true,"aure.no":true,"aurland.no":true,"aurskog-holand.no":true,"xn--aurskog-hland-jnb.no":true,"austevoll.no":true,"austrheim.no":true,"averoy.no":true,"xn--avery-yua.no":true,"balestrand.no":true,"ballangen.no":true,"balat.no":true,"xn--blt-elab.no":true,"balsfjord.no":true,"bahccavuotna.no":true,"xn--bhccavuotna-k7a.no":true,"bamble.no":true,"bardu.no":true,"beardu.no":true,"beiarn.no":true,"bajddar.no":true,"xn--bjddar-pta.no":true,"baidar.no":true,"xn--bidr-5nac.no":true,"berg.no":true,"bergen.no":true,"berlevag.no":true,"xn--berlevg-jxa.no":true,"bearalvahki.no":true,"xn--bearalvhki-y4a.no":true,"bindal.no":true,"birkenes.no":true,"bjarkoy.no":true,"xn--bjarky-fya.no":true,"bjerkreim.no":true,"bjugn.no":true,"bodo.no":true,"xn--bod-2na.no":true,"badaddja.no":true,"xn--bdddj-mrabd.no":true,"budejju.no":true,"bokn.no":true,"bremanger.no":true,"bronnoy.no":true,"xn--brnny-wuac.no":true,"bygland.no":true,"bykle.no":true,"barum.no":true,"xn--brum-voa.no":true,"bo.telemark.no":true,"xn--b-5ga.telemark.no":true,"bo.nordland.no":true,"xn--b-5ga.nordland.no":true,"bievat.no":true,"xn--bievt-0qa.no":true,"bomlo.no":true,"xn--bmlo-gra.no":true,"batsfjord.no":true,"xn--btsfjord-9za.no":true,"bahcavuotna.no":true,"xn--bhcavuotna-s4a.no":true,"dovre.no":true,"drammen.no":true,"drangedal.no":true,"dyroy.no":true,"xn--dyry-ira.no":true,"donna.no":true,"xn--dnna-gra.no":true,"eid.no":true,"eidfjord.no":true,"eidsberg.no":true,"eidskog.no":true,"eidsvoll.no":true,"eigersund.no":true,"elverum.no":true,"enebakk.no":true,"engerdal.no":true,"etne.no":true,"etnedal.no":true,"evenes.no":true,"evenassi.no":true,"xn--eveni-0qa01ga.no":true,"evje-og-hornnes.no":true,"farsund.no":true,"fauske.no":true,"fuossko.no":true,"fuoisku.no":true,"fedje.no":true,"fet.no":true,"finnoy.no":true,"xn--finny-yua.no":true,"fitjar.no":true,"fjaler.no":true,"fjell.no":true,"flakstad.no":true,"flatanger.no":true,"flekkefjord.no":true,"flesberg.no":true,"flora.no":true,"fla.no":true,"xn--fl-zia.no":true,"folldal.no":true,"forsand.no":true,"fosnes.no":true,"frei.no":true,"frogn.no":true,"froland.no":true,"frosta.no":true,"frana.no":true,"xn--frna-woa.no":true,"froya.no":true,"xn--frya-hra.no":true,"fusa.no":true,"fyresdal.no":true,"forde.no":true,"xn--frde-gra.no":true,"gamvik.no":true,"gangaviika.no":true,"xn--ggaviika-8ya47h.no":true,"gaular.no":true,"gausdal.no":true,"gildeskal.no":true,"xn--gildeskl-g0a.no":true,"giske.no":true,"gjemnes.no":true,"gjerdrum.no":true,"gjerstad.no":true,"gjesdal.no":true,"gjovik.no":true,"xn--gjvik-wua.no":true,"gloppen.no":true,"gol.no":true,"gran.no":true,"grane.no":true,"granvin.no":true,"gratangen.no":true,"grimstad.no":true,"grong.no":true,"kraanghke.no":true,"xn--kranghke-b0a.no":true,"grue.no":true,"gulen.no":true,"hadsel.no":true,"halden.no":true,"halsa.no":true,"hamar.no":true,"hamaroy.no":true,"habmer.no":true,"xn--hbmer-xqa.no":true,"hapmir.no":true,"xn--hpmir-xqa.no":true,"hammerfest.no":true,"hammarfeasta.no":true,"xn--hmmrfeasta-s4ac.no":true,"haram.no":true,"hareid.no":true,"harstad.no":true,"hasvik.no":true,"aknoluokta.no":true,"xn--koluokta-7ya57h.no":true,"hattfjelldal.no":true,"aarborte.no":true,"haugesund.no":true,"hemne.no":true,"hemnes.no":true,"hemsedal.no":true,"heroy.more-og-romsdal.no":true,"xn--hery-ira.xn--mre-og-romsdal-qqb.no":true,"heroy.nordland.no":true,"xn--hery-ira.nordland.no":true,"hitra.no":true,"hjartdal.no":true,"hjelmeland.no":true,"hobol.no":true,"xn--hobl-ira.no":true,"hof.no":true,"hol.no":true,"hole.no":true,"holmestrand.no":true,"holtalen.no":true,"xn--holtlen-hxa.no":true,"hornindal.no":true,"horten.no":true,"hurdal.no":true,"hurum.no":true,"hvaler.no":true,"hyllestad.no":true,"hagebostad.no":true,"xn--hgebostad-g3a.no":true,"hoyanger.no":true,"xn--hyanger-q1a.no":true,"hoylandet.no":true,"xn--hylandet-54a.no":true,"ha.no":true,"xn--h-2fa.no":true,"ibestad.no":true,"inderoy.no":true,"xn--indery-fya.no":true,"iveland.no":true,"jevnaker.no":true,"jondal.no":true,"jolster.no":true,"xn--jlster-bya.no":true,"karasjok.no":true,"karasjohka.no":true,"xn--krjohka-hwab49j.no":true,"karlsoy.no":true,"galsa.no":true,"xn--gls-elac.no":true,"karmoy.no":true,"xn--karmy-yua.no":true,"kautokeino.no":true,"guovdageaidnu.no":true,"klepp.no":true,"klabu.no":true,"xn--klbu-woa.no":true,"kongsberg.no":true,"kongsvinger.no":true,"kragero.no":true,"xn--krager-gya.no":true,"kristiansand.no":true,"kristiansund.no":true,"krodsherad.no":true,"xn--krdsherad-m8a.no":true,"kvalsund.no":true,"rahkkeravju.no":true,"xn--rhkkervju-01af.no":true,"kvam.no":true,"kvinesdal.no":true,"kvinnherad.no":true,"kviteseid.no":true,"kvitsoy.no":true,"xn--kvitsy-fya.no":true,"kvafjord.no":true,"xn--kvfjord-nxa.no":true,"giehtavuoatna.no":true,"kvanangen.no":true,"xn--kvnangen-k0a.no":true,"navuotna.no":true,"xn--nvuotna-hwa.no":true,"kafjord.no":true,"xn--kfjord-iua.no":true,"gaivuotna.no":true,"xn--givuotna-8ya.no":true,"larvik.no":true,"lavangen.no":true,"lavagis.no":true,"loabat.no":true,"xn--loabt-0qa.no":true,"lebesby.no":true,"davvesiida.no":true,"leikanger.no":true,"leirfjord.no":true,"leka.no":true,"leksvik.no":true,"lenvik.no":true,"leangaviika.no":true,"xn--leagaviika-52b.no":true,"lesja.no":true,"levanger.no":true,"lier.no":true,"lierne.no":true,"lillehammer.no":true,"lillesand.no":true,"lindesnes.no":true,"lindas.no":true,"xn--linds-pra.no":true,"lom.no":true,"loppa.no":true,"lahppi.no":true,"xn--lhppi-xqa.no":true,"lund.no":true,"lunner.no":true,"luroy.no":true,"xn--lury-ira.no":true,"luster.no":true,"lyngdal.no":true,"lyngen.no":true,"ivgu.no":true,"lardal.no":true,"lerdal.no":true,"xn--lrdal-sra.no":true,"lodingen.no":true,"xn--ldingen-q1a.no":true,"lorenskog.no":true,"xn--lrenskog-54a.no":true,"loten.no":true,"xn--lten-gra.no":true,"malvik.no":true,"masoy.no":true,"xn--msy-ula0h.no":true,"muosat.no":true,"xn--muost-0qa.no":true,"mandal.no":true,"marker.no":true,"marnardal.no":true,"masfjorden.no":true,"meland.no":true,"meldal.no":true,"melhus.no":true,"meloy.no":true,"xn--mely-ira.no":true,"meraker.no":true,"xn--merker-kua.no":true,"moareke.no":true,"xn--moreke-jua.no":true,"midsund.no":true,"midtre-gauldal.no":true,"modalen.no":true,"modum.no":true,"molde.no":true,"moskenes.no":true,"moss.no":true,"mosvik.no":true,"malselv.no":true,"xn--mlselv-iua.no":true,"malatvuopmi.no":true,"xn--mlatvuopmi-s4a.no":true,"namdalseid.no":true,"aejrie.no":true,"namsos.no":true,"namsskogan.no":true,"naamesjevuemie.no":true,"xn--nmesjevuemie-tcba.no":true,"laakesvuemie.no":true,"nannestad.no":true,"narvik.no":true,"narviika.no":true,"naustdal.no":true,"nedre-eiker.no":true,"nes.akershus.no":true,"nes.buskerud.no":true,"nesna.no":true,"nesodden.no":true,"nesseby.no":true,"unjarga.no":true,"xn--unjrga-rta.no":true,"nesset.no":true,"nissedal.no":true,"nittedal.no":true,"nord-aurdal.no":true,"nord-fron.no":true,"nord-odal.no":true,"norddal.no":true,"nordkapp.no":true,"davvenjarga.no":true,"xn--davvenjrga-y4a.no":true,"nordre-land.no":true,"nordreisa.no":true,"raisa.no":true,"xn--risa-5na.no":true,"nore-og-uvdal.no":true,"notodden.no":true,"naroy.no":true,"xn--nry-yla5g.no":true,"notteroy.no":true,"xn--nttery-byae.no":true,"odda.no":true,"oksnes.no":true,"xn--ksnes-uua.no":true,"oppdal.no":true,"oppegard.no":true,"xn--oppegrd-ixa.no":true,"orkdal.no":true,"orland.no":true,"xn--rland-uua.no":true,"orskog.no":true,"xn--rskog-uua.no":true,"orsta.no":true,"xn--rsta-fra.no":true,"os.hedmark.no":true,"os.hordaland.no":true,"osen.no":true,"osteroy.no":true,"xn--ostery-fya.no":true,"ostre-toten.no":true,"xn--stre-toten-zcb.no":true,"overhalla.no":true,"ovre-eiker.no":true,"xn--vre-eiker-k8a.no":true,"oyer.no":true,"xn--yer-zna.no":true,"oygarden.no":true,"xn--ygarden-p1a.no":true,"oystre-slidre.no":true,"xn--ystre-slidre-ujb.no":true,"porsanger.no":true,"porsangu.no":true,"xn--porsgu-sta26f.no":true,"porsgrunn.no":true,"radoy.no":true,"xn--rady-ira.no":true,"rakkestad.no":true,"rana.no":true,"ruovat.no":true,"randaberg.no":true,"rauma.no":true,"rendalen.no":true,"rennebu.no":true,"rennesoy.no":true,"xn--rennesy-v1a.no":true,"rindal.no":true,"ringebu.no":true,"ringerike.no":true,"ringsaker.no":true,"rissa.no":true,"risor.no":true,"xn--risr-ira.no":true,"roan.no":true,"rollag.no":true,"rygge.no":true,"ralingen.no":true,"xn--rlingen-mxa.no":true,"rodoy.no":true,"xn--rdy-0nab.no":true,"romskog.no":true,"xn--rmskog-bya.no":true,"roros.no":true,"xn--rros-gra.no":true,"rost.no":true,"xn--rst-0na.no":true,"royken.no":true,"xn--ryken-vua.no":true,"royrvik.no":true,"xn--ryrvik-bya.no":true,"rade.no":true,"xn--rde-ula.no":true,"salangen.no":true,"siellak.no":true,"saltdal.no":true,"salat.no":true,"xn--slt-elab.no":true,"xn--slat-5na.no":true,"samnanger.no":true,"sande.more-og-romsdal.no":true,"sande.xn--mre-og-romsdal-qqb.no":true,"sande.vestfold.no":true,"sandefjord.no":true,"sandnes.no":true,"sandoy.no":true,"xn--sandy-yua.no":true,"sarpsborg.no":true,"sauda.no":true,"sauherad.no":true,"sel.no":true,"selbu.no":true,"selje.no":true,"seljord.no":true,"sigdal.no":true,"siljan.no":true,"sirdal.no":true,"skaun.no":true,"skedsmo.no":true,"ski.no":true,"skien.no":true,"skiptvet.no":true,"skjervoy.no":true,"xn--skjervy-v1a.no":true,"skierva.no":true,"xn--skierv-uta.no":true,"skjak.no":true,"xn--skjk-soa.no":true,"skodje.no":true,"skanland.no":true,"xn--sknland-fxa.no":true,"skanit.no":true,"xn--sknit-yqa.no":true,"smola.no":true,"xn--smla-hra.no":true,"snillfjord.no":true,"snasa.no":true,"xn--snsa-roa.no":true,"snoasa.no":true,"snaase.no":true,"xn--snase-nra.no":true,"sogndal.no":true,"sokndal.no":true,"sola.no":true,"solund.no":true,"songdalen.no":true,"sortland.no":true,"spydeberg.no":true,"stange.no":true,"stavanger.no":true,"steigen.no":true,"steinkjer.no":true,"stjordal.no":true,"xn--stjrdal-s1a.no":true,"stokke.no":true,"stor-elvdal.no":true,"stord.no":true,"stordal.no":true,"storfjord.no":true,"omasvuotna.no":true,"strand.no":true,"stranda.no":true,"stryn.no":true,"sula.no":true,"suldal.no":true,"sund.no":true,"sunndal.no":true,"surnadal.no":true,"sveio.no":true,"svelvik.no":true,"sykkylven.no":true,"sogne.no":true,"xn--sgne-gra.no":true,"somna.no":true,"xn--smna-gra.no":true,"sondre-land.no":true,"xn--sndre-land-0cb.no":true,"sor-aurdal.no":true,"xn--sr-aurdal-l8a.no":true,"sor-fron.no":true,"xn--sr-fron-q1a.no":true,"sor-odal.no":true,"xn--sr-odal-q1a.no":true,"sor-varanger.no":true,"xn--sr-varanger-ggb.no":true,"matta-varjjat.no":true,"xn--mtta-vrjjat-k7af.no":true,"sorfold.no":true,"xn--srfold-bya.no":true,"sorreisa.no":true,"xn--srreisa-q1a.no":true,"sorum.no":true,"xn--srum-gra.no":true,"tana.no":true,"deatnu.no":true,"time.no":true,"tingvoll.no":true,"tinn.no":true,"tjeldsund.no":true,"dielddanuorri.no":true,"tjome.no":true,"xn--tjme-hra.no":true,"tokke.no":true,"tolga.no":true,"torsken.no":true,"tranoy.no":true,"xn--trany-yua.no":true,"tromso.no":true,"xn--troms-zua.no":true,"tromsa.no":true,"romsa.no":true,"trondheim.no":true,"troandin.no":true,"trysil.no":true,"trana.no":true,"xn--trna-woa.no":true,"trogstad.no":true,"xn--trgstad-r1a.no":true,"tvedestrand.no":true,"tydal.no":true,"tynset.no":true,"tysfjord.no":true,"divtasvuodna.no":true,"divttasvuotna.no":true,"tysnes.no":true,"tysvar.no":true,"xn--tysvr-vra.no":true,"tonsberg.no":true,"xn--tnsberg-q1a.no":true,"ullensaker.no":true,"ullensvang.no":true,"ulvik.no":true,"utsira.no":true,"vadso.no":true,"xn--vads-jra.no":true,"cahcesuolo.no":true,"xn--hcesuolo-7ya35b.no":true,"vaksdal.no":true,"valle.no":true,"vang.no":true,"vanylven.no":true,"vardo.no":true,"xn--vard-jra.no":true,"varggat.no":true,"xn--vrggt-xqad.no":true,"vefsn.no":true,"vaapste.no":true,"vega.no":true,"vegarshei.no":true,"xn--vegrshei-c0a.no":true,"vennesla.no":true,"verdal.no":true,"verran.no":true,"vestby.no":true,"vestnes.no":true,"vestre-slidre.no":true,"vestre-toten.no":true,"vestvagoy.no":true,"xn--vestvgy-ixa6o.no":true,"vevelstad.no":true,"vik.no":true,"vikna.no":true,"vindafjord.no":true,"volda.no":true,"voss.no":true,"varoy.no":true,"xn--vry-yla5g.no":true,"vagan.no":true,"xn--vgan-qoa.no":true,"voagat.no":true,"vagsoy.no":true,"xn--vgsy-qoa0j.no":true,"vaga.no":true,"xn--vg-yiab.no":true,"valer.ostfold.no":true,"xn--vler-qoa.xn--stfold-9xa.no":true,"valer.hedmark.no":true,"xn--vler-qoa.hedmark.no":true,"*.np":true,"nr":true,"biz.nr":true,"info.nr":true,"gov.nr":true,"edu.nr":true,"org.nr":true,"net.nr":true,"com.nr":true,"nu":true,"nz":true,"ac.nz":true,"co.nz":true,"cri.nz":true,"geek.nz":true,"gen.nz":true,"govt.nz":true,"health.nz":true,"iwi.nz":true,"kiwi.nz":true,"maori.nz":true,"mil.nz":true,"xn--mori-qsa.nz":true,"net.nz":true,"org.nz":true,"parliament.nz":true,"school.nz":true,"om":true,"co.om":true,"com.om":true,"edu.om":true,"gov.om":true,"med.om":true,"museum.om":true,"net.om":true,"org.om":true,"pro.om":true,"org":true,"pa":true,"ac.pa":true,"gob.pa":true,"com.pa":true,"org.pa":true,"sld.pa":true,"edu.pa":true,"net.pa":true,"ing.pa":true,"abo.pa":true,"med.pa":true,"nom.pa":true,"pe":true,"edu.pe":true,"gob.pe":true,"nom.pe":true,"mil.pe":true,"org.pe":true,"com.pe":true,"net.pe":true,"pf":true,"com.pf":true,"org.pf":true,"edu.pf":true,"*.pg":true,"ph":true,"com.ph":true,"net.ph":true,"org.ph":true,"gov.ph":true,"edu.ph":true,"ngo.ph":true,"mil.ph":true,"i.ph":true,"pk":true,"com.pk":true,"net.pk":true,"edu.pk":true,"org.pk":true,"fam.pk":true,"biz.pk":true,"web.pk":true,"gov.pk":true,"gob.pk":true,"gok.pk":true,"gon.pk":true,"gop.pk":true,"gos.pk":true,"info.pk":true,"pl":true,"com.pl":true,"net.pl":true,"org.pl":true,"aid.pl":true,"agro.pl":true,"atm.pl":true,"auto.pl":true,"biz.pl":true,"edu.pl":true,"gmina.pl":true,"gsm.pl":true,"info.pl":true,"mail.pl":true,"miasta.pl":true,"media.pl":true,"mil.pl":true,"nieruchomosci.pl":true,"nom.pl":true,"pc.pl":true,"powiat.pl":true,"priv.pl":true,"realestate.pl":true,"rel.pl":true,"sex.pl":true,"shop.pl":true,"sklep.pl":true,"sos.pl":true,"szkola.pl":true,"targi.pl":true,"tm.pl":true,"tourism.pl":true,"travel.pl":true,"turystyka.pl":true,"gov.pl":true,"ap.gov.pl":true,"ic.gov.pl":true,"is.gov.pl":true,"us.gov.pl":true,"kmpsp.gov.pl":true,"kppsp.gov.pl":true,"kwpsp.gov.pl":true,"psp.gov.pl":true,"wskr.gov.pl":true,"kwp.gov.pl":true,"mw.gov.pl":true,"ug.gov.pl":true,"um.gov.pl":true,"umig.gov.pl":true,"ugim.gov.pl":true,"upow.gov.pl":true,"uw.gov.pl":true,"starostwo.gov.pl":true,"pa.gov.pl":true,"po.gov.pl":true,"psse.gov.pl":true,"pup.gov.pl":true,"rzgw.gov.pl":true,"sa.gov.pl":true,"so.gov.pl":true,"sr.gov.pl":true,"wsa.gov.pl":true,"sko.gov.pl":true,"uzs.gov.pl":true,"wiih.gov.pl":true,"winb.gov.pl":true,"pinb.gov.pl":true,"wios.gov.pl":true,"witd.gov.pl":true,"wzmiuw.gov.pl":true,"piw.gov.pl":true,"wiw.gov.pl":true,"griw.gov.pl":true,"wif.gov.pl":true,"oum.gov.pl":true,"sdn.gov.pl":true,"zp.gov.pl":true,"uppo.gov.pl":true,"mup.gov.pl":true,"wuoz.gov.pl":true,"konsulat.gov.pl":true,"oirm.gov.pl":true,"augustow.pl":true,"babia-gora.pl":true,"bedzin.pl":true,"beskidy.pl":true,"bialowieza.pl":true,"bialystok.pl":true,"bielawa.pl":true,"bieszczady.pl":true,"boleslawiec.pl":true,"bydgoszcz.pl":true,"bytom.pl":true,"cieszyn.pl":true,"czeladz.pl":true,"czest.pl":true,"dlugoleka.pl":true,"elblag.pl":true,"elk.pl":true,"glogow.pl":true,"gniezno.pl":true,"gorlice.pl":true,"grajewo.pl":true,"ilawa.pl":true,"jaworzno.pl":true,"jelenia-gora.pl":true,"jgora.pl":true,"kalisz.pl":true,"kazimierz-dolny.pl":true,"karpacz.pl":true,"kartuzy.pl":true,"kaszuby.pl":true,"katowice.pl":true,"kepno.pl":true,"ketrzyn.pl":true,"klodzko.pl":true,"kobierzyce.pl":true,"kolobrzeg.pl":true,"konin.pl":true,"konskowola.pl":true,"kutno.pl":true,"lapy.pl":true,"lebork.pl":true,"legnica.pl":true,"lezajsk.pl":true,"limanowa.pl":true,"lomza.pl":true,"lowicz.pl":true,"lubin.pl":true,"lukow.pl":true,"malbork.pl":true,"malopolska.pl":true,"mazowsze.pl":true,"mazury.pl":true,"mielec.pl":true,"mielno.pl":true,"mragowo.pl":true,"naklo.pl":true,"nowaruda.pl":true,"nysa.pl":true,"olawa.pl":true,"olecko.pl":true,"olkusz.pl":true,"olsztyn.pl":true,"opoczno.pl":true,"opole.pl":true,"ostroda.pl":true,"ostroleka.pl":true,"ostrowiec.pl":true,"ostrowwlkp.pl":true,"pila.pl":true,"pisz.pl":true,"podhale.pl":true,"podlasie.pl":true,"polkowice.pl":true,"pomorze.pl":true,"pomorskie.pl":true,"prochowice.pl":true,"pruszkow.pl":true,"przeworsk.pl":true,"pulawy.pl":true,"radom.pl":true,"rawa-maz.pl":true,"rybnik.pl":true,"rzeszow.pl":true,"sanok.pl":true,"sejny.pl":true,"slask.pl":true,"slupsk.pl":true,"sosnowiec.pl":true,"stalowa-wola.pl":true,"skoczow.pl":true,"starachowice.pl":true,"stargard.pl":true,"suwalki.pl":true,"swidnica.pl":true,"swiebodzin.pl":true,"swinoujscie.pl":true,"szczecin.pl":true,"szczytno.pl":true,"tarnobrzeg.pl":true,"tgory.pl":true,"turek.pl":true,"tychy.pl":true,"ustka.pl":true,"walbrzych.pl":true,"warmia.pl":true,"warszawa.pl":true,"waw.pl":true,"wegrow.pl":true,"wielun.pl":true,"wlocl.pl":true,"wloclawek.pl":true,"wodzislaw.pl":true,"wolomin.pl":true,"wroclaw.pl":true,"zachpomor.pl":true,"zagan.pl":true,"zarow.pl":true,"zgora.pl":true,"zgorzelec.pl":true,"pm":true,"pn":true,"gov.pn":true,"co.pn":true,"org.pn":true,"edu.pn":true,"net.pn":true,"post":true,"pr":true,"com.pr":true,"net.pr":true,"org.pr":true,"gov.pr":true,"edu.pr":true,"isla.pr":true,"pro.pr":true,"biz.pr":true,"info.pr":true,"name.pr":true,"est.pr":true,"prof.pr":true,"ac.pr":true,"pro":true,"aca.pro":true,"bar.pro":true,"cpa.pro":true,"jur.pro":true,"law.pro":true,"med.pro":true,"eng.pro":true,"ps":true,"edu.ps":true,"gov.ps":true,"sec.ps":true,"plo.ps":true,"com.ps":true,"org.ps":true,"net.ps":true,"pt":true,"net.pt":true,"gov.pt":true,"org.pt":true,"edu.pt":true,"int.pt":true,"publ.pt":true,"com.pt":true,"nome.pt":true,"pw":true,"co.pw":true,"ne.pw":true,"or.pw":true,"ed.pw":true,"go.pw":true,"belau.pw":true,"py":true,"com.py":true,"coop.py":true,"edu.py":true,"gov.py":true,"mil.py":true,"net.py":true,"org.py":true,"qa":true,"com.qa":true,"edu.qa":true,"gov.qa":true,"mil.qa":true,"name.qa":true,"net.qa":true,"org.qa":true,"sch.qa":true,"re":true,"com.re":true,"asso.re":true,"nom.re":true,"ro":true,"com.ro":true,"org.ro":true,"tm.ro":true,"nt.ro":true,"nom.ro":true,"info.ro":true,"rec.ro":true,"arts.ro":true,"firm.ro":true,"store.ro":true,"www.ro":true,"rs":true,"co.rs":true,"org.rs":true,"edu.rs":true,"ac.rs":true,"gov.rs":true,"in.rs":true,"ru":true,"ac.ru":true,"com.ru":true,"edu.ru":true,"int.ru":true,"net.ru":true,"org.ru":true,"pp.ru":true,"adygeya.ru":true,"altai.ru":true,"amur.ru":true,"arkhangelsk.ru":true,"astrakhan.ru":true,"bashkiria.ru":true,"belgorod.ru":true,"bir.ru":true,"bryansk.ru":true,"buryatia.ru":true,"cbg.ru":true,"chel.ru":true,"chelyabinsk.ru":true,"chita.ru":true,"chukotka.ru":true,"chuvashia.ru":true,"dagestan.ru":true,"dudinka.ru":true,"e-burg.ru":true,"grozny.ru":true,"irkutsk.ru":true,"ivanovo.ru":true,"izhevsk.ru":true,"jar.ru":true,"joshkar-ola.ru":true,"kalmykia.ru":true,"kaluga.ru":true,"kamchatka.ru":true,"karelia.ru":true,"kazan.ru":true,"kchr.ru":true,"kemerovo.ru":true,"khabarovsk.ru":true,"khakassia.ru":true,"khv.ru":true,"kirov.ru":true,"koenig.ru":true,"komi.ru":true,"kostroma.ru":true,"krasnoyarsk.ru":true,"kuban.ru":true,"kurgan.ru":true,"kursk.ru":true,"lipetsk.ru":true,"magadan.ru":true,"mari.ru":true,"mari-el.ru":true,"marine.ru":true,"mordovia.ru":true,"msk.ru":true,"murmansk.ru":true,"nalchik.ru":true,"nnov.ru":true,"nov.ru":true,"novosibirsk.ru":true,"nsk.ru":true,"omsk.ru":true,"orenburg.ru":true,"oryol.ru":true,"palana.ru":true,"penza.ru":true,"perm.ru":true,"ptz.ru":true,"rnd.ru":true,"ryazan.ru":true,"sakhalin.ru":true,"samara.ru":true,"saratov.ru":true,"simbirsk.ru":true,"smolensk.ru":true,"spb.ru":true,"stavropol.ru":true,"stv.ru":true,"surgut.ru":true,"tambov.ru":true,"tatarstan.ru":true,"tom.ru":true,"tomsk.ru":true,"tsaritsyn.ru":true,"tsk.ru":true,"tula.ru":true,"tuva.ru":true,"tver.ru":true,"tyumen.ru":true,"udm.ru":true,"udmurtia.ru":true,"ulan-ude.ru":true,"vladikavkaz.ru":true,"vladimir.ru":true,"vladivostok.ru":true,"volgograd.ru":true,"vologda.ru":true,"voronezh.ru":true,"vrn.ru":true,"vyatka.ru":true,"yakutia.ru":true,"yamal.ru":true,"yaroslavl.ru":true,"yekaterinburg.ru":true,"yuzhno-sakhalinsk.ru":true,"amursk.ru":true,"baikal.ru":true,"cmw.ru":true,"fareast.ru":true,"jamal.ru":true,"kms.ru":true,"k-uralsk.ru":true,"kustanai.ru":true,"kuzbass.ru":true,"magnitka.ru":true,"mytis.ru":true,"nakhodka.ru":true,"nkz.ru":true,"norilsk.ru":true,"oskol.ru":true,"pyatigorsk.ru":true,"rubtsovsk.ru":true,"snz.ru":true,"syzran.ru":true,"vdonsk.ru":true,"zgrad.ru":true,"gov.ru":true,"mil.ru":true,"test.ru":true,"rw":true,"gov.rw":true,"net.rw":true,"edu.rw":true,"ac.rw":true,"com.rw":true,"co.rw":true,"int.rw":true,"mil.rw":true,"gouv.rw":true,"sa":true,"com.sa":true,"net.sa":true,"org.sa":true,"gov.sa":true,"med.sa":true,"pub.sa":true,"edu.sa":true,"sch.sa":true,"sb":true,"com.sb":true,"edu.sb":true,"gov.sb":true,"net.sb":true,"org.sb":true,"sc":true,"com.sc":true,"gov.sc":true,"net.sc":true,"org.sc":true,"edu.sc":true,"sd":true,"com.sd":true,"net.sd":true,"org.sd":true,"edu.sd":true,"med.sd":true,"tv.sd":true,"gov.sd":true,"info.sd":true,"se":true,"a.se":true,"ac.se":true,"b.se":true,"bd.se":true,"brand.se":true,"c.se":true,"d.se":true,"e.se":true,"f.se":true,"fh.se":true,"fhsk.se":true,"fhv.se":true,"g.se":true,"h.se":true,"i.se":true,"k.se":true,"komforb.se":true,"kommunalforbund.se":true,"komvux.se":true,"l.se":true,"lanbib.se":true,"m.se":true,"n.se":true,"naturbruksgymn.se":true,"o.se":true,"org.se":true,"p.se":true,"parti.se":true,"pp.se":true,"press.se":true,"r.se":true,"s.se":true,"t.se":true,"tm.se":true,"u.se":true,"w.se":true,"x.se":true,"y.se":true,"z.se":true,"sg":true,"com.sg":true,"net.sg":true,"org.sg":true,"gov.sg":true,"edu.sg":true,"per.sg":true,"sh":true,"com.sh":true,"net.sh":true,"gov.sh":true,"org.sh":true,"mil.sh":true,"si":true,"sj":true,"sk":true,"sl":true,"com.sl":true,"net.sl":true,"edu.sl":true,"gov.sl":true,"org.sl":true,"sm":true,"sn":true,"art.sn":true,"com.sn":true,"edu.sn":true,"gouv.sn":true,"org.sn":true,"perso.sn":true,"univ.sn":true,"so":true,"com.so":true,"net.so":true,"org.so":true,"sr":true,"st":true,"co.st":true,"com.st":true,"consulado.st":true,"edu.st":true,"embaixada.st":true,"gov.st":true,"mil.st":true,"net.st":true,"org.st":true,"principe.st":true,"saotome.st":true,"store.st":true,"su":true,"adygeya.su":true,"arkhangelsk.su":true,"balashov.su":true,"bashkiria.su":true,"bryansk.su":true,"dagestan.su":true,"grozny.su":true,"ivanovo.su":true,"kalmykia.su":true,"kaluga.su":true,"karelia.su":true,"khakassia.su":true,"krasnodar.su":true,"kurgan.su":true,"lenug.su":true,"mordovia.su":true,"msk.su":true,"murmansk.su":true,"nalchik.su":true,"nov.su":true,"obninsk.su":true,"penza.su":true,"pokrovsk.su":true,"sochi.su":true,"spb.su":true,"togliatti.su":true,"troitsk.su":true,"tula.su":true,"tuva.su":true,"vladikavkaz.su":true,"vladimir.su":true,"vologda.su":true,"sv":true,"com.sv":true,"edu.sv":true,"gob.sv":true,"org.sv":true,"red.sv":true,"sx":true,"gov.sx":true,"sy":true,"edu.sy":true,"gov.sy":true,"net.sy":true,"mil.sy":true,"com.sy":true,"org.sy":true,"sz":true,"co.sz":true,"ac.sz":true,"org.sz":true,"tc":true,"td":true,"tel":true,"tf":true,"tg":true,"th":true,"ac.th":true,"co.th":true,"go.th":true,"in.th":true,"mi.th":true,"net.th":true,"or.th":true,"tj":true,"ac.tj":true,"biz.tj":true,"co.tj":true,"com.tj":true,"edu.tj":true,"go.tj":true,"gov.tj":true,"int.tj":true,"mil.tj":true,"name.tj":true,"net.tj":true,"nic.tj":true,"org.tj":true,"test.tj":true,"web.tj":true,"tk":true,"tl":true,"gov.tl":true,"tm":true,"com.tm":true,"co.tm":true,"org.tm":true,"net.tm":true,"nom.tm":true,"gov.tm":true,"mil.tm":true,"edu.tm":true,"tn":true,"com.tn":true,"ens.tn":true,"fin.tn":true,"gov.tn":true,"ind.tn":true,"intl.tn":true,"nat.tn":true,"net.tn":true,"org.tn":true,"info.tn":true,"perso.tn":true,"tourism.tn":true,"edunet.tn":true,"rnrt.tn":true,"rns.tn":true,"rnu.tn":true,"mincom.tn":true,"agrinet.tn":true,"defense.tn":true,"turen.tn":true,"to":true,"com.to":true,"gov.to":true,"net.to":true,"org.to":true,"edu.to":true,"mil.to":true,"tp":true,"tr":true,"com.tr":true,"info.tr":true,"biz.tr":true,"net.tr":true,"org.tr":true,"web.tr":true,"gen.tr":true,"tv.tr":true,"av.tr":true,"dr.tr":true,"bbs.tr":true,"name.tr":true,"tel.tr":true,"gov.tr":true,"bel.tr":true,"pol.tr":true,"mil.tr":true,"k12.tr":true,"edu.tr":true,"kep.tr":true,"nc.tr":true,"gov.nc.tr":true,"travel":true,"tt":true,"co.tt":true,"com.tt":true,"org.tt":true,"net.tt":true,"biz.tt":true,"info.tt":true,"pro.tt":true,"int.tt":true,"coop.tt":true,"jobs.tt":true,"mobi.tt":true,"travel.tt":true,"museum.tt":true,"aero.tt":true,"name.tt":true,"gov.tt":true,"edu.tt":true,"tv":true,"tw":true,"edu.tw":true,"gov.tw":true,"mil.tw":true,"com.tw":true,"net.tw":true,"org.tw":true,"idv.tw":true,"game.tw":true,"ebiz.tw":true,"club.tw":true,"xn--zf0ao64a.tw":true,"xn--uc0atv.tw":true,"xn--czrw28b.tw":true,"tz":true,"ac.tz":true,"co.tz":true,"go.tz":true,"hotel.tz":true,"info.tz":true,"me.tz":true,"mil.tz":true,"mobi.tz":true,"ne.tz":true,"or.tz":true,"sc.tz":true,"tv.tz":true,"ua":true,"com.ua":true,"edu.ua":true,"gov.ua":true,"in.ua":true,"net.ua":true,"org.ua":true,"cherkassy.ua":true,"cherkasy.ua":true,"chernigov.ua":true,"chernihiv.ua":true,"chernivtsi.ua":true,"chernovtsy.ua":true,"ck.ua":true,"cn.ua":true,"cr.ua":true,"crimea.ua":true,"cv.ua":true,"dn.ua":true,"dnepropetrovsk.ua":true,"dnipropetrovsk.ua":true,"dominic.ua":true,"donetsk.ua":true,"dp.ua":true,"if.ua":true,"ivano-frankivsk.ua":true,"kh.ua":true,"kharkiv.ua":true,"kharkov.ua":true,"kherson.ua":true,"khmelnitskiy.ua":true,"khmelnytskyi.ua":true,"kiev.ua":true,"kirovograd.ua":true,"km.ua":true,"kr.ua":true,"krym.ua":true,"ks.ua":true,"kv.ua":true,"kyiv.ua":true,"lg.ua":true,"lt.ua":true,"lugansk.ua":true,"lutsk.ua":true,"lv.ua":true,"lviv.ua":true,"mk.ua":true,"mykolaiv.ua":true,"nikolaev.ua":true,"od.ua":true,"odesa.ua":true,"odessa.ua":true,"pl.ua":true,"poltava.ua":true,"rivne.ua":true,"rovno.ua":true,"rv.ua":true,"sb.ua":true,"sebastopol.ua":true,"sevastopol.ua":true,"sm.ua":true,"sumy.ua":true,"te.ua":true,"ternopil.ua":true,"uz.ua":true,"uzhgorod.ua":true,"vinnica.ua":true,"vinnytsia.ua":true,"vn.ua":true,"volyn.ua":true,"yalta.ua":true,"zaporizhzhe.ua":true,"zaporizhzhia.ua":true,"zhitomir.ua":true,"zhytomyr.ua":true,"zp.ua":true,"zt.ua":true,"ug":true,"co.ug":true,"or.ug":true,"ac.ug":true,"sc.ug":true,"go.ug":true,"ne.ug":true,"com.ug":true,"org.ug":true,"uk":true,"ac.uk":true,"co.uk":true,"gov.uk":true,"ltd.uk":true,"me.uk":true,"net.uk":true,"nhs.uk":true,"org.uk":true,"plc.uk":true,"police.uk":true,"*.sch.uk":true,"us":true,"dni.us":true,"fed.us":true,"isa.us":true,"kids.us":true,"nsn.us":true,"ak.us":true,"al.us":true,"ar.us":true,"as.us":true,"az.us":true,"ca.us":true,"co.us":true,"ct.us":true,"dc.us":true,"de.us":true,"fl.us":true,"ga.us":true,"gu.us":true,"hi.us":true,"ia.us":true,"id.us":true,"il.us":true,"in.us":true,"ks.us":true,"ky.us":true,"la.us":true,"ma.us":true,"md.us":true,"me.us":true,"mi.us":true,"mn.us":true,"mo.us":true,"ms.us":true,"mt.us":true,"nc.us":true,"nd.us":true,"ne.us":true,"nh.us":true,"nj.us":true,"nm.us":true,"nv.us":true,"ny.us":true,"oh.us":true,"ok.us":true,"or.us":true,"pa.us":true,"pr.us":true,"ri.us":true,"sc.us":true,"sd.us":true,"tn.us":true,"tx.us":true,"ut.us":true,"vi.us":true,"vt.us":true,"va.us":true,"wa.us":true,"wi.us":true,"wv.us":true,"wy.us":true,"k12.ak.us":true,"k12.al.us":true,"k12.ar.us":true,"k12.as.us":true,"k12.az.us":true,"k12.ca.us":true,"k12.co.us":true,"k12.ct.us":true,"k12.dc.us":true,"k12.de.us":true,"k12.fl.us":true,"k12.ga.us":true,"k12.gu.us":true,"k12.ia.us":true,"k12.id.us":true,"k12.il.us":true,"k12.in.us":true,"k12.ks.us":true,"k12.ky.us":true,"k12.la.us":true,"k12.ma.us":true,"k12.md.us":true,"k12.me.us":true,"k12.mi.us":true,"k12.mn.us":true,"k12.mo.us":true,"k12.ms.us":true,"k12.mt.us":true,"k12.nc.us":true,"k12.ne.us":true,"k12.nh.us":true,"k12.nj.us":true,"k12.nm.us":true,"k12.nv.us":true,"k12.ny.us":true,"k12.oh.us":true,"k12.ok.us":true,"k12.or.us":true,"k12.pa.us":true,"k12.pr.us":true,"k12.ri.us":true,"k12.sc.us":true,"k12.tn.us":true,"k12.tx.us":true,"k12.ut.us":true,"k12.vi.us":true,"k12.vt.us":true,"k12.va.us":true,"k12.wa.us":true,"k12.wi.us":true,"k12.wy.us":true,"cc.ak.us":true,"cc.al.us":true,"cc.ar.us":true,"cc.as.us":true,"cc.az.us":true,"cc.ca.us":true,"cc.co.us":true,"cc.ct.us":true,"cc.dc.us":true,"cc.de.us":true,"cc.fl.us":true,"cc.ga.us":true,"cc.gu.us":true,"cc.hi.us":true,"cc.ia.us":true,"cc.id.us":true,"cc.il.us":true,"cc.in.us":true,"cc.ks.us":true,"cc.ky.us":true,"cc.la.us":true,"cc.ma.us":true,"cc.md.us":true,"cc.me.us":true,"cc.mi.us":true,"cc.mn.us":true,"cc.mo.us":true,"cc.ms.us":true,"cc.mt.us":true,"cc.nc.us":true,"cc.nd.us":true,"cc.ne.us":true,"cc.nh.us":true,"cc.nj.us":true,"cc.nm.us":true,"cc.nv.us":true,"cc.ny.us":true,"cc.oh.us":true,"cc.ok.us":true,"cc.or.us":true,"cc.pa.us":true,"cc.pr.us":true,"cc.ri.us":true,"cc.sc.us":true,"cc.sd.us":true,"cc.tn.us":true,"cc.tx.us":true,"cc.ut.us":true,"cc.vi.us":true,"cc.vt.us":true,"cc.va.us":true,"cc.wa.us":true,"cc.wi.us":true,"cc.wv.us":true,"cc.wy.us":true,"lib.ak.us":true,"lib.al.us":true,"lib.ar.us":true,"lib.as.us":true,"lib.az.us":true,"lib.ca.us":true,"lib.co.us":true,"lib.ct.us":true,"lib.dc.us":true,"lib.de.us":true,"lib.fl.us":true,"lib.ga.us":true,"lib.gu.us":true,"lib.hi.us":true,"lib.ia.us":true,"lib.id.us":true,"lib.il.us":true,"lib.in.us":true,"lib.ks.us":true,"lib.ky.us":true,"lib.la.us":true,"lib.ma.us":true,"lib.md.us":true,"lib.me.us":true,"lib.mi.us":true,"lib.mn.us":true,"lib.mo.us":true,"lib.ms.us":true,"lib.mt.us":true,"lib.nc.us":true,"lib.nd.us":true,"lib.ne.us":true,"lib.nh.us":true,"lib.nj.us":true,"lib.nm.us":true,"lib.nv.us":true,"lib.ny.us":true,"lib.oh.us":true,"lib.ok.us":true,"lib.or.us":true,"lib.pa.us":true,"lib.pr.us":true,"lib.ri.us":true,"lib.sc.us":true,"lib.sd.us":true,"lib.tn.us":true,"lib.tx.us":true,"lib.ut.us":true,"lib.vi.us":true,"lib.vt.us":true,"lib.va.us":true,"lib.wa.us":true,"lib.wi.us":true,"lib.wy.us":true,"pvt.k12.ma.us":true,"chtr.k12.ma.us":true,"paroch.k12.ma.us":true,"uy":true,"com.uy":true,"edu.uy":true,"gub.uy":true,"mil.uy":true,"net.uy":true,"org.uy":true,"uz":true,"co.uz":true,"com.uz":true,"net.uz":true,"org.uz":true,"va":true,"vc":true,"com.vc":true,"net.vc":true,"org.vc":true,"gov.vc":true,"mil.vc":true,"edu.vc":true,"ve":true,"arts.ve":true,"co.ve":true,"com.ve":true,"e12.ve":true,"edu.ve":true,"firm.ve":true,"gob.ve":true,"gov.ve":true,"info.ve":true,"int.ve":true,"mil.ve":true,"net.ve":true,"org.ve":true,"rec.ve":true,"store.ve":true,"tec.ve":true,"web.ve":true,"vg":true,"vi":true,"co.vi":true,"com.vi":true,"k12.vi":true,"net.vi":true,"org.vi":true,"vn":true,"com.vn":true,"net.vn":true,"org.vn":true,"edu.vn":true,"gov.vn":true,"int.vn":true,"ac.vn":true,"biz.vn":true,"info.vn":true,"name.vn":true,"pro.vn":true,"health.vn":true,"vu":true,"com.vu":true,"edu.vu":true,"net.vu":true,"org.vu":true,"wf":true,"ws":true,"com.ws":true,"net.ws":true,"org.ws":true,"gov.ws":true,"edu.ws":true,"yt":true,"xn--mgbaam7a8h":true,"xn--y9a3aq":true,"xn--54b7fta0cc":true,"xn--90ais":true,"xn--fiqs8s":true,"xn--fiqz9s":true,"xn--lgbbat1ad8j":true,"xn--wgbh1c":true,"xn--node":true,"xn--qxam":true,"xn--j6w193g":true,"xn--h2brj9c":true,"xn--mgbbh1a71e":true,"xn--fpcrj9c3d":true,"xn--gecrj9c":true,"xn--s9brj9c":true,"xn--45brj9c":true,"xn--xkc2dl3a5ee0h":true,"xn--mgba3a4f16a":true,"xn--mgba3a4fra":true,"xn--mgbtx2b":true,"xn--mgbayh7gpa":true,"xn--3e0b707e":true,"xn--80ao21a":true,"xn--fzc2c9e2c":true,"xn--xkc2al3hye2a":true,"xn--mgbc0a9azcg":true,"xn--d1alf":true,"xn--l1acc":true,"xn--mix891f":true,"xn--mix082f":true,"xn--mgbx4cd0ab":true,"xn--mgb9awbf":true,"xn--mgbai9azgqp6j":true,"xn--mgbai9a5eva00b":true,"xn--ygbi2ammx":true,"xn--90a3ac":true,"xn--o1ac.xn--90a3ac":true,"xn--c1avg.xn--90a3ac":true,"xn--90azh.xn--90a3ac":true,"xn--d1at.xn--90a3ac":true,"xn--o1ach.xn--90a3ac":true,"xn--80au.xn--90a3ac":true,"xn--p1ai":true,"xn--wgbl6a":true,"xn--mgberp4a5d4ar":true,"xn--mgberp4a5d4a87g":true,"xn--mgbqly7c0a67fbc":true,"xn--mgbqly7cvafr":true,"xn--mgbpl2fh":true,"xn--yfro4i67o":true,"xn--clchc0ea0b2g2a9gcd":true,"xn--ogbpf8fl":true,"xn--mgbtf8fl":true,"xn--o3cw4h":true,"xn--pgbs0dh":true,"xn--kpry57d":true,"xn--kprw13d":true,"xn--nnx388a":true,"xn--j1amh":true,"xn--mgb2ddes":true,"xxx":true,"*.ye":true,"ac.za":true,"agrica.za":true,"alt.za":true,"co.za":true,"edu.za":true,"gov.za":true,"grondar.za":true,"law.za":true,"mil.za":true,"net.za":true,"ngo.za":true,"nis.za":true,"nom.za":true,"org.za":true,"school.za":true,"tm.za":true,"web.za":true,"*.zm":true,"*.zw":true,"aaa":true,"aarp":true,"abarth":true,"abb":true,"abbott":true,"abbvie":true,"abc":true,"able":true,"abogado":true,"abudhabi":true,"academy":true,"accenture":true,"accountant":true,"accountants":true,"aco":true,"active":true,"actor":true,"adac":true,"ads":true,"adult":true,"aeg":true,"aetna":true,"afamilycompany":true,"afl":true,"africa":true,"africamagic":true,"agakhan":true,"agency":true,"aig":true,"aigo":true,"airbus":true,"airforce":true,"airtel":true,"akdn":true,"alfaromeo":true,"alibaba":true,"alipay":true,"allfinanz":true,"allstate":true,"ally":true,"alsace":true,"alstom":true,"americanexpress":true,"americanfamily":true,"amex":true,"amfam":true,"amica":true,"amsterdam":true,"analytics":true,"android":true,"anquan":true,"anz":true,"aol":true,"apartments":true,"app":true,"apple":true,"aquarelle":true,"aramco":true,"archi":true,"army":true,"arte":true,"asda":true,"associates":true,"athleta":true,"attorney":true,"auction":true,"audi":true,"audible":true,"audio":true,"auspost":true,"author":true,"auto":true,"autos":true,"avianca":true,"aws":true,"axa":true,"azure":true,"baby":true,"baidu":true,"banamex":true,"bananarepublic":true,"band":true,"bank":true,"bar":true,"barcelona":true,"barclaycard":true,"barclays":true,"barefoot":true,"bargains":true,"basketball":true,"bauhaus":true,"bayern":true,"bbc":true,"bbt":true,"bbva":true,"bcg":true,"bcn":true,"beats":true,"beer":true,"bentley":true,"berlin":true,"best":true,"bestbuy":true,"bet":true,"bharti":true,"bible":true,"bid":true,"bike":true,"bing":true,"bingo":true,"bio":true,"black":true,"blackfriday":true,"blanco":true,"blockbuster":true,"blog":true,"bloomberg":true,"blue":true,"bms":true,"bmw":true,"bnl":true,"bnpparibas":true,"boats":true,"boehringer":true,"bofa":true,"bom":true,"bond":true,"boo":true,"book":true,"booking":true,"boots":true,"bosch":true,"bostik":true,"bot":true,"boutique":true,"bradesco":true,"bridgestone":true,"broadway":true,"broker":true,"brother":true,"brussels":true,"budapest":true,"bugatti":true,"build":true,"builders":true,"business":true,"buy":true,"buzz":true,"bzh":true,"cab":true,"cafe":true,"cal":true,"call":true,"calvinklein":true,"camera":true,"camp":true,"cancerresearch":true,"canon":true,"capetown":true,"capital":true,"capitalone":true,"car":true,"caravan":true,"cards":true,"care":true,"career":true,"careers":true,"cars":true,"cartier":true,"casa":true,"case":true,"caseih":true,"cash":true,"casino":true,"catering":true,"cba":true,"cbn":true,"cbre":true,"cbs":true,"ceb":true,"center":true,"ceo":true,"cern":true,"cfa":true,"cfd":true,"chanel":true,"channel":true,"chase":true,"chat":true,"cheap":true,"chintai":true,"chloe":true,"christmas":true,"chrome":true,"chrysler":true,"church":true,"cipriani":true,"circle":true,"cisco":true,"citadel":true,"citi":true,"citic":true,"city":true,"cityeats":true,"claims":true,"cleaning":true,"click":true,"clinic":true,"clothing":true,"cloud":true,"club":true,"clubmed":true,"coach":true,"codes":true,"coffee":true,"college":true,"cologne":true,"comcast":true,"commbank":true,"community":true,"company":true,"computer":true,"comsec":true,"condos":true,"construction":true,"consulting":true,"contact":true,"contractors":true,"cooking":true,"cookingchannel":true,"cool":true,"corsica":true,"country":true,"coupon":true,"coupons":true,"courses":true,"credit":true,"creditcard":true,"creditunion":true,"cricket":true,"crown":true,"crs":true,"cruises":true,"csc":true,"cuisinella":true,"cymru":true,"cyou":true,"dabur":true,"dad":true,"dance":true,"date":true,"dating":true,"datsun":true,"day":true,"dclk":true,"dds":true,"deal":true,"dealer":true,"deals":true,"degree":true,"delivery":true,"dell":true,"deloitte":true,"delta":true,"democrat":true,"dental":true,"dentist":true,"desi":true,"design":true,"dev":true,"dhl":true,"diamonds":true,"diet":true,"digital":true,"direct":true,"directory":true,"discount":true,"discover":true,"dish":true,"dnp":true,"docs":true,"dodge":true,"dog":true,"doha":true,"domains":true,"doosan":true,"dot":true,"download":true,"drive":true,"dstv":true,"dtv":true,"dubai":true,"duck":true,"dunlop":true,"duns":true,"dupont":true,"durban":true,"dvag":true,"dwg":true,"earth":true,"eat":true,"edeka":true,"education":true,"email":true,"emerck":true,"emerson":true,"energy":true,"engineer":true,"engineering":true,"enterprises":true,"epost":true,"epson":true,"equipment":true,"ericsson":true,"erni":true,"esq":true,"estate":true,"esurance":true,"etisalat":true,"eurovision":true,"eus":true,"events":true,"everbank":true,"exchange":true,"expert":true,"exposed":true,"express":true,"extraspace":true,"fage":true,"fail":true,"fairwinds":true,"faith":true,"family":true,"fan":true,"fans":true,"farm":true,"farmers":true,"fashion":true,"fast":true,"fedex":true,"feedback":true,"ferrari":true,"ferrero":true,"fiat":true,"fidelity":true,"fido":true,"film":true,"final":true,"finance":true,"financial":true,"fire":true,"firestone":true,"firmdale":true,"fish":true,"fishing":true,"fit":true,"fitness":true,"flickr":true,"flights":true,"flir":true,"florist":true,"flowers":true,"flsmidth":true,"fly":true,"foo":true,"foodnetwork":true,"football":true,"ford":true,"forex":true,"forsale":true,"forum":true,"foundation":true,"fox":true,"fresenius":true,"frl":true,"frogans":true,"frontdoor":true,"frontier":true,"ftr":true,"fujitsu":true,"fujixerox":true,"fund":true,"furniture":true,"futbol":true,"fyi":true,"gal":true,"gallery":true,"gallo":true,"gallup":true,"game":true,"games":true,"gap":true,"garden":true,"gbiz":true,"gdn":true,"gea":true,"gent":true,"genting":true,"george":true,"ggee":true,"gift":true,"gifts":true,"gives":true,"giving":true,"glade":true,"glass":true,"gle":true,"global":true,"globo":true,"gmail":true,"gmo":true,"gmx":true,"godaddy":true,"gold":true,"goldpoint":true,"golf":true,"goo":true,"goodhands":true,"goodyear":true,"goog":true,"google":true,"gop":true,"got":true,"gotv":true,"grainger":true,"graphics":true,"gratis":true,"green":true,"gripe":true,"group":true,"guardian":true,"gucci":true,"guge":true,"guide":true,"guitars":true,"guru":true,"hamburg":true,"hangout":true,"haus":true,"hbo":true,"hdfc":true,"hdfcbank":true,"health":true,"healthcare":true,"help":true,"helsinki":true,"here":true,"hermes":true,"hgtv":true,"hiphop":true,"hisamitsu":true,"hitachi":true,"hiv":true,"hkt":true,"hockey":true,"holdings":true,"holiday":true,"homedepot":true,"homegoods":true,"homes":true,"homesense":true,"honda":true,"honeywell":true,"horse":true,"host":true,"hosting":true,"hot":true,"hoteles":true,"hotmail":true,"house":true,"how":true,"hsbc":true,"htc":true,"hughes":true,"hyatt":true,"hyundai":true,"ibm":true,"icbc":true,"ice":true,"icu":true,"ieee":true,"ifm":true,"iinet":true,"ikano":true,"imamat":true,"imdb":true,"immo":true,"immobilien":true,"industries":true,"infiniti":true,"ing":true,"ink":true,"institute":true,"insurance":true,"insure":true,"intel":true,"international":true,"intuit":true,"investments":true,"ipiranga":true,"irish":true,"iselect":true,"ismaili":true,"ist":true,"istanbul":true,"itau":true,"itv":true,"iveco":true,"iwc":true,"jaguar":true,"java":true,"jcb":true,"jcp":true,"jeep":true,"jetzt":true,"jewelry":true,"jio":true,"jlc":true,"jll":true,"jmp":true,"jnj":true,"joburg":true,"jot":true,"joy":true,"jpmorgan":true,"jprs":true,"juegos":true,"juniper":true,"kaufen":true,"kddi":true,"kerryhotels":true,"kerrylogistics":true,"kerryproperties":true,"kfh":true,"kia":true,"kim":true,"kinder":true,"kindle":true,"kitchen":true,"kiwi":true,"koeln":true,"komatsu":true,"kosher":true,"kpmg":true,"kpn":true,"krd":true,"kred":true,"kuokgroup":true,"kyknet":true,"kyoto":true,"lacaixa":true,"ladbrokes":true,"lamborghini":true,"lancaster":true,"lancia":true,"lancome":true,"land":true,"landrover":true,"lanxess":true,"lasalle":true,"lat":true,"latino":true,"latrobe":true,"law":true,"lawyer":true,"lds":true,"lease":true,"leclerc":true,"lefrak":true,"legal":true,"lego":true,"lexus":true,"lgbt":true,"liaison":true,"lidl":true,"life":true,"lifeinsurance":true,"lifestyle":true,"lighting":true,"like":true,"lilly":true,"limited":true,"limo":true,"lincoln":true,"linde":true,"link":true,"lipsy":true,"live":true,"living":true,"lixil":true,"loan":true,"loans":true,"locker":true,"locus":true,"loft":true,"lol":true,"london":true,"lotte":true,"lotto":true,"love":true,"lpl":true,"lplfinancial":true,"ltd":true,"ltda":true,"lundbeck":true,"lupin":true,"luxe":true,"luxury":true,"macys":true,"madrid":true,"maif":true,"maison":true,"makeup":true,"man":true,"management":true,"mango":true,"market":true,"marketing":true,"markets":true,"marriott":true,"marshalls":true,"maserati":true,"mattel":true,"mba":true,"mcd":true,"mcdonalds":true,"mckinsey":true,"med":true,"media":true,"meet":true,"melbourne":true,"meme":true,"memorial":true,"men":true,"menu":true,"meo":true,"metlife":true,"miami":true,"microsoft":true,"mini":true,"mint":true,"mit":true,"mitsubishi":true,"mlb":true,"mls":true,"mma":true,"mnet":true,"mobily":true,"moda":true,"moe":true,"moi":true,"mom":true,"monash":true,"money":true,"monster":true,"montblanc":true,"mopar":true,"mormon":true,"mortgage":true,"moscow":true,"moto":true,"motorcycles":true,"mov":true,"movie":true,"movistar":true,"msd":true,"mtn":true,"mtpc":true,"mtr":true,"multichoice":true,"mutual":true,"mutuelle":true,"mzansimagic":true,"nab":true,"nadex":true,"nagoya":true,"naspers":true,"nationwide":true,"natura":true,"navy":true,"nba":true,"nec":true,"netbank":true,"netflix":true,"network":true,"neustar":true,"new":true,"newholland":true,"news":true,"next":true,"nextdirect":true,"nexus":true,"nfl":true,"ngo":true,"nhk":true,"nico":true,"nike":true,"nikon":true,"ninja":true,"nissan":true,"nokia":true,"northwesternmutual":true,"norton":true,"now":true,"nowruz":true,"nowtv":true,"nra":true,"nrw":true,"ntt":true,"nyc":true,"obi":true,"observer":true,"off":true,"office":true,"okinawa":true,"olayan":true,"olayangroup":true,"oldnavy":true,"ollo":true,"omega":true,"one":true,"ong":true,"onl":true,"online":true,"onyourside":true,"ooo":true,"open":true,"oracle":true,"orange":true,"organic":true,"orientexpress":true,"osaka":true,"otsuka":true,"ott":true,"ovh":true,"page":true,"pamperedchef":true,"panasonic":true,"panerai":true,"paris":true,"pars":true,"partners":true,"parts":true,"party":true,"passagens":true,"pay":true,"payu":true,"pccw":true,"pet":true,"pfizer":true,"pharmacy":true,"philips":true,"photo":true,"photography":true,"photos":true,"physio":true,"piaget":true,"pics":true,"pictet":true,"pictures":true,"pid":true,"pin":true,"ping":true,"pink":true,"pioneer":true,"pizza":true,"place":true,"play":true,"playstation":true,"plumbing":true,"plus":true,"pnc":true,"pohl":true,"poker":true,"politie":true,"porn":true,"pramerica":true,"praxi":true,"press":true,"prime":true,"prod":true,"productions":true,"prof":true,"progressive":true,"promo":true,"properties":true,"property":true,"protection":true,"pru":true,"prudential":true,"pub":true,"qpon":true,"quebec":true,"quest":true,"qvc":true,"racing":true,"raid":true,"read":true,"realestate":true,"realtor":true,"realty":true,"recipes":true,"red":true,"redstone":true,"redumbrella":true,"rehab":true,"reise":true,"reisen":true,"reit":true,"reliance":true,"ren":true,"rent":true,"rentals":true,"repair":true,"report":true,"republican":true,"rest":true,"restaurant":true,"review":true,"reviews":true,"rexroth":true,"rich":true,"richardli":true,"ricoh":true,"rightathome":true,"ril":true,"rio":true,"rip":true,"rocher":true,"rocks":true,"rodeo":true,"rogers":true,"room":true,"rsvp":true,"ruhr":true,"run":true,"rwe":true,"ryukyu":true,"saarland":true,"safe":true,"safety":true,"sakura":true,"sale":true,"salon":true,"samsclub":true,"samsung":true,"sandvik":true,"sandvikcoromant":true,"sanofi":true,"sap":true,"sapo":true,"sarl":true,"sas":true,"save":true,"saxo":true,"sbi":true,"sbs":true,"sca":true,"scb":true,"schaeffler":true,"schmidt":true,"scholarships":true,"school":true,"schule":true,"schwarz":true,"science":true,"scjohnson":true,"scor":true,"scot":true,"seat":true,"secure":true,"security":true,"seek":true,"sener":true,"services":true,"ses":true,"seven":true,"sew":true,"sex":true,"sexy":true,"sfr":true,"shangrila":true,"sharp":true,"shaw":true,"shell":true,"shia":true,"shiksha":true,"shoes":true,"shouji":true,"show":true,"showtime":true,"shriram":true,"silk":true,"sina":true,"singles":true,"site":true,"ski":true,"skin":true,"sky":true,"skype":true,"sling":true,"smart":true,"smile":true,"sncf":true,"soccer":true,"social":true,"softbank":true,"software":true,"sohu":true,"solar":true,"solutions":true,"song":true,"sony":true,"soy":true,"space":true,"spiegel":true,"spot":true,"spreadbetting":true,"srl":true,"srt":true,"stada":true,"staples":true,"star":true,"starhub":true,"statebank":true,"statefarm":true,"statoil":true,"stc":true,"stcgroup":true,"stockholm":true,"storage":true,"store":true,"studio":true,"study":true,"style":true,"sucks":true,"supersport":true,"supplies":true,"supply":true,"support":true,"surf":true,"surgery":true,"suzuki":true,"swatch":true,"swiftcover":true,"swiss":true,"sydney":true,"symantec":true,"systems":true,"tab":true,"taipei":true,"talk":true,"taobao":true,"target":true,"tatamotors":true,"tatar":true,"tattoo":true,"tax":true,"taxi":true,"tci":true,"tdk":true,"team":true,"tech":true,"technology":true,"telecity":true,"telefonica":true,"temasek":true,"tennis":true,"teva":true,"thd":true,"theater":true,"theatre":true,"theguardian":true,"tiaa":true,"tickets":true,"tienda":true,"tiffany":true,"tips":true,"tires":true,"tirol":true,"tjmaxx":true,"tjx":true,"tkmaxx":true,"tmall":true,"today":true,"tokyo":true,"tools":true,"top":true,"toray":true,"toshiba":true,"total":true,"tours":true,"town":true,"toyota":true,"toys":true,"trade":true,"trading":true,"training":true,"travelchannel":true,"travelers":true,"travelersinsurance":true,"trust":true,"trv":true,"tube":true,"tui":true,"tunes":true,"tushu":true,"tvs":true,"ubank":true,"ubs":true,"uconnect":true,"university":true,"uno":true,"uol":true,"ups":true,"vacations":true,"vana":true,"vanguard":true,"vegas":true,"ventures":true,"verisign":true,"versicherung":true,"vet":true,"viajes":true,"video":true,"vig":true,"viking":true,"villas":true,"vin":true,"vip":true,"virgin":true,"visa":true,"vision":true,"vista":true,"vistaprint":true,"viva":true,"vivo":true,"vlaanderen":true,"vodka":true,"volkswagen":true,"vote":true,"voting":true,"voto":true,"voyage":true,"vuelos":true,"wales":true,"walmart":true,"walter":true,"wang":true,"wanggou":true,"warman":true,"watch":true,"watches":true,"weather":true,"weatherchannel":true,"webcam":true,"weber":true,"website":true,"wed":true,"wedding":true,"weibo":true,"weir":true,"whoswho":true,"wien":true,"wiki":true,"williamhill":true,"win":true,"windows":true,"wine":true,"winners":true,"wme":true,"wolterskluwer":true,"woodside":true,"work":true,"works":true,"world":true,"wtc":true,"wtf":true,"xbox":true,"xerox":true,"xfinity":true,"xihuan":true,"xin":true,"xn--11b4c3d":true,"xn--1ck2e1b":true,"xn--1qqw23a":true,"xn--30rr7y":true,"xn--3bst00m":true,"xn--3ds443g":true,"xn--3oq18vl8pn36a":true,"xn--3pxu8k":true,"xn--42c2d9a":true,"xn--45q11c":true,"xn--4gbrim":true,"xn--4gq48lf9j":true,"xn--55qw42g":true,"xn--55qx5d":true,"xn--5su34j936bgsg":true,"xn--5tzm5g":true,"xn--6frz82g":true,"xn--6qq986b3xl":true,"xn--80adxhks":true,"xn--80asehdb":true,"xn--80aswg":true,"xn--8y0a063a":true,"xn--9dbq2a":true,"xn--9et52u":true,"xn--9krt00a":true,"xn--b4w605ferd":true,"xn--bck1b9a5dre4c":true,"xn--c1avg":true,"xn--c2br7g":true,"xn--cck2b3b":true,"xn--cg4bki":true,"xn--czr694b":true,"xn--czrs0t":true,"xn--czru2d":true,"xn--d1acj3b":true,"xn--eckvdtc9d":true,"xn--efvy88h":true,"xn--estv75g":true,"xn--fct429k":true,"xn--fhbei":true,"xn--fiq228c5hs":true,"xn--fiq64b":true,"xn--fjq720a":true,"xn--flw351e":true,"xn--fzys8d69uvgm":true,"xn--g2xx48c":true,"xn--gckr3f0f":true,"xn--hxt814e":true,"xn--i1b6b1a6a2e":true,"xn--imr513n":true,"xn--io0a7i":true,"xn--j1aef":true,"xn--jlq61u9w7b":true,"xn--jvr189m":true,"xn--kcrx77d1x4a":true,"xn--kpu716f":true,"xn--kput3i":true,"xn--mgba3a3ejt":true,"xn--mgba7c0bbn0a":true,"xn--mgbaakc7dvf":true,"xn--mgbab2bd":true,"xn--mgbb9fbpob":true,"xn--mgbca7dzdo":true,"xn--mgbt3dhd":true,"xn--mk1bu44c":true,"xn--mxtq1m":true,"xn--ngbc5azd":true,"xn--ngbe9e0a":true,"xn--nqv7f":true,"xn--nqv7fs00ema":true,"xn--nyqy26a":true,"xn--p1acf":true,"xn--pbt977c":true,"xn--pssy2u":true,"xn--q9jyb4c":true,"xn--qcka1pmc":true,"xn--rhqv96g":true,"xn--rovu88b":true,"xn--ses554g":true,"xn--t60b56a":true,"xn--tckwe":true,"xn--unup4y":true,"xn--vermgensberater-ctb":true,"xn--vermgensberatung-pwb":true,"xn--vhquv":true,"xn--vuq861b":true,"xn--w4r85el8fhu5dnra":true,"xn--w4rs40l":true,"xn--xhq521b":true,"xn--zfr164b":true,"xperia":true,"xyz":true,"yachts":true,"yahoo":true,"yamaxun":true,"yandex":true,"yodobashi":true,"yoga":true,"yokohama":true,"you":true,"youtube":true,"yun":true,"zappos":true,"zara":true,"zero":true,"zip":true,"zippo":true,"zone":true,"zuerich":true,"cloudfront.net":true,"ap-northeast-1.compute.amazonaws.com":true,"ap-southeast-1.compute.amazonaws.com":true,"ap-southeast-2.compute.amazonaws.com":true,"cn-north-1.compute.amazonaws.cn":true,"compute.amazonaws.cn":true,"compute.amazonaws.com":true,"compute-1.amazonaws.com":true,"eu-west-1.compute.amazonaws.com":true,"eu-central-1.compute.amazonaws.com":true,"sa-east-1.compute.amazonaws.com":true,"us-east-1.amazonaws.com":true,"us-gov-west-1.compute.amazonaws.com":true,"us-west-1.compute.amazonaws.com":true,"us-west-2.compute.amazonaws.com":true,"z-1.compute-1.amazonaws.com":true,"z-2.compute-1.amazonaws.com":true,"elasticbeanstalk.com":true,"elb.amazonaws.com":true,"s3.amazonaws.com":true,"s3-ap-northeast-1.amazonaws.com":true,"s3-ap-southeast-1.amazonaws.com":true,"s3-ap-southeast-2.amazonaws.com":true,"s3-external-1.amazonaws.com":true,"s3-external-2.amazonaws.com":true,"s3-fips-us-gov-west-1.amazonaws.com":true,"s3-eu-central-1.amazonaws.com":true,"s3-eu-west-1.amazonaws.com":true,"s3-sa-east-1.amazonaws.com":true,"s3-us-gov-west-1.amazonaws.com":true,"s3-us-west-1.amazonaws.com":true,"s3-us-west-2.amazonaws.com":true,"s3.cn-north-1.amazonaws.com.cn":true,"s3.eu-central-1.amazonaws.com":true,"betainabox.com":true,"ae.org":true,"ar.com":true,"br.com":true,"cn.com":true,"com.de":true,"com.se":true,"de.com":true,"eu.com":true,"gb.com":true,"gb.net":true,"hu.com":true,"hu.net":true,"jp.net":true,"jpn.com":true,"kr.com":true,"mex.com":true,"no.com":true,"qc.com":true,"ru.com":true,"sa.com":true,"se.com":true,"se.net":true,"uk.com":true,"uk.net":true,"us.com":true,"uy.com":true,"za.bz":true,"za.com":true,"africa.com":true,"gr.com":true,"in.net":true,"us.org":true,"co.com":true,"c.la":true,"cloudcontrolled.com":true,"cloudcontrolapp.com":true,"co.ca":true,"c.cdn77.org":true,"cdn77-ssl.net":true,"r.cdn77.net":true,"rsc.cdn77.org":true,"ssl.origin.cdn77-secure.org":true,"co.nl":true,"co.no":true,"*.platform.sh":true,"cupcake.is":true,"dreamhosters.com":true,"duckdns.org":true,"dyndns-at-home.com":true,"dyndns-at-work.com":true,"dyndns-blog.com":true,"dyndns-free.com":true,"dyndns-home.com":true,"dyndns-ip.com":true,"dyndns-mail.com":true,"dyndns-office.com":true,"dyndns-pics.com":true,"dyndns-remote.com":true,"dyndns-server.com":true,"dyndns-web.com":true,"dyndns-wiki.com":true,"dyndns-work.com":true,"dyndns.biz":true,"dyndns.info":true,"dyndns.org":true,"dyndns.tv":true,"at-band-camp.net":true,"ath.cx":true,"barrel-of-knowledge.info":true,"barrell-of-knowledge.info":true,"better-than.tv":true,"blogdns.com":true,"blogdns.net":true,"blogdns.org":true,"blogsite.org":true,"boldlygoingnowhere.org":true,"broke-it.net":true,"buyshouses.net":true,"cechire.com":true,"dnsalias.com":true,"dnsalias.net":true,"dnsalias.org":true,"dnsdojo.com":true,"dnsdojo.net":true,"dnsdojo.org":true,"does-it.net":true,"doesntexist.com":true,"doesntexist.org":true,"dontexist.com":true,"dontexist.net":true,"dontexist.org":true,"doomdns.com":true,"doomdns.org":true,"dvrdns.org":true,"dyn-o-saur.com":true,"dynalias.com":true,"dynalias.net":true,"dynalias.org":true,"dynathome.net":true,"dyndns.ws":true,"endofinternet.net":true,"endofinternet.org":true,"endoftheinternet.org":true,"est-a-la-maison.com":true,"est-a-la-masion.com":true,"est-le-patron.com":true,"est-mon-blogueur.com":true,"for-better.biz":true,"for-more.biz":true,"for-our.info":true,"for-some.biz":true,"for-the.biz":true,"forgot.her.name":true,"forgot.his.name":true,"from-ak.com":true,"from-al.com":true,"from-ar.com":true,"from-az.net":true,"from-ca.com":true,"from-co.net":true,"from-ct.com":true,"from-dc.com":true,"from-de.com":true,"from-fl.com":true,"from-ga.com":true,"from-hi.com":true,"from-ia.com":true,"from-id.com":true,"from-il.com":true,"from-in.com":true,"from-ks.com":true,"from-ky.com":true,"from-la.net":true,"from-ma.com":true,"from-md.com":true,"from-me.org":true,"from-mi.com":true,"from-mn.com":true,"from-mo.com":true,"from-ms.com":true,"from-mt.com":true,"from-nc.com":true,"from-nd.com":true,"from-ne.com":true,"from-nh.com":true,"from-nj.com":true,"from-nm.com":true,"from-nv.com":true,"from-ny.net":true,"from-oh.com":true,"from-ok.com":true,"from-or.com":true,"from-pa.com":true,"from-pr.com":true,"from-ri.com":true,"from-sc.com":true,"from-sd.com":true,"from-tn.com":true,"from-tx.com":true,"from-ut.com":true,"from-va.com":true,"from-vt.com":true,"from-wa.com":true,"from-wi.com":true,"from-wv.com":true,"from-wy.com":true,"ftpaccess.cc":true,"fuettertdasnetz.de":true,"game-host.org":true,"game-server.cc":true,"getmyip.com":true,"gets-it.net":true,"go.dyndns.org":true,"gotdns.com":true,"gotdns.org":true,"groks-the.info":true,"groks-this.info":true,"ham-radio-op.net":true,"here-for-more.info":true,"hobby-site.com":true,"hobby-site.org":true,"home.dyndns.org":true,"homedns.org":true,"homeftp.net":true,"homeftp.org":true,"homeip.net":true,"homelinux.com":true,"homelinux.net":true,"homelinux.org":true,"homeunix.com":true,"homeunix.net":true,"homeunix.org":true,"iamallama.com":true,"in-the-band.net":true,"is-a-anarchist.com":true,"is-a-blogger.com":true,"is-a-bookkeeper.com":true,"is-a-bruinsfan.org":true,"is-a-bulls-fan.com":true,"is-a-candidate.org":true,"is-a-caterer.com":true,"is-a-celticsfan.org":true,"is-a-chef.com":true,"is-a-chef.net":true,"is-a-chef.org":true,"is-a-conservative.com":true,"is-a-cpa.com":true,"is-a-cubicle-slave.com":true,"is-a-democrat.com":true,"is-a-designer.com":true,"is-a-doctor.com":true,"is-a-financialadvisor.com":true,"is-a-geek.com":true,"is-a-geek.net":true,"is-a-geek.org":true,"is-a-green.com":true,"is-a-guru.com":true,"is-a-hard-worker.com":true,"is-a-hunter.com":true,"is-a-knight.org":true,"is-a-landscaper.com":true,"is-a-lawyer.com":true,"is-a-liberal.com":true,"is-a-libertarian.com":true,"is-a-linux-user.org":true,"is-a-llama.com":true,"is-a-musician.com":true,"is-a-nascarfan.com":true,"is-a-nurse.com":true,"is-a-painter.com":true,"is-a-patsfan.org":true,"is-a-personaltrainer.com":true,"is-a-photographer.com":true,"is-a-player.com":true,"is-a-republican.com":true,"is-a-rockstar.com":true,"is-a-socialist.com":true,"is-a-soxfan.org":true,"is-a-student.com":true,"is-a-teacher.com":true,"is-a-techie.com":true,"is-a-therapist.com":true,"is-an-accountant.com":true,"is-an-actor.com":true,"is-an-actress.com":true,"is-an-anarchist.com":true,"is-an-artist.com":true,"is-an-engineer.com":true,"is-an-entertainer.com":true,"is-by.us":true,"is-certified.com":true,"is-found.org":true,"is-gone.com":true,"is-into-anime.com":true,"is-into-cars.com":true,"is-into-cartoons.com":true,"is-into-games.com":true,"is-leet.com":true,"is-lost.org":true,"is-not-certified.com":true,"is-saved.org":true,"is-slick.com":true,"is-uberleet.com":true,"is-very-bad.org":true,"is-very-evil.org":true,"is-very-good.org":true,"is-very-nice.org":true,"is-very-sweet.org":true,"is-with-theband.com":true,"isa-geek.com":true,"isa-geek.net":true,"isa-geek.org":true,"isa-hockeynut.com":true,"issmarterthanyou.com":true,"isteingeek.de":true,"istmein.de":true,"kicks-ass.net":true,"kicks-ass.org":true,"knowsitall.info":true,"land-4-sale.us":true,"lebtimnetz.de":true,"leitungsen.de":true,"likes-pie.com":true,"likescandy.com":true,"merseine.nu":true,"mine.nu":true,"misconfused.org":true,"mypets.ws":true,"myphotos.cc":true,"neat-url.com":true,"office-on-the.net":true,"on-the-web.tv":true,"podzone.net":true,"podzone.org":true,"readmyblog.org":true,"saves-the-whales.com":true,"scrapper-site.net":true,"scrapping.cc":true,"selfip.biz":true,"selfip.com":true,"selfip.info":true,"selfip.net":true,"selfip.org":true,"sells-for-less.com":true,"sells-for-u.com":true,"sells-it.net":true,"sellsyourhome.org":true,"servebbs.com":true,"servebbs.net":true,"servebbs.org":true,"serveftp.net":true,"serveftp.org":true,"servegame.org":true,"shacknet.nu":true,"simple-url.com":true,"space-to-rent.com":true,"stuff-4-sale.org":true,"stuff-4-sale.us":true,"teaches-yoga.com":true,"thruhere.net":true,"traeumtgerade.de":true,"webhop.biz":true,"webhop.info":true,"webhop.net":true,"webhop.org":true,"worse-than.tv":true,"writesthisblog.com":true,"eu.org":true,"al.eu.org":true,"asso.eu.org":true,"at.eu.org":true,"au.eu.org":true,"be.eu.org":true,"bg.eu.org":true,"ca.eu.org":true,"cd.eu.org":true,"ch.eu.org":true,"cn.eu.org":true,"cy.eu.org":true,"cz.eu.org":true,"de.eu.org":true,"dk.eu.org":true,"edu.eu.org":true,"ee.eu.org":true,"es.eu.org":true,"fi.eu.org":true,"fr.eu.org":true,"gr.eu.org":true,"hr.eu.org":true,"hu.eu.org":true,"ie.eu.org":true,"il.eu.org":true,"in.eu.org":true,"int.eu.org":true,"is.eu.org":true,"it.eu.org":true,"jp.eu.org":true,"kr.eu.org":true,"lt.eu.org":true,"lu.eu.org":true,"lv.eu.org":true,"mc.eu.org":true,"me.eu.org":true,"mk.eu.org":true,"mt.eu.org":true,"my.eu.org":true,"net.eu.org":true,"ng.eu.org":true,"nl.eu.org":true,"no.eu.org":true,"nz.eu.org":true,"paris.eu.org":true,"pl.eu.org":true,"pt.eu.org":true,"q-a.eu.org":true,"ro.eu.org":true,"ru.eu.org":true,"se.eu.org":true,"si.eu.org":true,"sk.eu.org":true,"tr.eu.org":true,"uk.eu.org":true,"us.eu.org":true,"a.ssl.fastly.net":true,"b.ssl.fastly.net":true,"global.ssl.fastly.net":true,"a.prod.fastly.net":true,"global.prod.fastly.net":true,"firebaseapp.com":true,"flynnhub.com":true,"service.gov.uk":true,"github.io":true,"githubusercontent.com":true,"ro.com":true,"appspot.com":true,"blogspot.ae":true,"blogspot.al":true,"blogspot.am":true,"blogspot.ba":true,"blogspot.be":true,"blogspot.bg":true,"blogspot.bj":true,"blogspot.ca":true,"blogspot.cf":true,"blogspot.ch":true,"blogspot.cl":true,"blogspot.co.at":true,"blogspot.co.id":true,"blogspot.co.il":true,"blogspot.co.ke":true,"blogspot.co.nz":true,"blogspot.co.uk":true,"blogspot.co.za":true,"blogspot.com":true,"blogspot.com.ar":true,"blogspot.com.au":true,"blogspot.com.br":true,"blogspot.com.by":true,"blogspot.com.co":true,"blogspot.com.cy":true,"blogspot.com.ee":true,"blogspot.com.eg":true,"blogspot.com.es":true,"blogspot.com.mt":true,"blogspot.com.ng":true,"blogspot.com.tr":true,"blogspot.com.uy":true,"blogspot.cv":true,"blogspot.cz":true,"blogspot.de":true,"blogspot.dk":true,"blogspot.fi":true,"blogspot.fr":true,"blogspot.gr":true,"blogspot.hk":true,"blogspot.hr":true,"blogspot.hu":true,"blogspot.ie":true,"blogspot.in":true,"blogspot.is":true,"blogspot.it":true,"blogspot.jp":true,"blogspot.kr":true,"blogspot.li":true,"blogspot.lt":true,"blogspot.lu":true,"blogspot.md":true,"blogspot.mk":true,"blogspot.mr":true,"blogspot.mx":true,"blogspot.my":true,"blogspot.nl":true,"blogspot.no":true,"blogspot.pe":true,"blogspot.pt":true,"blogspot.qa":true,"blogspot.re":true,"blogspot.ro":true,"blogspot.rs":true,"blogspot.ru":true,"blogspot.se":true,"blogspot.sg":true,"blogspot.si":true,"blogspot.sk":true,"blogspot.sn":true,"blogspot.td":true,"blogspot.tw":true,"blogspot.ug":true,"blogspot.vn":true,"codespot.com":true,"googleapis.com":true,"googlecode.com":true,"pagespeedmobilizer.com":true,"withgoogle.com":true,"withyoutube.com":true,"herokuapp.com":true,"herokussl.com":true,"iki.fi":true,"biz.at":true,"info.at":true,"co.pl":true,"azurewebsites.net":true,"azure-mobile.net":true,"cloudapp.net":true,"bmoattachments.org":true,"4u.com":true,"nfshost.com":true,"nyc.mn":true,"nid.io":true,"operaunite.com":true,"outsystemscloud.com":true,"art.pl":true,"gliwice.pl":true,"krakow.pl":true,"poznan.pl":true,"wroc.pl":true,"zakopane.pl":true,"pantheon.io":true,"gotpantheon.com":true,"priv.at":true,"qa2.com":true,"rhcloud.com":true,"sandcats.io":true,"biz.ua":true,"co.ua":true,"pp.ua":true,"sinaapp.com":true,"vipsinaapp.com":true,"1kapp.com":true,"gda.pl":true,"gdansk.pl":true,"gdynia.pl":true,"med.pl":true,"sopot.pl":true,"hk.com":true,"hk.org":true,"ltd.hk":true,"inc.hk":true,"yolasite.com":true,"za.net":true,"za.org":true}); + +// END of automatically generated file /***/ }), -/* 320 */ +/* 327 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * array-unique <https://github.com/jonschlinkert/array-unique> + * Copyright (c) 2015, Salesforce.com, Inc. + * All rights reserved. * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of Salesforce.com nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. */ +/*jshint unused:false */ +function Store() { +} +exports.Store = Store; -module.exports = function unique(arr) { - if (!Array.isArray(arr)) { - throw new TypeError('array-unique expects an array.'); - } +// Stores may be synchronous, but are still required to use a +// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync" +// API that converts from synchronous-callbacks to imperative style. +Store.prototype.synchronous = false; - var len = arr.length; - var i = -1; +Store.prototype.findCookie = function(domain, path, key, cb) { + throw new Error('findCookie is not implemented'); +}; - while (i++ < len) { - var j = i + 1; +Store.prototype.findCookies = function(domain, path, cb) { + throw new Error('findCookies is not implemented'); +}; - for (; j < arr.length; ++j) { - if (arr[i] === arr[j]) { - arr.splice(j--, 1); - } - } - } - return arr; +Store.prototype.putCookie = function(cookie, cb) { + throw new Error('putCookie is not implemented'); }; +Store.prototype.updateCookie = function(oldCookie, newCookie, cb) { + // recommended default implementation: + // return this.putCookie(newCookie, cb); + throw new Error('updateCookie is not implemented'); +}; -/***/ }), -/* 321 */ -/***/ (function(module, exports, __webpack_require__) { +Store.prototype.removeCookie = function(domain, path, key, cb) { + throw new Error('removeCookie is not implemented'); +}; -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. +Store.prototype.removeCookies = function(domain, path, cb) { + throw new Error('removeCookies is not implemented'); +}; -var errors = __webpack_require__(117); -var types = __webpack_require__(118); +Store.prototype.getAllCookies = function(cb) { + throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)'); +}; -var Reader = __webpack_require__(322); -var Writer = __webpack_require__(323); +/***/ }), +/* 328 */ +/***/ (function(module, exports) { -///--- Exports +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +var byteToHex = []; +for (var i = 0; i < 256; ++i) { + byteToHex[i] = (i + 0x100).toString(16).substr(1); +} -module.exports = { +function bytesToUuid(buf, offset) { + var i = offset || 0; + var bth = byteToHex; + return bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + '-' + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]] + + bth[buf[i++]] + bth[buf[i++]]; +} - Reader: Reader, +module.exports = bytesToUuid; - Writer: Writer +/***/ }), +/* 329 */ +/***/ (function(module, exports, __webpack_require__) { + +// Unique ID creation requires a high quality random # generator. In node.js +// this is prett straight-forward - we use the crypto API. + +var rb = __webpack_require__(8).randomBytes; + +function rng() { + return rb(16); }; -for (var t in types) { - if (types.hasOwnProperty(t)) - module.exports[t] = types[t]; -} -for (var e in errors) { - if (errors.hasOwnProperty(e)) - module.exports[e] = errors[e]; -} +module.exports = rng; /***/ }), -/* 322 */ -/***/ (function(module, exports, __webpack_require__) { +/* 330 */ +/***/ (function(module, exports) { -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. +module.exports = extend -var assert = __webpack_require__(22); +var hasOwnProperty = Object.prototype.hasOwnProperty; -var ASN1 = __webpack_require__(118); -var errors = __webpack_require__(117); +function extend() { + var target = {} + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] -///--- Globals + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } -var newInvalidAsn1Error = errors.newInvalidAsn1Error; + return target +} +/***/ }), +/* 331 */ +/***/ (function(module, exports) { -///--- API +module.exports = require("constants"); -function Reader(data) { - if (!data || !Buffer.isBuffer(data)) - throw new TypeError('data must be a node Buffer'); +/***/ }), +/* 332 */ +/***/ (function(module, exports) { - this._buf = data; - this._size = data.length; +module.exports = require("tls"); - // These hold the "current" state - this._len = 0; - this._offset = 0; -} +/***/ }), +/* 333 */ +/***/ (function(module, exports, __webpack_require__) { -Object.defineProperty(Reader.prototype, 'length', { - enumerable: true, - get: function () { return (this._len); } -}); +"use strict"; -Object.defineProperty(Reader.prototype, 'offset', { - enumerable: true, - get: function () { return (this._offset); } -}); -Object.defineProperty(Reader.prototype, 'remain', { - get: function () { return (this._size - this._offset); } +Object.defineProperty(exports, "__esModule", { + value: true }); +exports.getRcConfigForCwd = getRcConfigForCwd; +exports.getRcArgs = getRcArgs; -Object.defineProperty(Reader.prototype, 'buffer', { - get: function () { return (this._buf.slice(this._offset)); } -}); +var _path; +function _load_path() { + return _path = __webpack_require__(0); +} -/** - * Reads a single byte and advances offset; you can pass in `true` to make this - * a "peek" operation (i.e., get the byte, but don't advance the offset). - * - * @param {Boolean} peek true means don't move offset. - * @return {Number} the next byte, null if not enough data. - */ -Reader.prototype.readByte = function(peek) { - if (this._size - this._offset < 1) - return null; +var _lockfile; - var b = this._buf[this._offset] & 0xff; +function _load_lockfile() { + return _lockfile = __webpack_require__(12); +} - if (!peek) - this._offset += 1; +var _rc; - return b; -}; +function _load_rc() { + return _rc = _interopRequireWildcard(__webpack_require__(444)); +} +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -Reader.prototype.peek = function() { - return this.readByte(true); -}; +// Keys that will get resolved relative to the path of the rc file they belong to +const PATH_KEYS = ['yarn-path', 'cache-folder', 'global-folder', 'modules-folder', 'cwd']; +// given a cwd, load all .yarnrc files relative to it -/** - * Reads a (potentially) variable length off the BER buffer. This call is - * not really meant to be called directly, as callers have to manipulate - * the internal buffer afterwards. - * - * As a result of this call, you can call `Reader.length`, until the - * next thing called that does a readLength. - * - * @return {Number} the amount of offset to advance the buffer. - * @throws {InvalidAsn1Error} on bad ASN.1 - */ -Reader.prototype.readLength = function(offset) { - if (offset === undefined) - offset = this._offset; - if (offset >= this._size) - return null; +function getRcConfigForCwd(cwd) { + return (_rc || _load_rc()).findRc('yarn', cwd, (fileText, filePath) => { + var _parse = (0, (_lockfile || _load_lockfile()).parse)(fileText, 'yarnrc'); - var lenB = this._buf[offset++] & 0xff; - if (lenB === null) - return null; + const values = _parse.object; - if ((lenB & 0x80) == 0x80) { - lenB &= 0x7f; + // some keys reference directories so keep their relativity - if (lenB == 0) - throw newInvalidAsn1Error('Indefinite length not supported'); + for (const key in values) { + for (const pathKey of PATH_KEYS) { + if (key.replace(/^(--)?([^.]+\.)*/, '') === pathKey) { + values[key] = (0, (_path || _load_path()).resolve)((0, (_path || _load_path()).dirname)(filePath), values[key]); + } + } + } - if (lenB > 4) - throw newInvalidAsn1Error('encoding too long'); + return values; + }); +} - if (this._size - offset < lenB) - return null; +// get the built of arguments of a .yarnrc chain of the passed cwd +function buildRcArgs(cwd) { + const config = getRcConfigForCwd(cwd); - this._len = 0; - for (var i = 0; i < lenB; i++) - this._len = (this._len << 8) + (this._buf[offset++] & 0xff); + const argsForCommands = new Map(); - } else { - // Wasn't a variable length - this._len = lenB; - } + for (const key in config) { + // args can be prefixed with the command name they're meant for, eg. + // `--install.check-files true` + const keyMatch = key.match(/^--(?:([^.]+)\.)?(.*)$/); + if (!keyMatch) { + continue; + } - return offset; -}; + const commandName = keyMatch[1] || '*'; + const arg = keyMatch[2]; + const value = config[key]; + // create args for this command name if we didn't previously have them + const args = argsForCommands.get(commandName) || []; + argsForCommands.set(commandName, args); -/** - * Parses the next sequence in this BER buffer. - * - * To get the length of the sequence, call `Reader.length`. - * - * @return {Number} the sequence's tag. - */ -Reader.prototype.readSequence = function(tag) { - var seq = this.peek(); - if (seq === null) - return null; - if (tag !== undefined && tag !== seq) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + seq.toString(16)); + // turn config value into appropriate cli flag + if (typeof value === 'string') { + args.push(`--${arg}`, value); + } else if (value === true) { + args.push(`--${arg}`); + } else if (value === false) { + args.push(`--no-${arg}`); + } + } - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; + return argsForCommands; +} - this._offset = o; - return seq; -}; +// extract the value of a --cwd arg if present +function extractCwdArg(args) { + for (let i = 0, I = args.length; i < I; ++i) { + const arg = args[i]; + if (arg === '--') { + return null; + } else if (arg === '--cwd') { + return args[i + 1]; + } + } + return null; +} +// get a list of arguments from .yarnrc that apply to this commandName +function getRcArgs(commandName, args) { + let previousCwds = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; -Reader.prototype.readInt = function() { - return this._readTag(ASN1.Integer); -}; + // for the cwd, use the --cwd arg if it was passed or else use process.cwd() + const origCwd = extractCwdArg(args) || process.cwd(); + // get a map of command names and their arguments + const argMap = buildRcArgs(origCwd); -Reader.prototype.readBoolean = function() { - return (this._readTag(ASN1.Boolean) === 0 ? false : true); -}; + // concat wildcard arguments and arguments meant for this specific command + const newArgs = [].concat(argMap.get('*') || [], argMap.get(commandName) || []); + // check if the .yarnrc args specified a cwd + const newCwd = extractCwdArg(newArgs); + if (newCwd && newCwd !== origCwd) { + // ensure that we don't enter into a loop + if (previousCwds.indexOf(newCwd) !== -1) { + throw new Error(`Recursive .yarnrc files specifying --cwd flags. Bailing out.`); + } -Reader.prototype.readEnumeration = function() { - return this._readTag(ASN1.Enumeration); -}; + // if we have a new cwd then let's refetch the .yarnrc args relative to it + return getRcArgs(commandName, newArgs, previousCwds.concat(origCwd)); + } + return newArgs; +} -Reader.prototype.readString = function(tag, retbuf) { - if (!tag) - tag = ASN1.OctetString; +/***/ }), +/* 334 */ +/***/ (function(module, exports, __webpack_require__) { - var b = this.peek(); - if (b === null) - return null; +"use strict"; - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); - var o = this.readLength(this._offset + 1); // stored in `length` +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = handleSignals; - if (o === null) - return null; - - if (this.length > this._size - o) - return null; - - this._offset = o; - - if (this.length === 0) - return retbuf ? new Buffer(0) : ''; - - var str = this._buf.slice(this._offset, this._offset + this.length); - this._offset += this.length; - - return retbuf ? str : str.toString('utf8'); -}; - -Reader.prototype.readOID = function(tag) { - if (!tag) - tag = ASN1.OID; - - var b = this.readString(tag, true); - if (b === null) - return null; +var _child; - var values = []; - var value = 0; +function _load_child() { + return _child = __webpack_require__(48); +} - for (var i = 0; i < b.length; i++) { - var byte = b[i] & 0xff; +function forwardSignalAndExit(signal) { + (0, (_child || _load_child()).forwardSignalToSpawnedProcesses)(signal); + // We want to exit immediately here since `SIGTERM` means that + // If we lose stdout messages due to abrupt exit, shoot the messenger? + process.exit(1); // eslint-disable-line no-process-exit +} +function handleSignals() { + process.on('SIGTERM', () => { + forwardSignalAndExit('SIGTERM'); + }); +} - value <<= 7; - value += byte & 0x7f; - if ((byte & 0x80) == 0) { - values.push(value); - value = 0; - } - } +/***/ }), +/* 335 */ +/***/ (function(module, exports, __webpack_require__) { - value = values.shift(); - values.unshift(value % 40); - values.unshift((value / 40) >> 0); +/** + * Module dependencies. + */ - return values.join('.'); -}; +var EventEmitter = __webpack_require__(46).EventEmitter; +var spawn = __webpack_require__(148).spawn; +var readlink = __webpack_require__(497).readlinkSync; +var path = __webpack_require__(0); +var dirname = path.dirname; +var basename = path.basename; +var fs = __webpack_require__(5); +/** + * Expose the root command. + */ -Reader.prototype._readTag = function(tag) { - assert.ok(tag !== undefined); +exports = module.exports = new Command(); - var b = this.peek(); +/** + * Expose `Command`. + */ - if (b === null) - return null; +exports.Command = Command; - if (b !== tag) - throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + - ': got 0x' + b.toString(16)); +/** + * Expose `Option`. + */ - var o = this.readLength(this._offset + 1); // stored in `length` - if (o === null) - return null; +exports.Option = Option; - if (this.length > 4) - throw newInvalidAsn1Error('Integer too long: ' + this.length); +/** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {String} flags + * @param {String} description + * @api public + */ - if (this.length > this._size - o) - return null; - this._offset = o; +function Option(flags, description) { + this.flags = flags; + this.required = ~flags.indexOf('<'); + this.optional = ~flags.indexOf('['); + this.bool = !~flags.indexOf('-no-'); + flags = flags.split(/[ ,|]+/); + if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); + this.long = flags.shift(); + this.description = description || ''; +} - var fb = this._buf[this._offset]; - var value = 0; +/** + * Return option name. + * + * @return {String} + * @api private + */ - for (var i = 0; i < this.length; i++) { - value <<= 8; - value |= (this._buf[this._offset++] & 0xff); - } +Option.prototype.name = function() { + return this.long + .replace('--', '') + .replace('no-', ''); +}; - if ((fb & 0x80) == 0x80 && i !== 4) - value -= (1 << (i * 8)); +/** + * Check if `arg` matches the short or long flag. + * + * @param {String} arg + * @return {Boolean} + * @api private + */ - return value >> 0; +Option.prototype.is = function(arg) { + return arg == this.short || arg == this.long; }; +/** + * Initialize a new `Command`. + * + * @param {String} name + * @api public + */ +function Command(name) { + this.commands = []; + this.options = []; + this._execs = {}; + this._allowUnknownOption = false; + this._args = []; + this._name = name || ''; +} -///--- Exported API - -module.exports = Reader; +/** + * Inherit from `EventEmitter.prototype`. + */ +Command.prototype.__proto__ = EventEmitter.prototype; -/***/ }), -/* 323 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Add command `name`. + * + * The `.action()` callback is invoked when the + * command `name` is specified via __ARGV__, + * and the remaining arguments are applied to the + * function for access. + * + * When the `name` is "*" an un-matched command + * will be passed as the first arg, followed by + * the rest of __ARGV__ remaining. + * + * Examples: + * + * program + * .version('0.0.1') + * .option('-C, --chdir <path>', 'change the working directory') + * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf') + * .option('-T, --no-tests', 'ignore test hook') + * + * program + * .command('setup') + * .description('run remote setup commands') + * .action(function() { + * console.log('setup'); + * }); + * + * program + * .command('exec <cmd>') + * .description('run the given remote command') + * .action(function(cmd) { + * console.log('exec "%s"', cmd); + * }); + * + * program + * .command('teardown <dir> [otherDirs...]') + * .description('run teardown commands') + * .action(function(dir, otherDirs) { + * console.log('dir "%s"', dir); + * if (otherDirs) { + * otherDirs.forEach(function (oDir) { + * console.log('dir "%s"', oDir); + * }); + * } + * }); + * + * program + * .command('*') + * .description('deploy the given env') + * .action(function(env) { + * console.log('deploying "%s"', env); + * }); + * + * program.parse(process.argv); + * + * @param {String} name + * @param {String} [desc] for git-style sub-commands + * @return {Command} the new command + * @api public + */ -// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. +Command.prototype.command = function(name, desc, opts) { + opts = opts || {}; + var args = name.split(/ +/); + var cmd = new Command(args.shift()); -var assert = __webpack_require__(22); -var ASN1 = __webpack_require__(118); -var errors = __webpack_require__(117); + if (desc) { + cmd.description(desc); + this.executables = true; + this._execs[cmd._name] = true; + if (opts.isDefault) this.defaultExecutable = cmd._name; + } + cmd._noHelp = !!opts.noHelp; + this.commands.push(cmd); + cmd.parseExpectedArgs(args); + cmd.parent = this; -///--- Globals + if (desc) return this; + return cmd; +}; -var newInvalidAsn1Error = errors.newInvalidAsn1Error; +/** + * Define argument syntax for the top-level command. + * + * @api public + */ -var DEFAULT_OPTS = { - size: 1024, - growthFactor: 8 +Command.prototype.arguments = function (desc) { + return this.parseExpectedArgs(desc.split(/ +/)); }; +/** + * Add an implicit `help [cmd]` subcommand + * which invokes `--help` for the given command. + * + * @api private + */ -///--- Helpers +Command.prototype.addImplicitHelpCommand = function() { + this.command('help [cmd]', 'display help for [cmd]'); +}; -function merge(from, to) { - assert.ok(from); - assert.equal(typeof(from), 'object'); - assert.ok(to); - assert.equal(typeof(to), 'object'); +/** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} for chaining + * @api public + */ - var keys = Object.getOwnPropertyNames(from); - keys.forEach(function(key) { - if (to[key]) - return; +Command.prototype.parseExpectedArgs = function(args) { + if (!args.length) return; + var self = this; + args.forEach(function(arg) { + var argDetails = { + required: false, + name: '', + variadic: false + }; - var value = Object.getOwnPropertyDescriptor(from, key); - Object.defineProperty(to, key, value); - }); + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } - return to; -} + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + self._args.push(argDetails); + } + }); + return this; +}; +/** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} for chaining + * @api public + */ +Command.prototype.action = function(fn) { + var self = this; + var listener = function(args, unknown) { + // Parse any so-far unknown options + args = args || []; + unknown = unknown || []; -///--- API + var parsed = self.parseOptions(unknown); -function Writer(options) { - options = merge(DEFAULT_OPTS, options || {}); + // Output help if necessary + outputHelpIfNecessary(self, parsed.unknown); - this._buf = new Buffer(options.size || 1024); - this._size = this._buf.length; - this._offset = 0; - this._options = options; + // If there are still any unknown options, then we simply + // die, unless someone asked for help, in which case we give it + // to them, and then we die. + if (parsed.unknown.length > 0) { + self.unknownOption(parsed.unknown[0]); + } - // A list of offsets in the buffer where we need to insert - // sequence tag/len pairs. - this._seq = []; -} + // Leftover arguments need to be pushed back. Fixes issue #56 + if (parsed.args.length) args = parsed.args.concat(args); -Object.defineProperty(Writer.prototype, 'buffer', { - get: function () { - if (this._seq.length) - throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)'); + self._args.forEach(function(arg, i) { + if (arg.required && null == args[i]) { + self.missingArgument(arg.name); + } else if (arg.variadic) { + if (i !== self._args.length - 1) { + self.variadicArgNotLast(arg.name); + } - return (this._buf.slice(0, this._offset)); - } -}); + args[i] = args.splice(i); + } + }); -Writer.prototype.writeByte = function(b) { - if (typeof(b) !== 'number') - throw new TypeError('argument must be a Number'); + // Always append ourselves to the end of the arguments, + // to make sure we match the number of arguments the user + // expects + if (self._args.length) { + args[self._args.length] = self; + } else { + args.push(self); + } - this._ensure(1); - this._buf[this._offset++] = b; + fn.apply(self, args); + }; + var parent = this.parent || this; + var name = parent === this ? '*' : this._name; + parent.on(name, listener); + if (this._alias) parent.on(this._alias, listener); + return this; }; +/** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to false + * program.option('-p, --pepper', 'add pepper'); + * + * --pepper + * program.pepper + * // => Boolean + * + * // simple boolean defaulting to true + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir <path>', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {String} flags + * @param {String} description + * @param {Function|Mixed} fn or default + * @param {Mixed} defaultValue + * @return {Command} for chaining + * @api public + */ -Writer.prototype.writeInt = function(i, tag) { - if (typeof(i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof(tag) !== 'number') - tag = ASN1.Integer; +Command.prototype.option = function(flags, description, fn, defaultValue) { + var self = this + , option = new Option(flags, description) + , oname = option.name() + , name = camelcase(oname); - var sz = 4; + // default as 3rd arg + if (typeof fn != 'function') { + if (fn instanceof RegExp) { + var regex = fn; + fn = function(val, def) { + var m = regex.exec(val); + return m ? m[0] : def; + } + } + else { + defaultValue = fn; + fn = null; + } + } - while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && - (sz > 1)) { - sz--; - i <<= 8; + // preassign default value only for --no-*, [optional], or <required> + if (false == option.bool || option.optional || option.required) { + // when --no-* we make sure default is true + if (false == option.bool) defaultValue = true; + // preassign only if we have a default + if (undefined !== defaultValue) self[name] = defaultValue; } - if (sz > 4) - throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff'); + // register the option + this.options.push(option); - this._ensure(2 + sz); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = sz; + // when it's passed assign the value + // and conditionally invoke the callback + this.on(oname, function(val) { + // coercion + if (null !== val && fn) val = fn(val, undefined === self[name] + ? defaultValue + : self[name]); - while (sz-- > 0) { - this._buf[this._offset++] = ((i & 0xff000000) >>> 24); - i <<= 8; - } + // unassigned or bool + if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { + // if no value, bool true, and we have a default, then use it! + if (null == val) { + self[name] = option.bool + ? defaultValue || true + : false; + } else { + self[name] = val; + } + } else if (null !== val) { + // reassign + self[name] = val; + } + }); + return this; }; +/** + * Allow unknown options on the command line. + * + * @param {Boolean} arg if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ +Command.prototype.allowUnknownOption = function(arg) { + this._allowUnknownOption = arguments.length === 0 || arg; + return this; +}; -Writer.prototype.writeNull = function() { - this.writeByte(ASN1.Null); - this.writeByte(0x00); -}; +/** + * Parse `argv`, settings options and invoking commands when defined. + * + * @param {Array} argv + * @return {Command} for chaining + * @api public + */ +Command.prototype.parse = function(argv) { + // implicit help + if (this.executables) this.addImplicitHelpCommand(); -Writer.prototype.writeEnumeration = function(i, tag) { - if (typeof(i) !== 'number') - throw new TypeError('argument must be a Number'); - if (typeof(tag) !== 'number') - tag = ASN1.Enumeration; + // store raw args + this.rawArgs = argv; - return this.writeInt(i, tag); -}; + // guess name + this._name = this._name || basename(argv[1], '.js'); + // github-style sub-commands with no sub-command + if (this.executables && argv.length < 3 && !this.defaultExecutable) { + // this user needs help + argv.push('--help'); + } -Writer.prototype.writeBoolean = function(b, tag) { - if (typeof(b) !== 'boolean') - throw new TypeError('argument must be a Boolean'); - if (typeof(tag) !== 'number') - tag = ASN1.Boolean; + // process argv + var parsed = this.parseOptions(this.normalize(argv.slice(2))); + var args = this.args = parsed.args; - this._ensure(3); - this._buf[this._offset++] = tag; - this._buf[this._offset++] = 0x01; - this._buf[this._offset++] = b ? 0xff : 0x00; + var result = this.parseArgs(this.args, parsed.unknown); + + // executable sub-commands + var name = result.args[0]; + if (this._execs[name] && typeof this._execs[name] != "function") { + return this.executeSubCommand(argv, args, parsed.unknown); + } else if (this.defaultExecutable) { + // use the default subcommand + args.unshift(name = this.defaultExecutable); + return this.executeSubCommand(argv, args, parsed.unknown); + } + + return result; }; +/** + * Execute a sub-command executable. + * + * @param {Array} argv + * @param {Array} args + * @param {Array} unknown + * @api private + */ -Writer.prototype.writeString = function(s, tag) { - if (typeof(s) !== 'string') - throw new TypeError('argument must be a string (was: ' + typeof(s) + ')'); - if (typeof(tag) !== 'number') - tag = ASN1.OctetString; +Command.prototype.executeSubCommand = function(argv, args, unknown) { + args = args.concat(unknown); - var len = Buffer.byteLength(s); - this.writeByte(tag); - this.writeLength(len); - if (len) { - this._ensure(len); - this._buf.write(s, this._offset); - this._offset += len; + if (!args.length) this.help(); + if ('help' == args[0] && 1 == args.length) this.help(); + + // <cmd> --help + if ('help' == args[0]) { + args[0] = args[1]; + args[1] = '--help'; } -}; + // executable + var f = argv[1]; + // name of the subcommand, link `pm-install` + var bin = basename(f, '.js') + '-' + args[0]; -Writer.prototype.writeBuffer = function(buf, tag) { - if (typeof(tag) !== 'number') - throw new TypeError('tag must be a number'); - if (!Buffer.isBuffer(buf)) - throw new TypeError('argument must be a buffer'); - this.writeByte(tag); - this.writeLength(buf.length); - this._ensure(buf.length); - buf.copy(this._buf, this._offset, 0, buf.length); - this._offset += buf.length; -}; + // In case of globally installed, get the base dir where executable + // subcommand file should be located at + var baseDir + , link = readlink(f); + // when symbolink is relative path + if (link !== f && link.charAt(0) !== '/') { + link = path.join(dirname(f), link) + } + baseDir = dirname(link); -Writer.prototype.writeStringArray = function(strings) { - if ((!strings instanceof Array)) - throw new TypeError('argument must be an Array[String]'); + // prefer local `./<bin>` to bin in the $PATH + var localBin = path.join(baseDir, bin); - var self = this; - strings.forEach(function(s) { - self.writeString(s); - }); -}; + // whether bin file is a js script with explicit `.js` extension + var isExplicitJS = false; + if (exists(localBin + '.js')) { + bin = localBin + '.js'; + isExplicitJS = true; + } else if (exists(localBin)) { + bin = localBin; + } -// This is really to solve DER cases, but whatever for now -Writer.prototype.writeOID = function(s, tag) { - if (typeof(s) !== 'string') - throw new TypeError('argument must be a string'); - if (typeof(tag) !== 'number') - tag = ASN1.OID; + args = args.slice(1); - if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) - throw new Error('argument is not a valid OID string'); + var proc; + if (process.platform !== 'win32') { + if (isExplicitJS) { + args.unshift(localBin); + // add executable arguments to spawn + args = (process.execArgv || []).concat(args); - function encodeOctet(bytes, octet) { - if (octet < 128) { - bytes.push(octet); - } else if (octet < 16384) { - bytes.push((octet >>> 7) | 0x80); - bytes.push(octet & 0x7F); - } else if (octet < 2097152) { - bytes.push((octet >>> 14) | 0x80); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); - } else if (octet < 268435456) { - bytes.push((octet >>> 21) | 0x80); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); + proc = spawn('node', args, { stdio: 'inherit', customFds: [0, 1, 2] }); } else { - bytes.push(((octet >>> 28) | 0x80) & 0xFF); - bytes.push(((octet >>> 21) | 0x80) & 0xFF); - bytes.push(((octet >>> 14) | 0x80) & 0xFF); - bytes.push(((octet >>> 7) | 0x80) & 0xFF); - bytes.push(octet & 0x7F); + proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }); } + } else { + args.unshift(localBin); + proc = spawn(process.execPath, args, { stdio: 'inherit'}); } - var tmp = s.split('.'); - var bytes = []; - bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); - tmp.slice(2).forEach(function(b) { - encodeOctet(bytes, parseInt(b, 10)); + proc.on('close', process.exit.bind(process)); + proc.on('error', function(err) { + if (err.code == "ENOENT") { + console.error('\n %s(1) does not exist, try --help\n', bin); + } else if (err.code == "EACCES") { + console.error('\n %s(1) not executable. try chmod or run with root\n', bin); + } + process.exit(1); }); - var self = this; - this._ensure(2 + bytes.length); - this.writeByte(tag); - this.writeLength(bytes.length); - bytes.forEach(function(b) { - self.writeByte(b); - }); + // Store the reference to the child process + this.runningCommand = proc; }; +/** + * Normalize `args`, splitting joined short flags. For example + * the arg "-abc" is equivalent to "-a -b -c". + * This also normalizes equal sign and splits "--abc=def" into "--abc def". + * + * @param {Array} args + * @return {Array} + * @api private + */ -Writer.prototype.writeLength = function(len) { - if (typeof(len) !== 'number') - throw new TypeError('argument must be a Number'); +Command.prototype.normalize = function(args) { + var ret = [] + , arg + , lastOpt + , index; - this._ensure(4); + for (var i = 0, len = args.length; i < len; ++i) { + arg = args[i]; + if (i > 0) { + lastOpt = this.optionFor(args[i-1]); + } - if (len <= 0x7f) { - this._buf[this._offset++] = len; - } else if (len <= 0xff) { - this._buf[this._offset++] = 0x81; - this._buf[this._offset++] = len; - } else if (len <= 0xffff) { - this._buf[this._offset++] = 0x82; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else if (len <= 0xffffff) { - this._buf[this._offset++] = 0x83; - this._buf[this._offset++] = len >> 16; - this._buf[this._offset++] = len >> 8; - this._buf[this._offset++] = len; - } else { - throw new InvalidAsn1ERror('Length too long (> 4 bytes)'); + if (arg === '--') { + // Honor option terminator + ret = ret.concat(args.slice(i)); + break; + } else if (lastOpt && lastOpt.required) { + ret.push(arg); + } else if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { + arg.slice(1).split('').forEach(function(c) { + ret.push('-' + c); + }); + } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { + ret.push(arg.slice(0, index), arg.slice(index + 1)); + } else { + ret.push(arg); + } } -}; - -Writer.prototype.startSequence = function(tag) { - if (typeof(tag) !== 'number') - tag = ASN1.Sequence | ASN1.Constructor; - this.writeByte(tag); - this._seq.push(this._offset); - this._ensure(3); - this._offset += 3; + return ret; }; +/** + * Parse command `args`. + * + * When listener(s) are available those + * callbacks are invoked, otherwise the "*" + * event is emitted and those actions are invoked. + * + * @param {Array} args + * @return {Command} for chaining + * @api private + */ -Writer.prototype.endSequence = function() { - var seq = this._seq.pop(); - var start = seq + 3; - var len = this._offset - start; +Command.prototype.parseArgs = function(args, unknown) { + var name; - if (len <= 0x7f) { - this._shift(start, len, -2); - this._buf[seq] = len; - } else if (len <= 0xff) { - this._shift(start, len, -1); - this._buf[seq] = 0x81; - this._buf[seq + 1] = len; - } else if (len <= 0xffff) { - this._buf[seq] = 0x82; - this._buf[seq + 1] = len >> 8; - this._buf[seq + 2] = len; - } else if (len <= 0xffffff) { - this._shift(start, len, 1); - this._buf[seq] = 0x83; - this._buf[seq + 1] = len >> 16; - this._buf[seq + 2] = len >> 8; - this._buf[seq + 3] = len; + if (args.length) { + name = args[0]; + if (this.listeners(name).length) { + this.emit(args.shift(), args, unknown); + } else { + this.emit('*', args); + } } else { - throw new InvalidAsn1Error('Sequence too long'); - } -}; - + outputHelpIfNecessary(this, unknown); -Writer.prototype._shift = function(start, len, shift) { - assert.ok(start !== undefined); - assert.ok(len !== undefined); - assert.ok(shift); + // If there were no args and we have unknown options, + // then they are extraneous and we need to error. + if (unknown.length > 0) { + this.unknownOption(unknown[0]); + } + } - this._buf.copy(this._buf, start + shift, start, start + len); - this._offset += shift; + return this; }; -Writer.prototype._ensure = function(len) { - assert.ok(len); - - if (this._size - this._offset < len) { - var sz = this._size * this._options.growthFactor; - if (sz - this._offset < len) - sz += len; - - var buf = new Buffer(sz); +/** + * Return an option matching `arg` if any. + * + * @param {String} arg + * @return {Option} + * @api private + */ - this._buf.copy(buf, 0, 0, this._offset); - this._buf = buf; - this._size = sz; +Command.prototype.optionFor = function(arg) { + for (var i = 0, len = this.options.length; i < len; ++i) { + if (this.options[i].is(arg)) { + return this.options[i]; + } } }; +/** + * Parse options from `argv` returning `argv` + * void of these options. + * + * @param {Array} argv + * @return {Array} + * @api public + */ +Command.prototype.parseOptions = function(argv) { + var args = [] + , len = argv.length + , literal + , option + , arg; -///--- Exported API + var unknownOptions = []; -module.exports = Writer; + // parse options + for (var i = 0; i < len; ++i) { + arg = argv[i]; + // literal args after -- + if ('--' == arg) { + literal = true; + continue; + } -/***/ }), -/* 324 */ -/***/ (function(module, exports, __webpack_require__) { + if (literal) { + args.push(arg); + continue; + } -module.exports = -{ - parallel : __webpack_require__(326), - serial : __webpack_require__(327), - serialOrdered : __webpack_require__(187) -}; + // find matching Option + option = this.optionFor(arg); + + // option is defined + if (option) { + // requires arg + if (option.required) { + arg = argv[++i]; + if (null == arg) return this.optionMissingArgument(option); + this.emit(option.name(), arg); + // optional arg + } else if (option.optional) { + arg = argv[i+1]; + if (null == arg || ('-' == arg[0] && '-' != arg)) { + arg = null; + } else { + ++i; + } + this.emit(option.name(), arg); + // bool + } else { + this.emit(option.name()); + } + continue; + } + // looks like an option + if (arg.length > 1 && '-' == arg[0]) { + unknownOptions.push(arg); -/***/ }), -/* 325 */ -/***/ (function(module, exports) { + // If the next argument looks like it might be + // an argument for this option, we pass it on. + // If it isn't, then it'll simply be ignored + if (argv[i+1] && '-' != argv[i+1][0]) { + unknownOptions.push(argv[++i]); + } + continue; + } -module.exports = defer; + // arg + args.push(arg); + } + + return { args: args, unknown: unknownOptions }; +}; /** - * Runs provided function on next iteration of the event loop + * Return an object containing options as key-value pairs * - * @param {function} fn - function to run + * @return {Object} + * @api public */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); +Command.prototype.opts = function() { + var result = {} + , len = this.options.length; - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); + for (var i = 0 ; i < len; i++) { + var key = camelcase(this.options[i].name()); + result[key] = key === 'version' ? this._version : this[key]; } -} + return result; +}; +/** + * Argument `name` is missing. + * + * @param {String} name + * @api private + */ -/***/ }), -/* 326 */ -/***/ (function(module, exports, __webpack_require__) { +Command.prototype.missingArgument = function(name) { + console.error(); + console.error(" error: missing required argument `%s'", name); + console.error(); + process.exit(1); +}; -var iterate = __webpack_require__(184) - , initState = __webpack_require__(185) - , terminator = __webpack_require__(186) - ; +/** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {String} option + * @param {String} flag + * @api private + */ -// Public API -module.exports = parallel; +Command.prototype.optionMissingArgument = function(option, flag) { + console.error(); + if (flag) { + console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); + } else { + console.error(" error: option `%s' argument missing", option.flags); + } + console.error(); + process.exit(1); +}; /** - * Runs iterator over provided array elements in parallel + * Unknown option `flag`. * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator + * @param {String} flag + * @api private */ -function parallel(list, iterator, callback) -{ - var state = initState(list); - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } +Command.prototype.unknownOption = function(flag) { + if (this._allowUnknownOption) return; + console.error(); + console.error(" error: unknown option `%s'", flag); + console.error(); + process.exit(1); +}; - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); +/** + * Variadic argument with `name` is not the last argument as required. + * + * @param {String} name + * @api private + */ - state.index++; - } +Command.prototype.variadicArgNotLast = function(name) { + console.error(); + console.error(" error: variadic arguments must be last `%s'", name); + console.error(); + process.exit(1); +}; - return terminator.bind(state, callback); -} +/** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * @param {String} str + * @param {String} flags + * @return {Command} for chaining + * @api public + */ +Command.prototype.version = function(str, flags) { + if (0 == arguments.length) return this._version; + this._version = str; + flags = flags || '-V, --version'; + this.option(flags, 'output the version number'); + this.on('version', function() { + process.stdout.write(str + '\n'); + process.exit(0); + }); + return this; +}; -/***/ }), -/* 327 */ -/***/ (function(module, exports, __webpack_require__) { +/** + * Set the description to `str`. + * + * @param {String} str + * @return {String|Command} + * @api public + */ -var serialOrdered = __webpack_require__(187); +Command.prototype.description = function(str) { + if (0 === arguments.length) return this._description; + this._description = str; + return this; +}; -// Public API -module.exports = serial; +/** + * Set an alias for the command + * + * @param {String} alias + * @return {String|Command} + * @api public + */ + +Command.prototype.alias = function(alias) { + if (0 == arguments.length) return this._alias; + this._alias = alias; + return this; +}; /** - * Runs iterator over provided array elements in series + * Set / get the command usage `str`. * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator + * @param {String} str + * @return {String|Command} + * @api public */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); -} +Command.prototype.usage = function(str) { + var args = this._args.map(function(arg) { + return humanReadableArgName(arg); + }); -/***/ }), -/* 328 */ -/***/ (function(module, exports, __webpack_require__) { + var usage = '[options]' + + (this.commands.length ? ' [command]' : '') + + (this._args.length ? ' ' + args.join(' ') : ''); + if (0 == arguments.length) return this._usage || usage; + this._usage = str; -/*! - * Copyright 2010 LearnBoost <dev@learnboost.com> - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ + return this; +}; /** - * Module dependencies. + * Get the name of the command + * + * @param {String} name + * @return {String|Command} + * @api public */ -var crypto = __webpack_require__(7) - , parse = __webpack_require__(11).parse - ; +Command.prototype.name = function() { + return this._name; +}; /** - * Valid keys. + * Return the largest option length. + * + * @return {Number} + * @api private */ -var keys = - [ 'acl' - , 'location' - , 'logging' - , 'notification' - , 'partNumber' - , 'policy' - , 'requestPayment' - , 'torrent' - , 'uploadId' - , 'uploads' - , 'versionId' - , 'versioning' - , 'versions' - , 'website' - ] +Command.prototype.largestOptionLength = function() { + return this.options.reduce(function(max, option) { + return Math.max(max, option.flags.length); + }, 0); +}; /** - * Return an "Authorization" header value with the given `options` - * in the form of "AWS <key>:<signature>" + * Return help for options. * - * @param {Object} options * @return {String} * @api private */ -function authorization (options) { - return 'AWS ' + options.key + ':' + sign(options) -} +Command.prototype.optionHelp = function() { + var width = this.largestOptionLength(); -module.exports = authorization -module.exports.authorization = authorization + // Prepend the help information + return [pad('-h, --help', width) + ' ' + 'output usage information'] + .concat(this.options.map(function(option) { + return pad(option.flags, width) + ' ' + option.description; + })) + .join('\n'); +}; /** - * Simple HMAC-SHA1 Wrapper + * Return command help documentation. * - * @param {Object} options * @return {String} * @api private - */ + */ -function hmacSha1 (options) { - return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') -} +Command.prototype.commandHelp = function() { + if (!this.commands.length) return ''; -module.exports.hmacSha1 = hmacSha1 + var commands = this.commands.filter(function(cmd) { + return !cmd._noHelp; + }).map(function(cmd) { + var args = cmd._args.map(function(arg) { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._alias ? '|' + cmd._alias : '') + + (cmd.options.length ? ' [options]' : '') + + ' ' + args + , cmd.description() + ]; + }); + + var width = commands.reduce(function(max, command) { + return Math.max(max, command[0].length); + }, 0); + + return [ + '' + , ' Commands:' + , '' + , commands.map(function(cmd) { + var desc = cmd[1] ? ' ' + cmd[1] : ''; + return pad(cmd[0], width) + desc; + }).join('\n').replace(/^/gm, ' ') + , '' + ].join('\n'); +}; /** - * Create a base64 sha1 HMAC for `options`. - * - * @param {Object} options + * Return program help documentation. + * * @return {String} * @api private */ -function sign (options) { - options.message = stringToSign(options) - return hmacSha1(options) -} -module.exports.sign = sign +Command.prototype.helpInformation = function() { + var desc = []; + if (this._description) { + desc = [ + ' ' + this._description + , '' + ]; + } + + var cmdName = this._name; + if (this._alias) { + cmdName = cmdName + '|' + this._alias; + } + var usage = [ + '' + ,' Usage: ' + cmdName + ' ' + this.usage() + , '' + ]; + + var cmds = []; + var commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; + + var options = [ + ' Options:' + , '' + , '' + this.optionHelp().replace(/^/gm, ' ') + , '' + , '' + ]; + + return usage + .concat(cmds) + .concat(desc) + .concat(options) + .join('\n'); +}; /** - * Create a base64 sha1 HMAC for `options`. + * Output help information for this command * - * Specifically to be used with S3 presigned URLs - * - * @param {Object} options - * @return {String} - * @api private + * @api public */ -function signQuery (options) { - options.message = queryStringToSign(options) - return hmacSha1(options) -} -module.exports.signQuery= signQuery +Command.prototype.outputHelp = function(cb) { + if (!cb) { + cb = function(passthru) { + return passthru; + } + } + process.stdout.write(cb(this.helpInformation())); + this.emit('--help'); +}; /** - * Return a string for sign() with the given `options`. + * Output help information and exit. * - * Spec: - * - * <verb>\n - * <md5>\n - * <content-type>\n - * <date>\n - * [headers\n] - * <resource> + * @api public + */ + +Command.prototype.help = function(cb) { + this.outputHelp(cb); + process.exit(); +}; + +/** + * Camel-case the given `flag` * - * @param {Object} options + * @param {String} flag * @return {String} * @api private */ -function stringToSign (options) { - var headers = options.amazonHeaders || '' - if (headers) headers += '\n' - var r = - [ options.verb - , options.md5 - , options.contentType - , options.date ? options.date.toUTCString() : '' - , headers + options.resource - ] - return r.join('\n') +function camelcase(flag) { + return flag.split('-').reduce(function(str, word) { + return str + word[0].toUpperCase() + word.slice(1); + }); } -module.exports.queryStringToSign = stringToSign /** - * Return a string for sign() with the given `options`, but is meant exclusively - * for S3 presigned URLs - * - * Spec: - * - * <date>\n - * <resource> + * Pad `str` to `width`. * - * @param {Object} options + * @param {String} str + * @param {Number} width * @return {String} * @api private */ -function queryStringToSign (options){ - return 'GET\n\n\n' + options.date + '\n' + options.resource +function pad(str, width) { + var len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); } -module.exports.queryStringToSign = queryStringToSign /** - * Perform the following: - * - * - ignore non-amazon headers - * - lowercase fields - * - sort lexicographically - * - trim whitespace between ":" - * - join with newline + * Output help information if necessary * - * @param {Object} headers - * @return {String} + * @param {Command} command to output help for + * @param {Array} array of options to search for -h or --help * @api private */ -function canonicalizeHeaders (headers) { - var buf = [] - , fields = Object.keys(headers) - ; - for (var i = 0, len = fields.length; i < len; ++i) { - var field = fields[i] - , val = headers[field] - , field = field.toLowerCase() - ; - if (0 !== field.indexOf('x-amz')) continue - buf.push(field + ':' + val) +function outputHelpIfNecessary(cmd, options) { + options = options || []; + for (var i = 0; i < options.length; i++) { + if (options[i] == '--help' || options[i] == '-h') { + cmd.outputHelp(); + process.exit(0); + } } - return buf.sort().join('\n') } -module.exports.canonicalizeHeaders = canonicalizeHeaders /** - * Perform the following: - * - * - ignore non sub-resources - * - sort lexicographically + * Takes an argument an returns its human readable equivalent for help usage. * - * @param {String} resource + * @param {Object} arg * @return {String} * @api private */ -function canonicalizeResource (resource) { - var url = parse(resource, true) - , path = url.pathname - , buf = [] - ; +function humanReadableArgName(arg) { + var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); - Object.keys(url.query).forEach(function(key){ - if (!~keys.indexOf(key)) return - var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) - buf.push(key + val) - }) + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']' +} - return path + (buf.length ? '?' + buf.sort().join('&') : '') +// for versions before node v0.8 when there weren't `fs.existsSync` +function exists(file) { + try { + if (fs.statSync(file).isFile()) { + return true; + } + } catch (e) { + return false; + } } -module.exports.canonicalizeResource = canonicalizeResource -/***/ }), -/* 329 */ -/***/ (function(module, exports, __webpack_require__) { -var aws4 = exports, - url = __webpack_require__(11), - querystring = __webpack_require__(114), - crypto = __webpack_require__(7), - lru = __webpack_require__(330), - credentialsCache = lru(1000) +/***/ }), +/* 336 */ +/***/ (function(module, exports) { -// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html -function hmac(key, string, encoding) { - return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) +var defaultConfig = { + uncaughtException: false, + SIGINT: true, + SIGTERM: true, + SIGQUIT: true } -function hash(string, encoding) { - return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) -} +var DEBUG = false -// This function assumes the string has already been percent encoded -function encodeRfc3986(urlEncodedString) { - return urlEncodedString.replace(/[!'()*]/g, function(c) { - return '%' + c.charCodeAt(0).toString(16).toUpperCase() +function ON_DEATH (callback) { + var handlers = []; + Object.keys(defaultConfig).forEach(function(key) { + var val = defaultConfig[key] + var handler = null; + if (val) { + if (DEBUG) { + handler = function() { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift(key) + console.log('Trapped ' + key) + callback.apply(null, args) + }; + process.on(key, handler) + } else { + handler = function() { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift(key) + callback.apply(null, args) + } + process.on(key, handler) + } + handlers.push([key, handler]) + } }) + return function OFF_DEATH() { + handlers.forEach(function (args) { + var key = args[0]; + var handler = args[1]; + process.removeListener(key, handler); + }) + } } -// request: { path | body, [host], [method], [headers], [service], [region] } -// credentials: { accessKeyId, secretAccessKey, [sessionToken] } -function RequestSigner(request, credentials) { +module.exports = function (arg) { + if (typeof arg === 'object') { + if (arg['debug']) + DEBUG = arg.debug + if (arg['DEBUG']) + DEBUG = arg.DEBUG + delete arg.debug; delete arg.DEBUG; - if (typeof request === 'string') request = url.parse(request) + Object.keys(arg).forEach(function(key) { + defaultConfig[key] = arg[key] + }) - var headers = request.headers = (request.headers || {}), - hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host) + if (DEBUG) + console.log('ON_DEATH: debug mode enabled for pid [%d]', process.pid) - this.request = request - this.credentials = credentials || this.defaultCredentials() + return ON_DEATH + } else if (typeof arg === 'function') { + return ON_DEATH(arg) + } +} - this.service = request.service || hostParts[0] || '' - this.region = request.region || hostParts[1] || 'us-east-1' - // SES uses a different domain from the service name - if (this.service === 'email') this.service = 'ses' - if (!request.method && request.body) - request.method = 'POST' +/***/ }), +/* 337 */ +/***/ (function(module, exports, __webpack_require__) { - if (!headers.Host && !headers.host) { - headers.Host = request.hostname || request.host || this.createHost() +"use strict"; - // If a port is specified explicitly, use it as is - if (request.port) - headers.Host += ':' + request.port - } - if (!request.hostname && !request.host) - request.hostname = headers.Host || headers.host +var util = __webpack_require__(2); +var onExit = __webpack_require__(314); +var currentlyUnhandled = __webpack_require__(472); - this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' -} +var installed = false; -RequestSigner.prototype.matchHost = function(host) { - var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/) - var hostParts = (match || []).slice(1, 3) +module.exports = function (log) { + if (installed) { + return; + } - // ES's hostParts are sometimes the other way round, if the value that is expected - // to be region equals ‘es’ switch them back - // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com - if (hostParts[1] === 'es') - hostParts = hostParts.reverse() - - return hostParts -} - -// http://docs.aws.amazon.com/general/latest/gr/rande.html -RequestSigner.prototype.isSingleRegion = function() { - // Special case for S3 and SimpleDB in us-east-1 - if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true - - return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] - .indexOf(this.service) >= 0 -} + installed = true; -RequestSigner.prototype.createHost = function() { - var region = this.isSingleRegion() ? '' : - (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region, - service = this.service === 'ses' ? 'email' : this.service - return service + region + '.amazonaws.com' -} + log = log || console.error; -RequestSigner.prototype.prepareRequest = function() { - this.parsePath() + var listUnhandled = currentlyUnhandled(); - var request = this.request, headers = request.headers, query + onExit(function () { + var unhandledRejections = listUnhandled(); - if (request.signQuery) { + if (unhandledRejections.length > 0) { + unhandledRejections.forEach(function (x) { + var err = x.reason; - this.parsedPath.query = query = this.parsedPath.query || {} + if (!(err instanceof Error)) { + err = new Error('Promise rejected with value: ' + util.inspect(err)); + } - if (this.credentials.sessionToken) - query['X-Amz-Security-Token'] = this.credentials.sessionToken + log(err.stack); + }); - if (this.service === 's3' && !query['X-Amz-Expires']) - query['X-Amz-Expires'] = 86400 + process.exitCode = 1; + } + }); +}; - if (query['X-Amz-Date']) - this.datetime = query['X-Amz-Date'] - else - query['X-Amz-Date'] = this.getDateTime() - query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' - query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() - query['X-Amz-SignedHeaders'] = this.signedHeaders() +/***/ }), +/* 338 */ +/***/ (function(module, exports, __webpack_require__) { - } else { +"use strict"; - if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { - if (request.body && !headers['Content-Type'] && !headers['content-type']) - headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' - if (request.body && !headers['Content-Length'] && !headers['content-length']) - headers['Content-Length'] = Buffer.byteLength(request.body) +const fs = __webpack_require__(289); +const path = __webpack_require__(0); +const retry = __webpack_require__(614); +const syncFs = __webpack_require__(587); - if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) - headers['X-Amz-Security-Token'] = this.credentials.sessionToken +const locks = {}; - if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) - headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') +function getLockFile(file) { + return `${file}.lock`; +} - if (headers['X-Amz-Date'] || headers['x-amz-date']) - this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] - else - headers['X-Amz-Date'] = this.getDateTime() +function canonicalPath(file, options, callback) { + if (!options.realpath) { + return callback(null, path.resolve(file)); } - delete headers.Authorization - delete headers.authorization - } + // Use realpath to resolve symlinks + // It also resolves relative paths + options.fs.realpath(file, callback); } -RequestSigner.prototype.sign = function() { - if (!this.parsedPath) this.prepareRequest() +function acquireLock(file, options, callback) { + // Use mkdir to create the lockfile (atomic operation) + options.fs.mkdir(getLockFile(file), (err) => { + // If successful, we are done + if (!err) { + return callback(); + } - if (this.request.signQuery) { - this.parsedPath.query['X-Amz-Signature'] = this.signature() - } else { - this.request.headers.Authorization = this.authHeader() - } + // If error is not EEXIST then some other error occurred while locking + if (err.code !== 'EEXIST') { + return callback(err); + } - this.request.path = this.formatPath() + // Otherwise, check if lock is stale by analyzing the file mtime + if (options.stale <= 0) { + return callback(Object.assign(new Error('Lock file is already being hold'), { code: 'ELOCKED', file })); + } - return this.request -} + options.fs.stat(getLockFile(file), (err, stat) => { + if (err) { + // Retry if the lockfile has been removed (meanwhile) + // Skip stale check to avoid recursiveness + if (err.code === 'ENOENT') { + return acquireLock(file, Object.assign({}, options, { stale: 0 }), callback); + } -RequestSigner.prototype.getDateTime = function() { - if (!this.datetime) { - var headers = this.request.headers, - date = new Date(headers.Date || headers.date || new Date) + return callback(err); + } - this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') + if (!isLockStale(stat, options)) { + return callback(Object.assign(new Error('Lock file is already being hold'), { code: 'ELOCKED', file })); + } - // Remove the trailing 'Z' on the timestamp string for CodeCommit git access - if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) - } - return this.datetime -} + // If it's stale, remove it and try again! + // Skip stale check to avoid recursiveness + removeLock(file, options, (err) => { + if (err) { + return callback(err); + } -RequestSigner.prototype.getDate = function() { - return this.getDateTime().substr(0, 8) + acquireLock(file, Object.assign({}, options, { stale: 0 }), callback); + }); + }); + }); } -RequestSigner.prototype.authHeader = function() { - return [ - 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), - 'SignedHeaders=' + this.signedHeaders(), - 'Signature=' + this.signature(), - ].join(', ') +function isLockStale(stat, options) { + return stat.mtime.getTime() < Date.now() - options.stale; } -RequestSigner.prototype.signature = function() { - var date = this.getDate(), - cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), - kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) - if (!kCredentials) { - kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) - kRegion = hmac(kDate, this.region) - kService = hmac(kRegion, this.service) - kCredentials = hmac(kService, 'aws4_request') - credentialsCache.set(cacheKey, kCredentials) - } - return hmac(kCredentials, this.stringToSign(), 'hex') -} +function removeLock(file, options, callback) { + // Remove lockfile, ignoring ENOENT errors + options.fs.rmdir(getLockFile(file), (err) => { + if (err && err.code !== 'ENOENT') { + return callback(err); + } -RequestSigner.prototype.stringToSign = function() { - return [ - 'AWS4-HMAC-SHA256', - this.getDateTime(), - this.credentialString(), - hash(this.canonicalString(), 'hex'), - ].join('\n') + callback(); + }); } -RequestSigner.prototype.canonicalString = function() { - if (!this.parsedPath) this.prepareRequest() - - var pathStr = this.parsedPath.path, - query = this.parsedPath.query, - headers = this.request.headers, - queryStr = '', - normalizePath = this.service !== 's3', - decodePath = this.service === 's3' || this.request.doNotEncodePath, - decodeSlashesInPath = this.service === 's3', - firstValOnly = this.service === 's3', - bodyHash +function updateLock(file, options) { + const lock = locks[file]; - if (this.service === 's3' && this.request.signQuery) { - bodyHash = 'UNSIGNED-PAYLOAD' - } else if (this.isCodeCommitGit) { - bodyHash = '' - } else { - bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || - hash(this.request.body || '', 'hex') - } + /* istanbul ignore next */ + if (lock.updateTimeout) { + return; + } - if (query) { - queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) { - if (!key) return obj - obj[key] = !Array.isArray(query[key]) ? query[key] : - (firstValOnly ? query[key][0] : query[key].slice().sort()) - return obj - }, {}))) - } - if (pathStr !== '/') { - if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') - pathStr = pathStr.split('/').reduce(function(path, piece) { - if (normalizePath && piece === '..') { - path.pop() - } else if (!normalizePath || piece !== '.') { - if (decodePath) piece = querystring.unescape(piece) - path.push(encodeRfc3986(querystring.escape(piece))) - } - return path - }, []).join('/') - if (pathStr[0] !== '/') pathStr = '/' + pathStr - if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') - } + lock.updateDelay = lock.updateDelay || options.update; + lock.updateTimeout = setTimeout(() => { + const mtime = Date.now() / 1000; - return [ - this.request.method || 'GET', - pathStr, - queryStr, - this.canonicalHeaders() + '\n', - this.signedHeaders(), - bodyHash, - ].join('\n') -} + lock.updateTimeout = null; -RequestSigner.prototype.canonicalHeaders = function() { - var headers = this.request.headers - function trimAll(header) { - return header.toString().trim().replace(/\s+/g, ' ') - } - return Object.keys(headers) - .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) - .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) - .join('\n') -} + options.fs.utimes(getLockFile(file), mtime, mtime, (err) => { + // Ignore if the lock was released + if (lock.released) { + return; + } -RequestSigner.prototype.signedHeaders = function() { - return Object.keys(this.request.headers) - .map(function(key) { return key.toLowerCase() }) - .sort() - .join(';') -} + // Verify if we are within the stale threshold + if (lock.lastUpdate <= Date.now() - options.stale && + lock.lastUpdate > Date.now() - options.stale * 2) { + return compromisedLock(file, lock, Object.assign(new Error(lock.updateError || 'Unable to update lock within the stale \ +threshold'), { code: 'ECOMPROMISED' })); + } -RequestSigner.prototype.credentialString = function() { - return [ - this.getDate(), - this.region, - this.service, - 'aws4_request', - ].join('/') -} + // If the file is older than (stale * 2), we assume the clock is moved manually, + // which we consider a valid case -RequestSigner.prototype.defaultCredentials = function() { - var env = process.env - return { - accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, - secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, - sessionToken: env.AWS_SESSION_TOKEN, - } -} + // If it failed to update the lockfile, keep trying unless + // the lockfile was deleted! + if (err) { + if (err.code === 'ENOENT') { + return compromisedLock(file, lock, Object.assign(err, { code: 'ECOMPROMISED' })); + } -RequestSigner.prototype.parsePath = function() { - var path = this.request.path || '/', - queryIx = path.indexOf('?'), - query = null + lock.updateError = err; + lock.updateDelay = 1000; + return updateLock(file, options); + } - if (queryIx >= 0) { - query = querystring.parse(path.slice(queryIx + 1)) - path = path.slice(0, queryIx) - } + // All ok, keep updating.. + lock.lastUpdate = Date.now(); + lock.updateError = null; + lock.updateDelay = null; + updateLock(file, options); + }); + }, lock.updateDelay); - // S3 doesn't always encode characters > 127 correctly and - // all services don't encode characters > 255 correctly - // So if there are non-reserved chars (and it's not already all % encoded), just encode them all - if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) { - path = path.split('/').map(function(piece) { - return querystring.escape(querystring.unescape(piece)) - }).join('/') - } + // Unref the timer so that the nodejs process can exit freely + // This is safe because all acquired locks will be automatically released + // on process exit - this.parsedPath = { - path: path, - query: query, - } + // We first check that `lock.updateTimeout.unref` exists because some users + // may be using this module outside of NodeJS (e.g., in an electron app), + // and in those cases `setTimeout` return an integer. + if (lock.updateTimeout.unref) { + lock.updateTimeout.unref(); + } } -RequestSigner.prototype.formatPath = function() { - var path = this.parsedPath.path, - query = this.parsedPath.query - - if (!query) return path - - // Services don't support empty query string keys - if (query[''] != null) delete query[''] - - return path + '?' + encodeRfc3986(querystring.stringify(query)) -} +function compromisedLock(file, lock, err) { + lock.released = true; // Signal the lock has been released + /* istanbul ignore next */ + lock.updateTimeout && clearTimeout(lock.updateTimeout); // Cancel lock mtime update -aws4.RequestSigner = RequestSigner + if (locks[file] === lock) { + delete locks[file]; + } -aws4.sign = function(request, credentials) { - return new RequestSigner(request, credentials).sign() + lock.compromised(err); } +// ----------------------------------------- -/***/ }), -/* 330 */ -/***/ (function(module, exports) { +function lock(file, options, compromised, callback) { + if (typeof options === 'function') { + callback = compromised; + compromised = options; + options = null; + } -module.exports = function(size) { - return new LruCache(size) -} + if (!callback) { + callback = compromised; + compromised = null; + } -function LruCache(size) { - this.capacity = size | 0 - this.map = Object.create(null) - this.list = new DoublyLinkedList() -} + options = Object.assign({ + stale: 10000, + update: null, + realpath: true, + retries: 0, + fs, + }, options); -LruCache.prototype.get = function(key) { - var node = this.map[key] - if (node == null) return undefined - this.used(node) - return node.val -} + options.retries = options.retries || 0; + options.retries = typeof options.retries === 'number' ? { retries: options.retries } : options.retries; + options.stale = Math.max(options.stale || 0, 2000); + options.update = options.update == null ? options.stale / 2 : options.update || 0; + options.update = Math.max(Math.min(options.update, options.stale / 2), 1000); + compromised = compromised || function (err) { throw err; }; -LruCache.prototype.set = function(key, val) { - var node = this.map[key] - if (node != null) { - node.val = val - } else { - if (!this.capacity) this.prune() - if (!this.capacity) return false - node = new DoublyLinkedNode(key, val) - this.map[key] = node - this.capacity-- - } - this.used(node) - return true -} + // Resolve to a canonical file path + canonicalPath(file, options, (err, file) => { + if (err) { + return callback(err); + } -LruCache.prototype.used = function(node) { - this.list.moveToFront(node) -} + // Attempt to acquire the lock + const operation = retry.operation(options.retries); -LruCache.prototype.prune = function() { - var node = this.list.pop() - if (node != null) { - delete this.map[node.key] - this.capacity++ - } -} + operation.attempt(() => { + acquireLock(file, options, (err) => { + if (operation.retry(err)) { + return; + } + if (err) { + return callback(operation.mainError()); + } -function DoublyLinkedList() { - this.firstNode = null - this.lastNode = null -} + // We now own the lock + const lock = locks[file] = { + options, + compromised, + lastUpdate: Date.now(), + }; -DoublyLinkedList.prototype.moveToFront = function(node) { - if (this.firstNode == node) return + // We must keep the lock fresh to avoid staleness + updateLock(file, options); - this.remove(node) + callback(null, (releasedCallback) => { + if (lock.released) { + return releasedCallback && + releasedCallback(Object.assign(new Error('Lock is already released'), { code: 'ERELEASED' })); + } - if (this.firstNode == null) { - this.firstNode = node - this.lastNode = node - node.prev = null - node.next = null - } else { - node.prev = null - node.next = this.firstNode - node.next.prev = node - this.firstNode = node - } + // Not necessary to use realpath twice when unlocking + unlock(file, Object.assign({}, options, { realpath: false }), releasedCallback); + }); + }); + }); + }); } -DoublyLinkedList.prototype.pop = function() { - var lastNode = this.lastNode - if (lastNode != null) { - this.remove(lastNode) - } - return lastNode -} +function unlock(file, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } -DoublyLinkedList.prototype.remove = function(node) { - if (this.firstNode == node) { - this.firstNode = node.next - } else if (node.prev != null) { - node.prev.next = node.next - } - if (this.lastNode == node) { - this.lastNode = node.prev - } else if (node.next != null) { - node.next.prev = node.prev - } -} + options = Object.assign({ + fs, + realpath: true, + }, options); + callback = callback || function () {}; -function DoublyLinkedNode(key, val) { - this.key = key - this.val = val - this.prev = null - this.next = null -} + // Resolve to a canonical file path + canonicalPath(file, options, (err, file) => { + if (err) { + return callback(err); + } + // Skip if the lock is not acquired + const lock = locks[file]; -/***/ }), -/* 331 */ -/***/ (function(module, exports, __webpack_require__) { + if (!lock) { + return callback(Object.assign(new Error('Lock is not acquired/owned by you'), { code: 'ENOTACQUIRED' })); + } -"use strict"; + lock.updateTimeout && clearTimeout(lock.updateTimeout); // Cancel lock mtime update + lock.released = true; // Signal the lock has been released + delete locks[file]; // Delete from locks + removeLock(file, options, callback); + }); +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = { - 'upgrade-interactive': 'upgradeInteractive', - 'generate-lock-entry': 'generateLockEntry' -}; +function lockSync(file, options, compromised) { + if (typeof options === 'function') { + compromised = options; + options = null; + } -/***/ }), -/* 332 */ -/***/ (function(module, exports, __webpack_require__) { + options = options || {}; + options.fs = syncFs(options.fs || fs); + options.retries = options.retries || 0; + options.retries = typeof options.retries === 'number' ? { retries: options.retries } : options.retries; -"use strict"; + // Retries are not allowed because it requires the flow to be sync + if (options.retries.retries) { + throw Object.assign(new Error('Cannot use retries with the sync api'), { code: 'ESYNC' }); + } + let err; + let release; -Object.defineProperty(exports, "__esModule", { - value: true -}); + lock(file, options, compromised, (_err, _release) => { + err = _err; + release = _release; + }); -exports.default = function (message) { - return { - useless: true, - run() { - throw new (_errors || _load_errors()).MessageError(message); - }, - setFlags: () => {}, - hasWrapper: () => true - }; -}; + if (err) { + throw err; + } -var _errors; + return release; +} -function _load_errors() { - return _errors = __webpack_require__(3); +function unlockSync(file, options) { + options = options || {}; + options.fs = syncFs(options.fs || fs); + + let err; + + unlock(file, options, (_err) => { + err = _err; + }); + + if (err) { + throw err; + } } -/***/ }), -/* 333 */ -/***/ (function(module, exports, __webpack_require__) { +function check(file, options, callback) { + if (typeof options === 'function') { + callback = options; + options = null; + } -"use strict"; + options = Object.assign({ + stale: 10000, + realpath: true, + fs, + }, options); + options.stale = Math.max(options.stale || 0, 2000); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.examples = exports.hasWrapper = exports.setFlags = exports.run = undefined; + // Resolve to a canonical file path + canonicalPath(file, options, (err, file) => { + if (err) { + return callback(err); + } -var _buildSubCommands2; + // Check if lockfile exists + options.fs.stat(getLockFile(file), (err, stat) => { + if (err) { + // if does not exist, file is not locked. Otherwise, callback with error + return (err.code === 'ENOENT') ? callback(null, false) : callback(err); + } -function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); + if (options.stale <= 0) { return callback(null, true); } + + // Otherwise, check if lock is stale by analyzing the file mtime + return callback(null, !isLockStale(stat, options)); + }); + }); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function checkSync(file, options) { + options = options || {}; + options.fs = syncFs(options.fs || fs); -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('access', { - public() { - return Promise.reject(new Error('TODO')); - }, + let err; + let locked; - restricted() { - return Promise.reject(new Error('TODO')); - }, + check(file, options, (_err, _locked) => { + err = _err; + locked = _locked; + }); - grant() { - return Promise.reject(new Error('TODO')); - }, + if (err) { + throw err; + } - revoke() { - return Promise.reject(new Error('TODO')); - }, + return locked; +} - lsPackages() { - return Promise.reject(new Error('TODO')); - }, - lsCollaborators() { - return Promise.reject(new Error('TODO')); - }, +// Remove acquired locks on exit +/* istanbul ignore next */ +process.on('exit', () => { + Object.keys(locks).forEach((file) => { + try { locks[file].options.fs.rmdirSync(getLockFile(file)); } catch (e) { /* empty */ } + }); +}); - edit() { - return Promise.reject(new Error('TODO')); - } -}, ['access public [<package>]', 'access restricted [<package>]', 'access grant <read-only|read-write> <scope:team> [<package>]', 'access revoke <scope:team> [<package>]', 'access ls-packages [<user>|<scope>|<scope:team>]', 'access ls-collaborators [<package> [<user>]]', 'access edit [<package>]']); +module.exports = lock; +module.exports.lock = lock; +module.exports.unlock = unlock; +module.exports.lockSync = lockSync; +module.exports.unlockSync = unlockSync; +module.exports.check = check; +module.exports.checkSync = checkSync; -const run = _buildSubCommands.run, - setFlags = _buildSubCommands.setFlags, - hasWrapper = _buildSubCommands.hasWrapper, - examples = _buildSubCommands.examples; -exports.run = run; -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; -exports.examples = examples; /***/ }), -/* 334 */ +/* 339 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; -exports.run = run; - -var _yarnResolver; +var compileSchema = __webpack_require__(344) + , resolve = __webpack_require__(237) + , Cache = __webpack_require__(340) + , SchemaObject = __webpack_require__(238) + , stableStringify = __webpack_require__(217) + , formats = __webpack_require__(343) + , rules = __webpack_require__(345) + , v5 = __webpack_require__(369) + , util = __webpack_require__(60) + , async = __webpack_require__(235) + , co = __webpack_require__(280); -function _load_yarnResolver() { - return _yarnResolver = _interopRequireDefault(__webpack_require__(205)); -} +module.exports = Ajv; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Ajv.prototype.compileAsync = async.compile; -const path = __webpack_require__(1); +var customKeyword = __webpack_require__(366); +Ajv.prototype.addKeyword = customKeyword.add; +Ajv.prototype.getKeyword = customKeyword.get; +Ajv.prototype.removeKeyword = customKeyword.remove; +Ajv.ValidationError = __webpack_require__(239); -function hasWrapper(commander) { - return false; +var META_SCHEMA_ID = 'http://json-schema.org/draft-04/schema'; +var SCHEMA_URI_FORMAT = /^(?:(?:[a-z][a-z0-9+-.]*:)?\/\/)?[^\s]*$/i; +function SCHEMA_URI_FORMAT_FUNC(str) { + return SCHEMA_URI_FORMAT.test(str); } -function setFlags(commander) {} +var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes' ]; -function run(config, reporter, flags, args) { - const binFolder = path.join(config.cwd, config.registries[(_yarnResolver || _load_yarnResolver()).default.registry].folder, '.bin'); - console.log(binFolder); - return Promise.resolve(); -} +/** + * Creates validator instance. + * Usage: `Ajv(opts)` + * @param {Object} opts optional options + * @return {Object} ajv instance + */ +function Ajv(opts) { + if (!(this instanceof Ajv)) return new Ajv(opts); + var self = this; -/***/ }), -/* 335 */ -/***/ (function(module, exports, __webpack_require__) { + opts = this._opts = util.copy(opts) || {}; + this._schemas = {}; + this._refs = {}; + this._fragments = {}; + this._formats = formats(opts.format); + this._cache = opts.cache || new Cache; + this._loadingSchemas = {}; + this._compilations = []; + this.RULES = rules(); -"use strict"; + // this is done on purpose, so that methods are bound to the instance + // (without using bind) so that they can be used without the instance + this.validate = validate; + this.compile = compile; + this.addSchema = addSchema; + this.addMetaSchema = addMetaSchema; + this.validateSchema = validateSchema; + this.getSchema = getSchema; + this.removeSchema = removeSchema; + this.addFormat = addFormat; + this.errorsText = errorsText; + this._addSchema = _addSchema; + this._compile = _compile; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.examples = exports.setFlags = exports.run = undefined; + opts.loopRequired = opts.loopRequired || Infinity; + if (opts.async || opts.transpile) async.setup(opts); + if (opts.beautify === true) opts.beautify = { indent_size: 2 }; + if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; + this._metaOpts = getMetaSchemaOptions(); -var _asyncToGenerator2; + if (opts.formats) addInitialFormats(); + addDraft4MetaSchema(); + if (opts.v5) v5.enable(this); + if (typeof opts.meta == 'object') addMetaSchema(opts.meta); + addInitialSchemas(); -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} -exports.hasWrapper = hasWrapper; + /** + * Validate data using schema + * Schema will be compiled and cached (using serialized JSON as key. [json-stable-stringify](https://github.com/substack/json-stable-stringify) is used to serialize. + * @param {String|Object} schemaKeyRef key, ref or schema object + * @param {Any} data to be validated + * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). + */ + function validate(schemaKeyRef, data) { + var v; + if (typeof schemaKeyRef == 'string') { + v = getSchema(schemaKeyRef); + if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); + } else { + var schemaObj = _addSchema(schemaKeyRef); + v = schemaObj.validate || _compile(schemaObj); + } -var _buildSubCommands2; + var valid = v(data); + if (v.$async === true) + return self._opts.async == '*' ? co(valid) : valid; + self.errors = v.errors; + return valid; + } -function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); -} -var _fs; + /** + * Create validating function for passed schema. + * @param {Object} schema schema object + * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. + * @return {Function} validating function + */ + function compile(schema, _meta) { + var schemaObj = _addSchema(schema, undefined, _meta); + return schemaObj.validate || _compile(schemaObj); + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} -var _constants; + /** + * Adds schema to the instance. + * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. + * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. + * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. + * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. + */ + function addSchema(schema, key, _skipValidation, _meta) { + if (Array.isArray(schema)){ + for (var i=0; i<schema.length; i++) addSchema(schema[i], undefined, _skipValidation, _meta); + return; + } + // can key/id have # inside? + key = resolve.normalizeId(key || schema.id); + checkUnique(key); + self._schemas[key] = _addSchema(schema, _skipValidation, _meta, true); + } -function _load_constants() { - return _constants = __webpack_require__(8); -} -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + /** + * Add schema that will be used to validate other schemas + * options in META_IGNORE_OPTIONS are alway set to false + * @param {Object} schema schema object + * @param {String} key optional schema key + * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema + */ + function addMetaSchema(schema, key, skipValidation) { + addSchema(schema, key, skipValidation, true); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const path = __webpack_require__(1); + /** + * Validate schema + * @param {Object} schema schema to validate + * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid + * @return {Boolean} true if schema is valid + */ + function validateSchema(schema, throwOrLogError) { + var $schema = schema.$schema || self._opts.defaultMeta || defaultMeta(); + var currentUriFormat = self._formats.uri; + self._formats.uri = typeof currentUriFormat == 'function' + ? SCHEMA_URI_FORMAT_FUNC + : SCHEMA_URI_FORMAT; + var valid; + try { valid = validate($schema, schema); } + finally { self._formats.uri = currentUriFormat; } + if (!valid && throwOrLogError) { + var message = 'schema is invalid: ' + errorsText(); + if (self._opts.validateSchema == 'log') console.error(message); + else throw new Error(message); + } + return valid; + } -function hasWrapper(flags, args) { - return args[0] !== 'dir'; -} -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('cache', { - ls(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let readCacheMetadata = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let parentDir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : config.cacheFolder; - let metadataFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_constants || _load_constants()).METADATA_FILENAME; + function defaultMeta() { + var meta = self._opts.meta; + self._opts.defaultMeta = typeof meta == 'object' + ? meta.id || meta + : self._opts.v5 + ? v5.META_SCHEMA_ID + : META_SCHEMA_ID; + return self._opts.defaultMeta; + } - const folders = yield (_fs || _load_fs()).readdir(parentDir); - const packagesMetadata = []; - for (const folder of folders) { - if (folder[0] === '.') { - continue; - } + /** + * Get compiled schema from the instance by `key` or `ref`. + * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). + * @return {Function} schema validating function (with property `schema`). + */ + function getSchema(keyRef) { + var schemaObj = _getSchemaObj(keyRef); + switch (typeof schemaObj) { + case 'object': return schemaObj.validate || _compile(schemaObj); + case 'string': return getSchema(schemaObj); + case 'undefined': return _getSchemaFragment(keyRef); + } + } - const loc = path.join(config.cacheFolder, parentDir.replace(config.cacheFolder, ''), folder); - // Check if this is a scoped package - if (!(yield (_fs || _load_fs()).exists(path.join(loc, metadataFile)))) { - // If so, recurrently read scoped packages metadata - packagesMetadata.push(...(yield readCacheMetadata(loc))); - } else { - var _ref2 = yield config.readPackageMetadata(loc); - const registry = _ref2.registry, - manifest = _ref2.package, - remote = _ref2.remote; + function _getSchemaFragment(ref) { + var res = resolve.schema.call(self, { schema: {} }, ref); + if (res) { + var schema = res.schema + , root = res.root + , baseId = res.baseId; + var v = compileSchema.call(self, schema, root, undefined, baseId); + self._fragments[ref] = new SchemaObject({ + ref: ref, + fragment: true, + schema: schema, + root: root, + baseId: baseId, + validate: v + }); + return v; + } + } - packagesMetadata.push([manifest.name, manifest.version, registry, remote && remote.resolved || '']); - } - } - return packagesMetadata; - }); + function _getSchemaObj(keyRef) { + keyRef = resolve.normalizeId(keyRef); + return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; + } - return function readCacheMetadata() { - return _ref.apply(this, arguments); - }; - })(); - const body = yield readCacheMetadata(); + /** + * Remove cached schema(s). + * If no parameter is passed all schemas but meta-schemas are removed. + * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. + * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. + * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object + */ + function removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + _removeAllSchemas(self._schemas, schemaKeyRef); + _removeAllSchemas(self._refs, schemaKeyRef); + return; + } + switch (typeof schemaKeyRef) { + case 'undefined': + _removeAllSchemas(self._schemas); + _removeAllSchemas(self._refs); + self._cache.clear(); + return; + case 'string': + var schemaObj = _getSchemaObj(schemaKeyRef); + if (schemaObj) self._cache.del(schemaObj.jsonStr); + delete self._schemas[schemaKeyRef]; + delete self._refs[schemaKeyRef]; + return; + case 'object': + var jsonStr = stableStringify(schemaKeyRef); + self._cache.del(jsonStr); + var id = schemaKeyRef.id; + if (id) { + id = resolve.normalizeId(id); + delete self._schemas[id]; + delete self._refs[id]; + } + } + } - reporter.table(['Name', 'Version', 'Registry', 'Resolved'], body); - })(); - }, - dir(config, reporter) { - reporter.log(config.cacheFolder); - }, + function _removeAllSchemas(schemas, regex) { + for (var keyRef in schemas) { + var schemaObj = schemas[keyRef]; + if (!schemaObj.meta && (!regex || regex.test(keyRef))) { + self._cache.del(schemaObj.jsonStr); + delete schemas[keyRef]; + } + } + } - clean(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let getPackageCachefolders = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (packageName) { - let parentDir = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : config.cacheFolder; - let metadataFile = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (_constants || _load_constants()).METADATA_FILENAME; - const folders = yield (_fs || _load_fs()).readdir(parentDir); - const packageFolders = []; + function _addSchema(schema, skipValidation, meta, shouldAddSchema) { + if (typeof schema != 'object') throw new Error('schema should be object'); + var jsonStr = stableStringify(schema); + var cached = self._cache.get(jsonStr); + if (cached) return cached; - for (const folder of folders) { - if (folder[0] === '.') { - continue; - } + shouldAddSchema = shouldAddSchema || self._opts.addUsedSchema !== false; - const loc = path.join(config.cacheFolder, parentDir.replace(config.cacheFolder, ''), folder); - // Check if this is a scoped package - if (!(yield (_fs || _load_fs()).exists(path.join(loc, metadataFile)))) { - // If so, recurrently read scoped packages metadata - packageFolders.push(...(yield getPackageCachefolders(packageName, loc))); - } else { - var _ref4 = yield config.readPackageMetadata(loc); + var id = resolve.normalizeId(schema.id); + if (id && shouldAddSchema) checkUnique(id); - const manifest = _ref4.package; + var willValidate = self._opts.validateSchema !== false && !skipValidation; + var recursiveMeta; + if (willValidate && !(recursiveMeta = schema.id && schema.id == schema.$schema)) + validateSchema(schema, true); - if (packageName === manifest.name) { - packageFolders.push(loc); - } - } - } + var localRefs = resolve.ids.call(self, schema); - return packageFolders; - }); + var schemaObj = new SchemaObject({ + id: id, + schema: schema, + localRefs: localRefs, + jsonStr: jsonStr, + meta: meta + }); - return function getPackageCachefolders(_x3) { - return _ref3.apply(this, arguments); - }; - })(); + if (id[0] != '#' && shouldAddSchema) self._refs[id] = schemaObj; + self._cache.put(jsonStr, schemaObj); - if (config.cacheFolder) { - const activity = reporter.activity(); + if (willValidate && recursiveMeta) validateSchema(schema, true); - if (args.length > 0) { - // Clear named package from cache - const folders = yield getPackageCachefolders(args[0]); + return schemaObj; + } - if (folders.length === 0) { - activity.end(); - reporter.warn(reporter.lang('couldntClearPackageFromCache', args[0])); - return; - } - for (const folder of folders) { - yield (_fs || _load_fs()).unlink(folder); - } - activity.end(); - reporter.success(reporter.lang('clearedPackageFromCache', args[0])); - } else { - // Clear all cache - yield (_fs || _load_fs()).unlink(config._cacheRootFolder); - yield (_fs || _load_fs()).mkdirp(config.cacheFolder); - activity.end(); - reporter.success(reporter.lang('clearedCache')); - } - } - })(); + function _compile(schemaObj, root) { + if (schemaObj.compiling) { + schemaObj.validate = callValidate; + callValidate.schema = schemaObj.schema; + callValidate.errors = null; + callValidate.root = root ? root : callValidate; + if (schemaObj.schema.$async === true) + callValidate.$async = true; + return callValidate; + } + schemaObj.compiling = true; + + var currentOpts; + if (schemaObj.meta) { + currentOpts = self._opts; + self._opts = self._metaOpts; + } + + var v; + try { v = compileSchema.call(self, schemaObj.schema, root, schemaObj.localRefs); } + finally { + schemaObj.compiling = false; + if (schemaObj.meta) self._opts = currentOpts; + } + + schemaObj.validate = v; + schemaObj.refs = v.refs; + schemaObj.refVal = v.refVal; + schemaObj.root = v.root; + return v; + + + function callValidate() { + var _validate = schemaObj.validate; + var result = _validate.apply(null, arguments); + callValidate.errors = _validate.errors; + return result; + } } -}); -const run = _buildSubCommands.run, - setFlags = _buildSubCommands.setFlags, - examples = _buildSubCommands.examples; -exports.run = run; -exports.setFlags = setFlags; -exports.examples = examples; + + /** + * Convert array of error message objects to string + * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used. + * @param {Object} options optional options with properties `separator` and `dataVar`. + * @return {String} human readable string with all errors descriptions + */ + function errorsText(errors, options) { + errors = errors || self.errors; + if (!errors) return 'No errors'; + options = options || {}; + var separator = options.separator === undefined ? ', ' : options.separator; + var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; + + var text = ''; + for (var i=0; i<errors.length; i++) { + var e = errors[i]; + if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; + } + return text.slice(0, -separator.length); + } + + + /** + * Add custom format + * @param {String} name format name + * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) + */ + function addFormat(name, format) { + if (typeof format == 'string') format = new RegExp(format); + self._formats[name] = format; + } + + + function addDraft4MetaSchema() { + if (self._opts.meta !== false) { + var metaSchema = __webpack_require__(367); + addMetaSchema(metaSchema, META_SCHEMA_ID, true); + self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; + } + } + + + function addInitialSchemas() { + var optsSchemas = self._opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) addSchema(optsSchemas); + else for (var key in optsSchemas) addSchema(optsSchemas[key], key); + } + + + function addInitialFormats() { + for (var name in self._opts.formats) { + var format = self._opts.formats[name]; + addFormat(name, format); + } + } + + + function checkUnique(id) { + if (self._schemas[id] || self._refs[id]) + throw new Error('schema with key or id "' + id + '" already exists'); + } + + + function getMetaSchemaOptions() { + var metaOpts = util.copy(self._opts); + for (var i=0; i<META_IGNORE_OPTIONS.length; i++) + delete metaOpts[META_IGNORE_OPTIONS[i]]; + return metaOpts; + } +} + + +/***/ }), +/* 340 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + + +var Cache = module.exports = function Cache() { + this._cache = {}; +}; + + +Cache.prototype.put = function Cache_put(key, value) { + this._cache[key] = value; +}; + + +Cache.prototype.get = function Cache_get(key) { + return this._cache[key]; +}; + + +Cache.prototype.del = function Cache_del(key) { + delete this._cache[key]; +}; + + +Cache.prototype.clear = function Cache_clear() { + this._cache = {}; +}; + + +/***/ }), +/* 341 */ +/***/ (function(module, exports) { + +function webpackEmptyContext(req) { + throw new Error("Cannot find module '" + req + "'."); +} +webpackEmptyContext.keys = function() { return []; }; +webpackEmptyContext.resolve = webpackEmptyContext; +module.exports = webpackEmptyContext; +webpackEmptyContext.id = 341; + +/***/ }), +/* 342 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +//all requires must be explicit because browserify won't work with dynamic requires +module.exports = { + '$ref': __webpack_require__(362), + allOf: __webpack_require__(348), + anyOf: __webpack_require__(349), + dependencies: __webpack_require__(352), + 'enum': __webpack_require__(353), + format: __webpack_require__(354), + items: __webpack_require__(355), + maximum: __webpack_require__(240), + minimum: __webpack_require__(240), + maxItems: __webpack_require__(241), + minItems: __webpack_require__(241), + maxLength: __webpack_require__(242), + minLength: __webpack_require__(242), + maxProperties: __webpack_require__(243), + minProperties: __webpack_require__(243), + multipleOf: __webpack_require__(356), + not: __webpack_require__(357), + oneOf: __webpack_require__(358), + pattern: __webpack_require__(359), + properties: __webpack_require__(361), + required: __webpack_require__(363), + uniqueItems: __webpack_require__(365), + validate: __webpack_require__(244) +}; + + +/***/ }), +/* 343 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var util = __webpack_require__(60); + +var DATE = /^\d\d\d\d-(\d\d)-(\d\d)$/; +var DAYS = [0,31,29,31,30,31,30,31,31,30,31,30,31]; +var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i; +var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i; +var URI = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?(?:\#(?:[a-z0-9\-._~!$&'()*+,;=:@\/?]|%[0-9a-f]{2})*)?$/i; +var UUID = /^(?:urn\:uuid\:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +var JSON_POINTER = /^(?:\/(?:[^~\/]|~0|~1)*)*$|^\#(?:\/(?:[a-z0-9_\-\.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:\#|(?:\/(?:[^~\/]|~0|~1)*)*)$/; + + +module.exports = formats; + +function formats(mode) { + mode = mode == 'full' ? 'full' : 'fast'; + var formatDefs = util.copy(formats[mode]); + for (var fName in formats.compare) { + formatDefs[fName] = { + validate: formatDefs[fName], + compare: formats.compare[fName] + }; + } + return formatDefs; +} + + +formats.fast = { + // date: http://tools.ietf.org/html/rfc3339#section-5.6 + date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, + // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 + time: /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i, + 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i, + // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js + uri: /^(?:[a-z][a-z0-9+-.]*)?(?:\:|\/)\/?[^\s]*$/i, + // email (sources from jsen validator): + // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 + // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') + email: /^[a-z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, + hostname: HOSTNAME, + // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + // uuid: http://tools.ietf.org/html/rfc4122 + uuid: UUID, + // JSON-pointer: https://tools.ietf.org/html/rfc6901 + // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A + 'json-pointer': JSON_POINTER, + // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.full = { + date: date, + time: time, + 'date-time': date_time, + uri: uri, + email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&''*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: hostname, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, + ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, + regex: regex, + uuid: UUID, + 'json-pointer': JSON_POINTER, + 'relative-json-pointer': RELATIVE_JSON_POINTER +}; + + +formats.compare = { + date: compareDate, + time: compareTime, + 'date-time': compareDateTime +}; + + +function date(str) { + // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 + var matches = str.match(DATE); + if (!matches) return false; + + var month = +matches[1]; + var day = +matches[2]; + return month >= 1 && month <= 12 && day >= 1 && day <= DAYS[month]; +} + + +function time(str, full) { + var matches = str.match(TIME); + if (!matches) return false; + + var hour = matches[1]; + var minute = matches[2]; + var second = matches[3]; + var timeZone = matches[5]; + return hour <= 23 && minute <= 59 && second <= 59 && (!full || timeZone); +} + + +var DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + // http://tools.ietf.org/html/rfc3339#section-5.6 + var dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); +} + + +function hostname(str) { + // https://tools.ietf.org/html/rfc1034#section-3.5 + // https://tools.ietf.org/html/rfc1123#section-2 + return str.length <= 255 && HOSTNAME.test(str); +} + + +var NOT_URI_FRAGMENT = /\/|\:/; +function uri(str) { + // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." + return NOT_URI_FRAGMENT.test(str) && URI.test(str); +} + + +function regex(str) { + try { + new RegExp(str); + return true; + } catch(e) { + return false; + } +} + + +function compareDate(d1, d2) { + if (!(d1 && d2)) return; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + if (d1 === d2) return 0; +} + + +function compareTime(t1, t2) { + if (!(t1 && t2)) return; + t1 = t1.match(TIME); + t2 = t2.match(TIME); + if (!(t1 && t2)) return; + t1 = t1[1] + t1[2] + t1[3] + (t1[4]||''); + t2 = t2[1] + t2[2] + t2[3] + (t2[4]||''); + if (t1 > t2) return 1; + if (t1 < t2) return -1; + if (t1 === t2) return 0; +} + + +function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return; + dt1 = dt1.split(DATE_TIME_SEPARATOR); + dt2 = dt2.split(DATE_TIME_SEPARATOR); + var res = compareDate(dt1[0], dt2[0]); + if (res === undefined) return; + return res || compareTime(dt1[1], dt2[1]); +} + + +/***/ }), +/* 344 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var resolve = __webpack_require__(237) + , util = __webpack_require__(60) + , stableStringify = __webpack_require__(217) + , async = __webpack_require__(235); + +var beautify; + +function loadBeautify(){ + if (beautify === undefined) { + var name = 'js-beautify'; + try { beautify = !(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()).js_beautify; } + catch(e) { beautify = false; } + } +} + +var validateGenerator = __webpack_require__(244); + +/** + * Functions below are used inside compiled validations function + */ + +var co = __webpack_require__(280); +var ucs2length = util.ucs2length; +var equal = __webpack_require__(236); + +// this error is thrown by async schemas to return validation errors via exception +var ValidationError = __webpack_require__(239); + +module.exports = compile; + + +/** + * Compiles schema to validation function + * @this Ajv + * @param {Object} schema schema object + * @param {Object} root object with information about the root schema for this schema + * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution + * @param {String} baseId base ID for IDs in the schema + * @return {Function} validation function + */ +function compile(schema, root, localRefs, baseId) { + /* jshint validthis: true, evil: true */ + /* eslint no-shadow: 0 */ + var self = this + , opts = this._opts + , refVal = [ undefined ] + , refs = {} + , patterns = [] + , patternsHash = {} + , defaults = [] + , defaultsHash = {} + , customRules = [] + , keepSourceCode = opts.sourceCode !== false; + + root = root || { schema: schema, refVal: refVal, refs: refs }; + + var c = checkCompiling.call(this, schema, root, baseId); + var compilation = this._compilations[c.index]; + if (c.compiling) return (compilation.callValidate = callValidate); + + var formats = this._formats; + var RULES = this.RULES; + + try { + var v = localCompile(schema, root, localRefs, baseId); + compilation.validate = v; + var cv = compilation.callValidate; + if (cv) { + cv.schema = v.schema; + cv.errors = null; + cv.refs = v.refs; + cv.refVal = v.refVal; + cv.root = v.root; + cv.$async = v.$async; + if (keepSourceCode) cv.sourceCode = v.sourceCode; + } + return v; + } finally { + endCompiling.call(this, schema, root, baseId); + } + + function callValidate() { + var validate = compilation.validate; + var result = validate.apply(null, arguments); + callValidate.errors = validate.errors; + return result; + } + + function localCompile(_schema, _root, localRefs, baseId) { + var isRoot = !_root || (_root && _root.schema == _schema); + if (_root.schema != root.schema) + return compile.call(self, _schema, _root, localRefs, baseId); + + var $async = _schema.$async === true; + if ($async && !opts.transpile) async.setup(opts); + + var sourceCode = validateGenerator({ + isTop: true, + schema: _schema, + isRoot: isRoot, + baseId: baseId, + root: _root, + schemaPath: '', + errSchemaPath: '#', + errorPath: '""', + RULES: RULES, + validate: validateGenerator, + util: util, + resolve: resolve, + resolveRef: resolveRef, + usePattern: usePattern, + useDefault: useDefault, + useCustomRule: useCustomRule, + opts: opts, + formats: formats, + self: self + }); + + sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + + sourceCode; + + if (opts.beautify) { + loadBeautify(); + /* istanbul ignore else */ + if (beautify) sourceCode = beautify(sourceCode, opts.beautify); + else console.error('"npm install js-beautify" to use beautify option'); + } + // console.log('\n\n\n *** \n', sourceCode); + var validate, validateCode + , transpile = opts._transpileFunc; + try { + validateCode = $async && transpile + ? transpile(sourceCode) + : sourceCode; + + var makeValidate = new Function( + 'self', + 'RULES', + 'formats', + 'root', + 'refVal', + 'defaults', + 'customRules', + 'co', + 'equal', + 'ucs2length', + 'ValidationError', + validateCode + ); + + validate = makeValidate( + self, + RULES, + formats, + root, + refVal, + defaults, + customRules, + co, + equal, + ucs2length, + ValidationError + ); + + refVal[0] = validate; + } catch(e) { + console.error('Error compiling schema, function code:', validateCode); + throw e; + } + + validate.schema = _schema; + validate.errors = null; + validate.refs = refs; + validate.refVal = refVal; + validate.root = isRoot ? validate : _root; + if ($async) validate.$async = true; + if (keepSourceCode) validate.sourceCode = sourceCode; + if (opts.sourceCode === true) { + validate.source = { + patterns: patterns, + defaults: defaults + }; + } + + return validate; + } + + function resolveRef(baseId, ref, isRoot) { + ref = resolve.url(baseId, ref); + var refIndex = refs[ref]; + var _refVal, refCode; + if (refIndex !== undefined) { + _refVal = refVal[refIndex]; + refCode = 'refVal[' + refIndex + ']'; + return resolvedRef(_refVal, refCode); + } + if (!isRoot && root.refs) { + var rootRefId = root.refs[ref]; + if (rootRefId !== undefined) { + _refVal = root.refVal[rootRefId]; + refCode = addLocalRef(ref, _refVal); + return resolvedRef(_refVal, refCode); + } + } + + refCode = addLocalRef(ref); + var v = resolve.call(self, localCompile, root, ref); + if (!v) { + var localSchema = localRefs && localRefs[ref]; + if (localSchema) { + v = resolve.inlineRef(localSchema, opts.inlineRefs) + ? localSchema + : compile.call(self, localSchema, root, localRefs, baseId); + } + } + + if (v) { + replaceLocalRef(ref, v); + return resolvedRef(v, refCode); + } + } + + function addLocalRef(ref, v) { + var refId = refVal.length; + refVal[refId] = v; + refs[ref] = refId; + return 'refVal' + refId; + } + + function replaceLocalRef(ref, v) { + var refId = refs[ref]; + refVal[refId] = v; + } + + function resolvedRef(refVal, code) { + return typeof refVal == 'object' + ? { code: code, schema: refVal, inline: true } + : { code: code, $async: refVal && refVal.$async }; + } + + function usePattern(regexStr) { + var index = patternsHash[regexStr]; + if (index === undefined) { + index = patternsHash[regexStr] = patterns.length; + patterns[index] = regexStr; + } + return 'pattern' + index; + } + + function useDefault(value) { + switch (typeof value) { + case 'boolean': + case 'number': + return '' + value; + case 'string': + return util.toQuotedString(value); + case 'object': + if (value === null) return 'null'; + var valueStr = stableStringify(value); + var index = defaultsHash[valueStr]; + if (index === undefined) { + index = defaultsHash[valueStr] = defaults.length; + defaults[index] = value; + } + return 'default' + index; + } + } + + function useCustomRule(rule, schema, parentSchema, it) { + var validateSchema = rule.definition.validateSchema; + if (validateSchema && self._opts.validateSchema !== false) { + var valid = validateSchema(schema); + if (!valid) { + var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); + if (self._opts.validateSchema == 'log') console.error(message); + else throw new Error(message); + } + } + + var compile = rule.definition.compile + , inline = rule.definition.inline + , macro = rule.definition.macro; + + var validate; + if (compile) { + validate = compile.call(self, schema, parentSchema, it); + } else if (macro) { + validate = macro.call(self, schema, parentSchema, it); + if (opts.validateSchema !== false) self.validateSchema(validate, true); + } else if (inline) { + validate = inline.call(self, it, rule.keyword, schema, parentSchema); + } else { + validate = rule.definition.validate; + } + + var index = customRules.length; + customRules[index] = validate; + + return { + code: 'customRule' + index, + validate: validate + }; + } +} + + +/** + * Checks if the schema is currently compiled + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) + */ +function checkCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var index = compIndex.call(this, schema, root, baseId); + if (index >= 0) return { index: index, compiling: true }; + index = this._compilations.length; + this._compilations[index] = { + schema: schema, + root: root, + baseId: baseId + }; + return { index: index, compiling: false }; +} + + +/** + * Removes the schema from the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + */ +function endCompiling(schema, root, baseId) { + /* jshint validthis: true */ + var i = compIndex.call(this, schema, root, baseId); + if (i >= 0) this._compilations.splice(i, 1); +} + + +/** + * Index of schema compilation in the currently compiled list + * @this Ajv + * @param {Object} schema schema to compile + * @param {Object} root root object + * @param {String} baseId base schema ID + * @return {Integer} compilation index + */ +function compIndex(schema, root, baseId) { + /* jshint validthis: true */ + for (var i=0; i<this._compilations.length; i++) { + var c = this._compilations[i]; + if (c.schema == schema && c.root == root && c.baseId == baseId) return i; + } + return -1; +} + + +function patternCode(i, patterns) { + return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');'; +} + + +function defaultCode(i) { + return 'var default' + i + ' = defaults[' + i + '];'; +} + + +function refValCode(i, refVal) { + return refVal[i] ? 'var refVal' + i + ' = refVal[' + i + '];' : ''; +} + + +function customRuleCode(i) { + return 'var customRule' + i + ' = customRules[' + i + '];'; +} + + +function vars(arr, statement) { + if (!arr.length) return ''; + var code = ''; + for (var i=0; i<arr.length; i++) + code += statement(i, arr); + return code; +} + + +/***/ }), +/* 345 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var ruleModules = __webpack_require__(342) + , toHash = __webpack_require__(60).toHash; + +module.exports = function rules() { + var RULES = [ + { type: 'number', + rules: [ 'maximum', 'minimum', 'multipleOf'] }, + { type: 'string', + rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, + { type: 'array', + rules: [ 'maxItems', 'minItems', 'uniqueItems', 'items' ] }, + { type: 'object', + rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'properties' ] }, + { rules: [ '$ref', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] } + ]; + + var ALL = [ 'type', 'additionalProperties', 'patternProperties' ]; + var KEYWORDS = [ 'additionalItems', '$schema', 'id', 'title', 'description', 'default' ]; + var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; + RULES.all = toHash(ALL); + + RULES.forEach(function (group) { + group.rules = group.rules.map(function (keyword) { + ALL.push(keyword); + var rule = RULES.all[keyword] = { + keyword: keyword, + code: ruleModules[keyword] + }; + return rule; + }); + }); + + RULES.keywords = toHash(ALL.concat(KEYWORDS)); + RULES.types = toHash(TYPES); + RULES.custom = {}; + + return RULES; +}; + + +/***/ }), +/* 346 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// https://mathiasbynens.be/notes/javascript-encoding +// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode +module.exports = function ucs2length(str) { + var length = 0 + , len = str.length + , pos = 0 + , value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 0xD800 && value <= 0xDBFF && pos < len) { + // high surrogate, and there is a next character + value = str.charCodeAt(pos); + if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate + } + } + return length; +}; + + +/***/ }), +/* 347 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate__formatLimit(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + out += 'var ' + ($valid) + ' = undefined;'; + if (it.opts.format === false) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $schemaFormat = it.schema.format, + $isDataFormat = it.opts.v5 && $schemaFormat.$data, + $closingBraces = ''; + if ($isDataFormat) { + var $schemaValueFormat = it.util.getData($schemaFormat.$data, $dataLvl, it.dataPathArr), + $format = 'format' + $lvl, + $compare = 'compare' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValueFormat) + '] , ' + ($compare) + ' = ' + ($format) + ' && ' + ($format) + '.compare;'; + } else { + var $format = it.formats[$schemaFormat]; + if (!($format && $format.compare)) { + out += ' ' + ($valid) + ' = true; '; + return out; + } + var $compare = 'formats' + it.util.getProperty($schemaFormat) + '.compare'; + } + var $isMax = $keyword == 'formatMaximum', + $exclusiveKeyword = 'formatExclusive' + ($isMax ? 'Maximum' : 'Minimum'), + $schemaExcl = it.schema[$exclusiveKeyword], + $isDataExcl = it.opts.v5 && $schemaExcl && $schemaExcl.$data, + $op = $isMax ? '<' : '>', + $result = 'result' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if ($isDataExcl) { + var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), + $exclusive = 'exclusive' + $lvl, + $opExpr = 'op' + $lvl, + $opStr = '\' + ' + $opExpr + ' + \''; + out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; + $schemaValueExcl = 'schemaExcl' + $lvl; + out += ' if (typeof ' + ($schemaValueExcl) + ' != \'boolean\' && ' + ($schemaValueExcl) + ' !== undefined) { ' + ($valid) + ' = false; '; + var $errorKeyword = $exclusiveKeyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatExclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; var ' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true; if (' + ($valid) + ' === undefined) { ' + ($valid) + ' = ' + ($exclusive) + ' ? ' + ($result) + ' ' + ($op) + ' 0 : ' + ($result) + ' ' + ($op) + '= 0; } if (!' + ($valid) + ') var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\';'; + } else { + var $exclusive = $schemaExcl === true, + $opStr = $op; + if (!$exclusive) $opStr += '='; + var $opExpr = '\'' + $opStr + '\''; + if ($isData) { + out += ' if (' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'string\') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + if ($isDataFormat) { + out += ' if (!' + ($compare) + ') ' + ($valid) + ' = true; else { '; + $closingBraces += '}'; + } + out += ' var ' + ($result) + ' = ' + ($compare) + '(' + ($data) + ', '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' ); if (' + ($result) + ' === undefined) ' + ($valid) + ' = false; if (' + ($valid) + ' === undefined) ' + ($valid) + ' = ' + ($result) + ' ' + ($op); + if (!$exclusive) { + out += '='; + } + out += ' 0;'; + } + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $errorKeyword = $keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || '_formatLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , exclusive: ' + ($exclusive) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be ' + ($opStr) + ' "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '}'; + return out; +} + + +/***/ }), +/* 348 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_allOf(it, $keyword) { + var out = ' '; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $currentBaseId = $it.baseId, + $allSchemasEmpty = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $allSchemasEmpty = false; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if ($breakOnError) { + if ($allSchemasEmpty) { + out += ' if (true) { '; + } else { + out += ' ' + ($closingBraces.slice(0, -1)) + ' '; + } + } + out = it.util.cleanUpCode(out); + return out; +} + + +/***/ }), +/* 349 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_anyOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $noEmptySchema = $schema.every(function($sch) { + return it.util.schemaHasRules($sch, it.RULES.all); + }); + if ($noEmptySchema) { + var $currentBaseId = $it.baseId; + out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match some schema in anyOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + out = it.util.cleanUpCode(out); + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + + +/***/ }), +/* 350 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_constant(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (!$isData) { + out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('constant') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to constant\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + return out; +} + + +/***/ }), +/* 351 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_custom(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $errorKeyword; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $rule = this, + $definition = 'definition' + $lvl, + $rDef = $rule.definition; + var $compile, $inline, $macro, $ruleValidate, $validateCode; + if ($isData && $rDef.$data) { + $validateCode = 'keywordValidate' + $lvl; + var $validateSchema = $rDef.validateSchema; + out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; + } else { + $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); + $schemaValue = 'validate.schema' + $schemaPath; + $validateCode = $ruleValidate.code; + $compile = $rDef.compile; + $inline = $rDef.inline; + $macro = $rDef.macro; + } + var $ruleErrs = $validateCode + '.errors', + $i = 'i' + $lvl, + $ruleErr = 'ruleErr' + $lvl, + $asyncKeyword = $rDef.async; + if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); + if (!($inline || $macro)) { + out += '' + ($ruleErrs) + ' = null;'; + } + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if ($validateSchema) { + out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') {'; + } + if ($inline) { + if ($rDef.statements) { + out += ' ' + ($ruleValidate.validate) + ' '; + } else { + out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; + } + } else if ($macro) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $ruleValidate.validate; + $it.schemaPath = ''; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($code); + } else { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + out += ' ' + ($validateCode) + '.call( '; + if (it.opts.passContext) { + out += 'this'; + } else { + out += 'self'; + } + if ($compile || $rDef.schema === false) { + out += ' , ' + ($data) + ' '; + } else { + out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; + } + out += ' , (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; + var def_callRuleValidate = out; + out = $$outStack.pop(); + if ($rDef.errors === false) { + out += ' ' + ($valid) + ' = '; + if ($asyncKeyword) { + out += '' + (it.yieldAwait); + } + out += '' + (def_callRuleValidate) + '; '; + } else { + if ($asyncKeyword) { + $ruleErrs = 'customErrors' + $lvl; + out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = ' + (it.yieldAwait) + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; + } else { + out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; + } + } + } + if ($rDef.modifying) { + out += ' ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; + } + if ($validateSchema) { + out += ' }'; + } + if ($rDef.valid) { + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + out += ' if ( '; + if ($rDef.valid === undefined) { + out += ' !'; + if ($macro) { + out += '' + ($nextValid); + } else { + out += '' + ($valid); + } + } else { + out += ' ' + (!$rDef.valid) + ' '; + } + out += ') { '; + $errorKeyword = $rule.keyword; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + var def_customError = out; + out = $$outStack.pop(); + if ($inline) { + if ($rDef.errors) { + if ($rDef.errors != 'full') { + out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } '; + if (it.opts.verbose) { + out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; + } + out += ' } '; + } + } else { + if ($rDef.errors === false) { + out += ' ' + (def_customError) + ' '; + } else { + out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else { for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } '; + if (it.opts.verbose) { + out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; + } + out += ' } } '; + } + } + } else if ($macro) { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError(vErrors); '; + } else { + out += ' validate.errors = vErrors; return false; '; + } + } + } else { + if ($rDef.errors === false) { + out += ' ' + (def_customError) + ' '; + } else { + out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; '; + if (it.opts.verbose) { + out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; + } + out += ' } } else { ' + (def_customError) + ' } '; + } + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } + return out; +} + + +/***/ }), +/* 352 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_dependencies(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $schemaDeps = {}, + $propertyDeps = {}; + for ($property in $schema) { + var $sch = $schema[$property]; + var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; + $deps[$property] = $sch; + } + out += 'var ' + ($errs) + ' = errors;'; + var $currentErrorPath = it.errorPath; + out += 'var missing' + ($lvl) + ';'; + for (var $property in $propertyDeps) { + $deps = $propertyDeps[$property]; + out += ' if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; + if ($breakOnError) { + out += ' && ( '; + var arr1 = $deps; + if (arr1) { + var _$property, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + _$property = arr1[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty(_$property); + out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) '; + } + } + out += ')) { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); + } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } else { + out += ' ) { '; + var arr2 = $deps; + if (arr2) { + var $reqProperty, i2 = -1, + l2 = arr2.length - 1; + while (i2 < l2) { + $reqProperty = arr2[i2 += 1]; + var $prop = it.util.getProperty($reqProperty), + $missingProperty = it.util.escapeQuotes($reqProperty); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers); + } + out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have '; + if ($deps.length == 1) { + out += 'property ' + (it.util.escapeQuotes($deps[0])); + } else { + out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); + } + out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + out += ' } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + it.errorPath = $currentErrorPath; + var $currentBaseId = $it.baseId; + for (var $property in $schemaDeps) { + var $sch = $schemaDeps[$property]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + (it.util.getProperty($property)) + ' !== undefined) { '; + $it.schema = $sch; + $it.schemaPath = $schemaPath + it.util.getProperty($property); + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} + + +/***/ }), +/* 353 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_enum(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $i = 'i' + $lvl, + $vSchema = 'schema' + $lvl; + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; + } + out += 'var ' + ($valid) + ';'; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be equal to one of the allowed values\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' }'; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), +/* 354 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_format(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + if (it.opts.format === false) { + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $unknownFormats = it.opts.unknownFormats, + $allowUnknown = Array.isArray($unknownFormats); + if ($isData) { + var $format = 'format' + $lvl; + out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var isObject' + ($lvl) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; if (isObject' + ($lvl) + ') { '; + if (it.async) { + out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; + } + out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' ('; + if ($unknownFormats === true || $allowUnknown) { + out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; + if ($allowUnknown) { + out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; + } + out += ') || '; + } + out += ' (' + ($format) + ' && !(typeof ' + ($format) + ' == \'function\' ? '; + if (it.async) { + out += ' (async' + ($lvl) + ' ? ' + (it.yieldAwait) + ' ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; + } else { + out += ' ' + ($format) + '(' + ($data) + ') '; + } + out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; + } else { + var $format = it.formats[$schema]; + if (!$format) { + if ($unknownFormats === true || ($allowUnknown && $unknownFormats.indexOf($schema) == -1)) { + throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); + } else { + if (!$allowUnknown) { + console.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); + if ($unknownFormats !== 'ignore') console.warn('In the next major version it will throw exception. See option unknownFormats for more information'); + } + if ($breakOnError) { + out += ' if (true) { '; + } + return out; + } + } + var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; + if ($isObject) { + var $async = $format.async === true; + $format = $format.validate; + } + if ($async) { + if (!it.async) throw new Error('async format in sync schema'); + var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; + out += ' if (!(' + (it.yieldAwait) + ' ' + ($formatRef) + '(' + ($data) + '))) { '; + } else { + out += ' if (! '; + var $formatRef = 'formats' + it.util.getProperty($schema); + if ($isObject) $formatRef += '.validate'; + if (typeof $format == 'function') { + out += ' ' + ($formatRef) + '(' + ($data) + ') '; + } else { + out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; + } + out += ') { '; + } + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match format "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), +/* 355 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_items(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $idx = 'i' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt, + $currentBaseId = it.baseId; + out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; + if (Array.isArray($schema)) { + var $additionalItems = it.schema.additionalItems; + if ($additionalItems === false) { + out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; + var $passData = $data + '[' + $i + ']'; + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); + $it.dataPathArr[$dataNxt] = $i; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) { + $it.schema = $additionalItems; + $it.schemaPath = it.schemaPath + '.additionalItems'; + $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; + out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } else if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); + var $passData = $data + '[' + $idx + ']'; + $it.dataPathArr[$dataNxt] = $idx; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} + + +/***/ }), +/* 356 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_multipleOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + out += 'var division' + ($lvl) + ';if ('; + if ($isData) { + out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; + } + out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; + if (it.opts.multipleOfPrecision) { + out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; + } else { + out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; + } + out += ' ) '; + if ($isData) { + out += ' ) '; + } + out += ' ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should be multiple of '; + if ($isData) { + out += '\' + ' + ($schemaValue); + } else { + out += '' + ($schema) + '\''; + } + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), +/* 357 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_not(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + if (it.util.schemaHasRules($schema, it.RULES.all)) { + $it.schema = $schema; + $it.schemaPath = $schemaPath; + $it.errSchemaPath = $errSchemaPath; + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + var $allErrorsOption; + if ($it.opts.allErrors) { + $allErrorsOption = $it.opts.allErrors; + $it.opts.allErrors = false; + } + out += ' ' + (it.validate($it)) + ' '; + $it.createErrors = true; + if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' if (' + ($nextValid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; + if (it.opts.allErrors) { + out += ' } '; + } + } else { + out += ' var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT be valid\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + if ($breakOnError) { + out += ' if (false) { '; + } + } + return out; +} + + +/***/ }), +/* 358 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_oneOf(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + out += 'var ' + ($errs) + ' = errors;var prevValid' + ($lvl) + ' = false;var ' + ($valid) + ' = false;'; + var $currentBaseId = $it.baseId; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + var arr1 = $schema; + if (arr1) { + var $sch, $i = -1, + l1 = arr1.length - 1; + while ($i < l1) { + $sch = arr1[$i += 1]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = $schemaPath + '[' + $i + ']'; + $it.errSchemaPath = $errSchemaPath + '/' + $i; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } else { + out += ' var ' + ($nextValid) + ' = true; '; + } + if ($i) { + out += ' if (' + ($nextValid) + ' && prevValid' + ($lvl) + ') ' + ($valid) + ' = false; else { '; + $closingBraces += '}'; + } + out += ' if (' + ($nextValid) + ') ' + ($valid) + ' = prevValid' + ($lvl) + ' = true;'; + } + } + it.compositeRule = $it.compositeRule = $wasComposite; + out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; + if (it.opts.messages !== false) { + out += ' , message: \'should match exactly one schema in oneOf\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; + if (it.opts.allErrors) { + out += ' } '; + } + return out; +} + + +/***/ }), +/* 359 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_pattern(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); + out += 'if ( '; + if ($isData) { + out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; + } + out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; + if ($isData) { + out += '' + ($schemaValue); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should match pattern "'; + if ($isData) { + out += '\' + ' + ($schemaValue) + ' + \''; + } else { + out += '' + (it.util.escapeQuotes($schema)); + } + out += '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + (it.util.toQuotedString($schema)); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += '} '; + if ($breakOnError) { + out += ' else { '; + } + return out; +} + + +/***/ }), +/* 360 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_patternRequired(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $key = 'key' + $lvl, + $matched = 'patternMatched' + $lvl, + $closingBraces = '', + $ownProperties = it.opts.ownProperties; + out += 'var ' + ($valid) + ' = true;'; + var arr1 = $schema; + if (arr1) { + var $pProperty, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $pProperty = arr1[i1 += 1]; + out += ' var ' + ($matched) + ' = false; for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' ' + ($matched) + ' = ' + (it.usePattern($pProperty)) + '.test(' + ($key) + '); if (' + ($matched) + ') break; } '; + var $missingPattern = it.util.escapeQuotes($pProperty); + out += ' if (!' + ($matched) + ') { ' + ($valid) + ' = false; var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternRequired') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingPattern: \'' + ($missingPattern) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should have property matching pattern \\\'' + ($missingPattern) + '\\\'\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + if ($breakOnError) { + $closingBraces += '}'; + out += ' else { '; + } + } + } + out += '' + ($closingBraces); + return out; +} + + +/***/ }), +/* 361 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_properties(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $key = 'key' + $lvl, + $dataNxt = $it.dataLevel = it.dataLevel + 1, + $nextData = 'data' + $dataNxt; + var $schemaKeys = Object.keys($schema || {}), + $pProperties = it.schema.patternProperties || {}, + $pPropertyKeys = Object.keys($pProperties), + $aProperties = it.schema.additionalProperties, + $someProperties = $schemaKeys.length || $pPropertyKeys.length, + $noAdditional = $aProperties === false, + $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, + $removeAdditional = it.opts.removeAdditional, + $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, + $ownProperties = it.opts.ownProperties, + $currentBaseId = it.baseId; + var $required = it.schema.required; + if ($required && !(it.opts.v5 && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required); + if (it.opts.v5) { + var $pgProperties = it.schema.patternGroups || {}, + $pgPropertyKeys = Object.keys($pgProperties); + } + out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; + if ($checkAdditional) { + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + if ($someProperties) { + out += ' var isAdditional' + ($lvl) + ' = !(false '; + if ($schemaKeys.length) { + if ($schemaKeys.length > 5) { + out += ' || validate.schema' + ($schemaPath) + '[' + ($key) + '] '; + } else { + var arr1 = $schemaKeys; + if (arr1) { + var $propertyKey, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $propertyKey = arr1[i1 += 1]; + out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; + } + } + } + } + if ($pPropertyKeys.length) { + var arr2 = $pPropertyKeys; + if (arr2) { + var $pProperty, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + $pProperty = arr2[$i += 1]; + out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; + } + } + } + if (it.opts.v5 && $pgPropertyKeys && $pgPropertyKeys.length) { + var arr3 = $pgPropertyKeys; + if (arr3) { + var $pgProperty, $i = -1, + l3 = arr3.length - 1; + while ($i < l3) { + $pgProperty = arr3[$i += 1]; + out += ' || ' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ') '; + } + } + } + out += ' ); if (isAdditional' + ($lvl) + ') { '; + } + if ($removeAdditional == 'all') { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + var $currentErrorPath = it.errorPath; + var $additionalProperty = '\' + ' + $key + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + } + if ($noAdditional) { + if ($removeAdditional) { + out += ' delete ' + ($data) + '[' + ($key) + ']; '; + } else { + out += ' ' + ($nextValid) + ' = false; '; + var $currErrSchemaPath = $errSchemaPath; + $errSchemaPath = it.errSchemaPath + '/additionalProperties'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have additional properties\' '; + } + if (it.opts.verbose) { + out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' break; '; + } + } + } else if ($additionalIsSchema) { + if ($removeAdditional == 'failing') { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; + it.compositeRule = $it.compositeRule = $wasComposite; + } else { + $it.schema = $aProperties; + $it.schemaPath = it.schemaPath + '.additionalProperties'; + $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; + $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + } + } + it.errorPath = $currentErrorPath; + } + if ($someProperties) { + out += ' } '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + var $useDefaults = it.opts.useDefaults && !it.compositeRule; + if ($schemaKeys.length) { + var arr4 = $schemaKeys; + if (arr4) { + var $propertyKey, i4 = -1, + l4 = arr4.length - 1; + while (i4 < l4) { + $propertyKey = arr4[i4 += 1]; + var $sch = $schema[$propertyKey]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + var $prop = it.util.getProperty($propertyKey), + $passData = $data + $prop, + $hasDefault = $useDefaults && $sch.default !== undefined; + $it.schema = $sch; + $it.schemaPath = $schemaPath + $prop; + $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); + $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); + $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + $code = it.util.varReplace($code, $nextData, $passData); + var $useData = $passData; + } else { + var $useData = $nextData; + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; + } + if ($hasDefault) { + out += ' ' + ($code) + ' '; + } else { + if ($requiredHash && $requiredHash[$propertyKey]) { + out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = false; '; + var $currentErrorPath = it.errorPath, + $currErrSchemaPath = $errSchemaPath, + $missingProperty = it.util.escapeQuotes($propertyKey); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); + } + $errSchemaPath = it.errSchemaPath + '/required'; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + $errSchemaPath = $currErrSchemaPath; + it.errorPath = $currentErrorPath; + out += ' } else { '; + } else { + if ($breakOnError) { + out += ' if (' + ($useData) + ' === undefined) { ' + ($nextValid) + ' = true; } else { '; + } else { + out += ' if (' + ($useData) + ' !== undefined) { '; + } + } + out += ' ' + ($code) + ' } '; + } + } + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + var arr5 = $pPropertyKeys; + if (arr5) { + var $pProperty, i5 = -1, + l5 = arr5.length - 1; + while (i5 < l5) { + $pProperty = arr5[i5 += 1]; + var $sch = $pProperties[$pProperty]; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); + $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); + out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + } + } + } + if (it.opts.v5) { + var arr6 = $pgPropertyKeys; + if (arr6) { + var $pgProperty, i6 = -1, + l6 = arr6.length - 1; + while (i6 < l6) { + $pgProperty = arr6[i6 += 1]; + var $pgSchema = $pgProperties[$pgProperty], + $sch = $pgSchema.schema; + if (it.util.schemaHasRules($sch, it.RULES.all)) { + $it.schema = $sch; + $it.schemaPath = it.schemaPath + '.patternGroups' + it.util.getProperty($pgProperty) + '.schema'; + $it.errSchemaPath = it.errSchemaPath + '/patternGroups/' + it.util.escapeFragment($pgProperty) + '/schema'; + out += ' var pgPropCount' + ($lvl) + ' = 0; for (var ' + ($key) + ' in ' + ($data) + ') { '; + if ($ownProperties) { + out += ' if (!Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($key) + ')) continue; '; + } + out += ' if (' + (it.usePattern($pgProperty)) + '.test(' + ($key) + ')) { pgPropCount' + ($lvl) + '++; '; + $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); + var $passData = $data + '[' + $key + ']'; + $it.dataPathArr[$dataNxt] = $key; + var $code = it.validate($it); + $it.baseId = $currentBaseId; + if (it.util.varOccurences($code, $nextData) < 2) { + out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; + } else { + out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; + } + if ($breakOnError) { + out += ' if (!' + ($nextValid) + ') break; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else ' + ($nextValid) + ' = true; '; + } + out += ' } '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + $closingBraces += '}'; + } + var $pgMin = $pgSchema.minimum, + $pgMax = $pgSchema.maximum; + if ($pgMin !== undefined || $pgMax !== undefined) { + out += ' var ' + ($valid) + ' = true; '; + var $currErrSchemaPath = $errSchemaPath; + if ($pgMin !== undefined) { + var $limit = $pgMin, + $reason = 'minimum', + $moreOrLess = 'less'; + out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' >= ' + ($pgMin) + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/minimum'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($pgMax !== undefined) { + out += ' else '; + } + } + if ($pgMax !== undefined) { + var $limit = $pgMax, + $reason = 'maximum', + $moreOrLess = 'more'; + out += ' ' + ($valid) + ' = pgPropCount' + ($lvl) + ' <= ' + ($pgMax) + '; '; + $errSchemaPath = it.errSchemaPath + '/patternGroups/maximum'; + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('patternGroups') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { reason: \'' + ($reason) + '\', limit: ' + ($limit) + ', pattern: \'' + (it.util.escapeQuotes($pgProperty)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have ' + ($moreOrLess) + ' than ' + ($limit) + ' properties matching pattern "' + (it.util.escapeQuotes($pgProperty)) + '"\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + } + $errSchemaPath = $currErrSchemaPath; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + $closingBraces += '}'; + } + } + } + } + } + } + if ($breakOnError) { + out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; + } + out = it.util.cleanUpCode(out); + return out; +} + + +/***/ }), +/* 362 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_ref(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $async, $refCode; + if ($schema == '#' || $schema == '#/') { + if (it.isRoot) { + $async = it.async; + $refCode = 'validate'; + } else { + $async = it.root.schema.$async === true; + $refCode = 'root.refVal[0]'; + } + } else { + var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); + if ($refVal === undefined) { + var $message = 'can\'t resolve reference ' + $schema + ' from id ' + it.baseId; + if (it.opts.missingRefs == 'fail') { + console.log($message); + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; + } + if (it.opts.verbose) { + out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + if ($breakOnError) { + out += ' if (false) { '; + } + } else if (it.opts.missingRefs == 'ignore') { + console.log($message); + if ($breakOnError) { + out += ' if (true) { '; + } + } else { + var $error = new Error($message); + $error.missingRef = it.resolve.url(it.baseId, $schema); + $error.missingSchema = it.resolve.normalizeId(it.resolve.fullPath($error.missingRef)); + throw $error; + } + } else if ($refVal.inline) { + var $it = it.util.copy(it); + $it.level++; + var $nextValid = 'valid' + $it.level; + $it.schema = $refVal.schema; + $it.schemaPath = ''; + $it.errSchemaPath = $schema; + var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); + out += ' ' + ($code) + ' '; + if ($breakOnError) { + out += ' if (' + ($nextValid) + ') { '; + } + } else { + $async = $refVal.$async === true; + $refCode = $refVal.code; + } + } + if ($refCode) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; + if (it.opts.passContext) { + out += ' ' + ($refCode) + '.call(this, '; + } else { + out += ' ' + ($refCode) + '( '; + } + out += ' ' + ($data) + ', (dataPath || \'\')'; + if (it.errorPath != '""') { + out += ' + ' + (it.errorPath); + } + var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', + $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; + out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; + var __callValidate = out; + out = $$outStack.pop(); + if ($async) { + if (!it.async) throw new Error('async schema referenced by sync schema'); + out += ' try { '; + if ($breakOnError) { + out += 'var ' + ($valid) + ' ='; + } + out += ' ' + (it.yieldAwait) + ' ' + (__callValidate) + '; } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' if (' + ($valid) + ') { '; + } + } else { + out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; + if ($breakOnError) { + out += ' else { '; + } + } + } + return out; +} + + +/***/ }), +/* 363 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_required(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + var $vSchema = 'schema' + $lvl; + if (!$isData) { + if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { + var $required = []; + var arr1 = $schema; + if (arr1) { + var $property, i1 = -1, + l1 = arr1.length - 1; + while (i1 < l1) { + $property = arr1[i1 += 1]; + var $propertySch = it.schema.properties[$property]; + if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) { + $required[$required.length] = $property; + } + } + } + } else { + var $required = $schema; + } + } + if ($isData || $required.length) { + var $currentErrorPath = it.errorPath, + $loopRequired = $isData || $required.length >= it.opts.loopRequired; + if ($breakOnError) { + out += ' var missing' + ($lvl) + '; '; + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + out += ' var ' + ($valid) + ' = true; '; + if ($isData) { + out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined; if (!' + ($valid) + ') break; } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } else { + out += ' if ( '; + var arr2 = $required; + if (arr2) { + var _$property, $i = -1, + l2 = arr2.length - 1; + while ($i < l2) { + _$property = arr2[$i += 1]; + if ($i) { + out += ' || '; + } + var $prop = it.util.getProperty(_$property); + out += ' ( ' + ($data) + ($prop) + ' === undefined && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? _$property : $prop)) + ') ) '; + } + } + out += ') { '; + var $propertyPath = 'missing' + $lvl, + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; + } + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } else { '; + } + } else { + if ($loopRequired) { + if (!$isData) { + out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; + } + var $i = 'i' + $lvl, + $propertyPath = 'schema' + $lvl + '[' + $i + ']', + $missingProperty = '\' + ' + $propertyPath + ' + \''; + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); + } + if ($isData) { + out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; + } + out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; + if ($isData) { + out += ' } '; + } + } else { + var arr3 = $required; + if (arr3) { + var $reqProperty, i3 = -1, + l3 = arr3.length - 1; + while (i3 < l3) { + $reqProperty = arr3[i3 += 1]; + var $prop = it.util.getProperty($reqProperty), + $missingProperty = it.util.escapeQuotes($reqProperty); + if (it.opts._errorDataPathProperty) { + it.errorPath = it.util.getPath($currentErrorPath, $reqProperty, it.opts.jsonPointers); + } + out += ' if (' + ($data) + ($prop) + ' === undefined) { var err = '; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; + if (it.opts.messages !== false) { + out += ' , message: \''; + if (it.opts._errorDataPathProperty) { + out += 'is a required property'; + } else { + out += 'should have required property \\\'' + ($missingProperty) + '\\\''; + } + out += '\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; + } + } + } + } + it.errorPath = $currentErrorPath; + } else if ($breakOnError) { + out += ' if (true) {'; + } + return out; +} + + +/***/ }), +/* 364 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_switch(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $errs = 'errs__' + $lvl; + var $it = it.util.copy(it); + var $closingBraces = ''; + $it.level++; + var $nextValid = 'valid' + $it.level; + var $ifPassed = 'ifPassed' + it.level, + $currentBaseId = $it.baseId, + $shouldContinue; + out += 'var ' + ($ifPassed) + ';'; + var arr1 = $schema; + if (arr1) { + var $sch, $caseIndex = -1, + l1 = arr1.length - 1; + while ($caseIndex < l1) { + $sch = arr1[$caseIndex += 1]; + if ($caseIndex && !$shouldContinue) { + out += ' if (!' + ($ifPassed) + ') { '; + $closingBraces += '}'; + } + if ($sch.if && it.util.schemaHasRules($sch.if, it.RULES.all)) { + out += ' var ' + ($errs) + ' = errors; '; + var $wasComposite = it.compositeRule; + it.compositeRule = $it.compositeRule = true; + $it.createErrors = false; + $it.schema = $sch.if; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].if'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/if'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + $it.createErrors = true; + it.compositeRule = $it.compositeRule = $wasComposite; + out += ' ' + ($ifPassed) + ' = ' + ($nextValid) + '; if (' + ($ifPassed) + ') { '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } } '; + } else { + out += ' ' + ($ifPassed) + ' = true; '; + if (typeof $sch.then == 'boolean') { + if ($sch.then === false) { + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('switch') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { caseIndex: ' + ($caseIndex) + ' } '; + if (it.opts.messages !== false) { + out += ' , message: \'should pass "switch" keyword validation\' '; + } + if (it.opts.verbose) { + out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + } + out += ' var ' + ($nextValid) + ' = ' + ($sch.then) + '; '; + } else { + $it.schema = $sch.then; + $it.schemaPath = $schemaPath + '[' + $caseIndex + '].then'; + $it.errSchemaPath = $errSchemaPath + '/' + $caseIndex + '/then'; + out += ' ' + (it.validate($it)) + ' '; + $it.baseId = $currentBaseId; + } + } + $shouldContinue = $sch.continue + } + } + out += '' + ($closingBraces) + 'var ' + ($valid) + ' = ' + ($nextValid) + '; '; + out = it.util.cleanUpCode(out); + return out; +} + + +/***/ }), +/* 365 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function generate_uniqueItems(it, $keyword) { + var out = ' '; + var $lvl = it.level; + var $dataLvl = it.dataLevel; + var $schema = it.schema[$keyword]; + var $schemaPath = it.schemaPath + it.util.getProperty($keyword); + var $errSchemaPath = it.errSchemaPath + '/' + $keyword; + var $breakOnError = !it.opts.allErrors; + var $data = 'data' + ($dataLvl || ''); + var $valid = 'valid' + $lvl; + var $isData = it.opts.v5 && $schema && $schema.$data, + $schemaValue; + if ($isData) { + out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; + $schemaValue = 'schema' + $lvl; + } else { + $schemaValue = $schema; + } + if (($schema || $isData) && it.opts.uniqueItems !== false) { + if ($isData) { + out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; + } + out += ' var ' + ($valid) + ' = true; if (' + ($data) + '.length > 1) { var i = ' + ($data) + '.length, j; outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } } '; + if ($isData) { + out += ' } '; + } + out += ' if (!' + ($valid) + ') { '; + var $$outStack = $$outStack || []; + $$outStack.push(out); + out = ''; /* istanbul ignore else */ + if (it.createErrors !== false) { + out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; + if (it.opts.messages !== false) { + out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; + } + if (it.opts.verbose) { + out += ' , schema: '; + if ($isData) { + out += 'validate.schema' + ($schemaPath); + } else { + out += '' + ($schema); + } + out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; + } + out += ' } '; + } else { + out += ' {} '; + } + var __err = out; + out = $$outStack.pop(); + if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ + if (it.async) { + out += ' throw new ValidationError([' + (__err) + ']); '; + } else { + out += ' validate.errors = [' + (__err) + ']; return false; '; + } + } else { + out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; + } + out += ' } '; + if ($breakOnError) { + out += ' else { '; + } + } else { + if ($breakOnError) { + out += ' if (true) { '; + } + } + return out; +} + + +/***/ }), +/* 366 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var IDENTIFIER = /^[a-z_$][a-z0-9_$\-]*$/i; +var customRuleCode = __webpack_require__(351); + +module.exports = { + add: addKeyword, + get: getKeyword, + remove: removeKeyword +}; + +/** + * Define custom keyword + * @this Ajv + * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). + * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. + */ +function addKeyword(keyword, definition) { + /* jshint validthis: true */ + /* eslint no-shadow: 0 */ + var RULES = this.RULES; + + if (RULES.keywords[keyword]) + throw new Error('Keyword ' + keyword + ' is already defined'); + + if (!IDENTIFIER.test(keyword)) + throw new Error('Keyword ' + keyword + ' is not a valid identifier'); + + if (definition) { + if (definition.macro && definition.valid !== undefined) + throw new Error('"valid" option cannot be used with macro keywords'); + + var dataType = definition.type; + if (Array.isArray(dataType)) { + var i, len = dataType.length; + for (i=0; i<len; i++) checkDataType(dataType[i]); + for (i=0; i<len; i++) _addRule(keyword, dataType[i], definition); + } else { + if (dataType) checkDataType(dataType); + _addRule(keyword, dataType, definition); + } + + var $data = definition.$data === true && this._opts.v5; + if ($data && !definition.validate) + throw new Error('$data support: "validate" function is not defined'); + + var metaSchema = definition.metaSchema; + if (metaSchema) { + if ($data) { + metaSchema = { + anyOf: [ + metaSchema, + { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#/definitions/$data' } + ] + }; + } + definition.validateSchema = this.compile(metaSchema, true); + } + } + + RULES.keywords[keyword] = RULES.all[keyword] = true; + + + function _addRule(keyword, dataType, definition) { + var ruleGroup; + for (var i=0; i<RULES.length; i++) { + var rg = RULES[i]; + if (rg.type == dataType) { + ruleGroup = rg; + break; + } + } + + if (!ruleGroup) { + ruleGroup = { type: dataType, rules: [] }; + RULES.push(ruleGroup); + } + + var rule = { + keyword: keyword, + definition: definition, + custom: true, + code: customRuleCode + }; + ruleGroup.rules.push(rule); + RULES.custom[keyword] = rule; + } + + + function checkDataType(dataType) { + if (!RULES.types[dataType]) throw new Error('Unknown type ' + dataType); + } +} + + +/** + * Get keyword + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. + */ +function getKeyword(keyword) { + /* jshint validthis: true */ + var rule = this.RULES.custom[keyword]; + return rule ? rule.definition : this.RULES.keywords[keyword] || false; +} + + +/** + * Remove keyword + * @this Ajv + * @param {String} keyword pre-defined or custom keyword. + */ +function removeKeyword(keyword) { + /* jshint validthis: true */ + var RULES = this.RULES; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + delete RULES.custom[keyword]; + for (var i=0; i<RULES.length; i++) { + var rules = RULES[i].rules; + for (var j=0; j<rules.length; j++) { + if (rules[j].keyword == keyword) { + rules.splice(j, 1); + break; + } + } + } +} + + +/***/ }), +/* 367 */ +/***/ (function(module, exports) { + +module.exports = { + "id": "http://json-schema.org/draft-04/schema#", + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#" + } + }, + "positiveInteger": { + "type": "integer", + "minimum": 0 + }, + "positiveIntegerDefault0": { + "allOf": [ + { + "$ref": "#/definitions/positiveInteger" + }, + { + "default": 0 + } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + } + }, + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uri" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + }, + "maximum": { + "type": "number" + }, + "exclusiveMaximum": { + "type": "boolean", + "default": false + }, + "minimum": { + "type": "number" + }, + "exclusiveMinimum": { + "type": "boolean", + "default": false + }, + "maxLength": { + "$ref": "#/definitions/positiveInteger" + }, + "minLength": { + "$ref": "#/definitions/positiveIntegerDefault0" + }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#" + } + ], + "default": {} + }, + "items": { + "anyOf": [ + { + "$ref": "#" + }, + { + "$ref": "#/definitions/schemaArray" + } + ], + "default": {} + }, + "maxItems": { + "$ref": "#/definitions/positiveInteger" + }, + "minItems": { + "$ref": "#/definitions/positiveIntegerDefault0" + }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxProperties": { + "$ref": "#/definitions/positiveInteger" + }, + "minProperties": { + "$ref": "#/definitions/positiveIntegerDefault0" + }, + "required": { + "$ref": "#/definitions/stringArray" + }, + "additionalProperties": { + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#" + } + ], + "default": {} + }, + "definitions": { + "type": "object", + "additionalProperties": { + "$ref": "#" + }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { + "$ref": "#" + }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { + "$ref": "#" + }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "$ref": "#" + }, + { + "$ref": "#/definitions/stringArray" + } + ] + } + }, + "enum": { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + "type": { + "anyOf": [ + { + "$ref": "#/definitions/simpleTypes" + }, + { + "type": "array", + "items": { + "$ref": "#/definitions/simpleTypes" + }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "allOf": { + "$ref": "#/definitions/schemaArray" + }, + "anyOf": { + "$ref": "#/definitions/schemaArray" + }, + "oneOf": { + "$ref": "#/definitions/schemaArray" + }, + "not": { + "$ref": "#" + } + }, + "dependencies": { + "exclusiveMaximum": [ + "maximum" + ], + "exclusiveMinimum": [ + "minimum" + ] + }, + "default": {} +}; + +/***/ }), +/* 368 */ +/***/ (function(module, exports) { + +module.exports = { + "id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json#", + "$schema": "http://json-schema.org/draft-04/schema#", + "description": "Core schema meta-schema (v5 proposals)", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#" + } + }, + "positiveInteger": { + "type": "integer", + "minimum": 0 + }, + "positiveIntegerDefault0": { + "allOf": [ + { + "$ref": "#/definitions/positiveInteger" + }, + { + "default": 0 + } + ] + }, + "simpleTypes": { + "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] + }, + "stringArray": { + "type": "array", + "items": { + "type": "string" + }, + "minItems": 1, + "uniqueItems": true + }, + "$data": { + "type": "object", + "required": [ + "$data" + ], + "properties": { + "$data": { + "type": "string", + "anyOf": [ + { + "format": "relative-json-pointer" + }, + { + "format": "json-pointer" + } + ] + } + }, + "additionalProperties": false + } + }, + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uri" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "default": {}, + "multipleOf": { + "anyOf": [ + { + "type": "number", + "minimum": 0, + "exclusiveMinimum": true + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "maximum": { + "anyOf": [ + { + "type": "number" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "exclusiveMaximum": { + "anyOf": [ + { + "type": "boolean", + "default": false + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "minimum": { + "anyOf": [ + { + "type": "number" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "exclusiveMinimum": { + "anyOf": [ + { + "type": "boolean", + "default": false + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "maxLength": { + "anyOf": [ + { + "$ref": "#/definitions/positiveInteger" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "minLength": { + "anyOf": [ + { + "$ref": "#/definitions/positiveIntegerDefault0" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "pattern": { + "anyOf": [ + { + "type": "string", + "format": "regex" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "additionalItems": { + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#" + }, + { + "$ref": "#/definitions/$data" + } + ], + "default": {} + }, + "items": { + "anyOf": [ + { + "$ref": "#" + }, + { + "$ref": "#/definitions/schemaArray" + } + ], + "default": {} + }, + "maxItems": { + "anyOf": [ + { + "$ref": "#/definitions/positiveInteger" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "minItems": { + "anyOf": [ + { + "$ref": "#/definitions/positiveIntegerDefault0" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "uniqueItems": { + "anyOf": [ + { + "type": "boolean", + "default": false + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "maxProperties": { + "anyOf": [ + { + "$ref": "#/definitions/positiveInteger" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "minProperties": { + "anyOf": [ + { + "$ref": "#/definitions/positiveIntegerDefault0" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "required": { + "anyOf": [ + { + "$ref": "#/definitions/stringArray" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "additionalProperties": { + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#" + }, + { + "$ref": "#/definitions/$data" + } + ], + "default": {} + }, + "definitions": { + "type": "object", + "additionalProperties": { + "$ref": "#" + }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { + "$ref": "#" + }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { + "$ref": "#" + }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "$ref": "#" + }, + { + "$ref": "#/definitions/stringArray" + } + ] + } + }, + "enum": { + "anyOf": [ + { + "type": "array", + "minItems": 1, + "uniqueItems": true + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "type": { + "anyOf": [ + { + "$ref": "#/definitions/simpleTypes" + }, + { + "type": "array", + "items": { + "$ref": "#/definitions/simpleTypes" + }, + "minItems": 1, + "uniqueItems": true + } + ] + }, + "allOf": { + "$ref": "#/definitions/schemaArray" + }, + "anyOf": { + "$ref": "#/definitions/schemaArray" + }, + "oneOf": { + "$ref": "#/definitions/schemaArray" + }, + "not": { + "$ref": "#" + }, + "format": { + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "formatMaximum": { + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "formatMinimum": { + "anyOf": [ + { + "type": "string" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "formatExclusiveMaximum": { + "anyOf": [ + { + "type": "boolean", + "default": false + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "formatExclusiveMinimum": { + "anyOf": [ + { + "type": "boolean", + "default": false + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "constant": { + "anyOf": [ + {}, + { + "$ref": "#/definitions/$data" + } + ] + }, + "contains": { + "$ref": "#" + }, + "patternGroups": { + "type": "object", + "additionalProperties": { + "type": "object", + "required": [ + "schema" + ], + "properties": { + "maximum": { + "anyOf": [ + { + "$ref": "#/definitions/positiveInteger" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "minimum": { + "anyOf": [ + { + "$ref": "#/definitions/positiveIntegerDefault0" + }, + { + "$ref": "#/definitions/$data" + } + ] + }, + "schema": { + "$ref": "#" + } + }, + "additionalProperties": false + }, + "default": {} + }, + "switch": { + "type": "array", + "items": { + "required": [ + "then" + ], + "properties": { + "if": { + "$ref": "#" + }, + "then": { + "anyOf": [ + { + "type": "boolean" + }, + { + "$ref": "#" + } + ] + }, + "continue": { + "type": "boolean" + } + }, + "additionalProperties": false, + "dependencies": { + "continue": [ + "if" + ] + } + } + } + }, + "dependencies": { + "exclusiveMaximum": [ + "maximum" + ], + "exclusiveMinimum": [ + "minimum" + ], + "formatMaximum": [ + "format" + ], + "formatMinimum": [ + "format" + ], + "formatExclusiveMaximum": [ + "formatMaximum" + ], + "formatExclusiveMinimum": [ + "formatMinimum" + ] + }, + "default": {} +}; /***/ }), -/* 336 */ +/* 369 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.examples = exports.setFlags = exports.run = undefined; - -var _slicedToArray2; - -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -exports.hasWrapper = hasWrapper; - -var _buildSubCommands2; - -function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); -} - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function hasWrapper(flags, args) { - return args[0] !== 'get'; -} -/* eslint object-shorthand: 0 */ - -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('config', { - set(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (args.length === 0 || args.length > 2) { - return false; - } +var META_SCHEMA_ID = 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/json-schema-v5.json'; - var _args = (0, (_slicedToArray2 || _load_slicedToArray()).default)(args, 2); +module.exports = { + enable: enableV5, + META_SCHEMA_ID: META_SCHEMA_ID +}; - const key = _args[0]; - var _args$ = _args[1]; - const val = _args$ === undefined ? true : _args$; - const yarnConfig = config.registries.yarn; - yield yarnConfig.saveHomeConfig({ [key]: val }); - reporter.success(reporter.lang('configSet', key, val)); - return true; - })(); - }, +function enableV5(ajv) { + var inlineFunctions = { + 'switch': __webpack_require__(364), + 'constant': __webpack_require__(350), + '_formatLimit': __webpack_require__(347), + 'patternRequired': __webpack_require__(360) + }; - get(config, reporter, flags, args) { - if (args.length !== 1) { - return false; - } + if (ajv._opts.meta !== false) { + var metaSchema = __webpack_require__(368); + ajv.addMetaSchema(metaSchema, META_SCHEMA_ID); + } + _addKeyword('constant'); + ajv.addKeyword('contains', { type: 'array', macro: containsMacro }); - reporter.log(String(config.getOption(args[0], false))); - return true; - }, + _addKeyword('formatMaximum', 'string', inlineFunctions._formatLimit); + _addKeyword('formatMinimum', 'string', inlineFunctions._formatLimit); + ajv.addKeyword('formatExclusiveMaximum'); + ajv.addKeyword('formatExclusiveMinimum'); - delete: (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (args.length !== 1) { - return false; - } + ajv.addKeyword('patternGroups'); // implemented in properties.jst + _addKeyword('patternRequired', 'object'); + _addKeyword('switch'); - const key = args[0]; - const yarnConfig = config.registries.yarn; - yield yarnConfig.saveHomeConfig({ [key]: undefined }); - reporter.success(reporter.lang('configDelete', key)); - return true; - }); - return function _delete(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); + function _addKeyword(keyword, types, inlineFunc) { + var definition = { + inline: inlineFunc || inlineFunctions[keyword], + statements: true, + errors: 'full' }; - })(), - - list(config, reporter, flags, args) { - if (args.length) { - return false; - } - - reporter.info(reporter.lang('configYarn')); - reporter.inspect(config.registries.yarn.config); - - reporter.info(reporter.lang('configNpm')); - reporter.inspect(config.registries.npm.config); - - return true; + if (types) definition.type = types; + ajv.addKeyword(keyword, definition); } -}); - -const run = _buildSubCommands.run, - setFlags = _buildSubCommands.setFlags, - examples = _buildSubCommands.examples; -exports.run = run; -exports.setFlags = setFlags; -exports.examples = examples; - -/***/ }), -/* 337 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = undefined; - -var _toArray2; - -function _load_toArray() { - return _toArray2 = _interopRequireDefault(__webpack_require__(67)); } -var _asyncToGenerator2; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function containsMacro(schema) { + return { + not: { items: { not: schema } } + }; } -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - var _args = (0, (_toArray2 || _load_toArray()).default)(args); - - const builderName = _args[0], - rest = _args.slice(1); - if (!builderName) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName')); - } +/***/ }), +/* 370 */ +/***/ (function(module, exports, __webpack_require__) { - const packageName = builderName.replace(/^(@[^\/]+\/)?/, '$1create-'); - const commandName = packageName.replace(/^@[^\/]+\//, ''); +"use strict"; - yield (0, (_global || _load_global()).run)(config, reporter, {}, ['add', packageName]); +var ESC = '\u001b['; +var x = module.exports; - for (const registry of (_index || _load_index()).registryNames) { - const packagePath = `${config.globalFolder}/${config.registries[registry].folder}/${packageName}`; +x.cursorTo = function (x, y) { + if (arguments.length === 0) { + return ESC + 'H'; + } - if (!(yield (_fs || _load_fs()).exists(packagePath))) { - continue; - } + if (arguments.length === 1) { + return ESC + (x + 1) + 'G'; + } - const manifest = yield config.tryManifest(packagePath, registry, false); + return ESC + (y + 1) + ';' + (x + 1) + 'H'; +}; - if (!manifest || !manifest.bin) { - continue; - } +x.cursorMove = function (x, y) { + var ret = ''; - let binPath; + if (x < 0) { + ret += ESC + (-x) + 'D'; + } else if (x > 0) { + ret += ESC + x + 'C'; + } - if (typeof manifest.bin === 'string') { - binPath = (0, (_path || _load_path()).resolve)(packagePath, manifest.bin); - } else if (typeof manifest.bin === 'object' && manifest.bin[commandName]) { - binPath = (0, (_path || _load_path()).resolve)(packagePath, manifest.bin[commandName]); - } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('createInvalidBin', packageName)); - } + if (y < 0) { + ret += ESC + (-y) + 'A'; + } else if (y > 0) { + ret += ESC + y + 'B'; + } - yield (_child || _load_child()).spawn(binPath, rest, { stdio: `inherit` }); - return; - } + return ret; +}; - throw new (_errors || _load_errors()).MessageError(reporter.lang('createMissingPackage')); - }); +x.cursorUp = function (count) { + return ESC + (typeof count === 'number' ? count : 1) + 'A'; +}; - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); +x.cursorDown = function (count) { + return ESC + (typeof count === 'number' ? count : 1) + 'B'; +}; -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; +x.cursorForward = function (count) { + return ESC + (typeof count === 'number' ? count : 1) + 'C'; +}; -var _path; +x.cursorBackward = function (count) { + return ESC + (typeof count === 'number' ? count : 1) + 'D'; +}; -function _load_path() { - return _path = __webpack_require__(1); -} +x.cursorLeft = ESC + '1000D'; +x.cursorSavePosition = ESC + 's'; +x.cursorRestorePosition = ESC + 'u'; +x.cursorGetPosition = ESC + '6n'; +x.cursorNextLine = ESC + 'E'; +x.cursorPrevLine = ESC + 'F'; +x.cursorHide = ESC + '?25l'; +x.cursorShow = ESC + '?25h'; -var _errors; +x.eraseLines = function (count) { + var clear = ''; -function _load_errors() { - return _errors = __webpack_require__(3); -} + for (var i = 0; i < count; i++) { + clear += x.cursorLeft + x.eraseEndLine + (i < count - 1 ? x.cursorUp() : ''); + } -var _index; + return clear; +}; -function _load_index() { - return _index = __webpack_require__(24); -} +x.eraseEndLine = ESC + 'K'; +x.eraseStartLine = ESC + '1K'; +x.eraseLine = ESC + '2K'; +x.eraseDown = ESC + 'J'; +x.eraseUp = ESC + '1J'; +x.eraseScreen = ESC + '2J'; +x.scrollUp = ESC + 'S'; +x.scrollDown = ESC + 'T'; -var _child; +x.clearScreen = '\u001bc'; +x.beep = '\u0007'; -function _load_child() { - return _child = _interopRequireWildcard(__webpack_require__(45)); -} +x.image = function (buf, opts) { + opts = opts || {}; -var _fs; + var ret = '\u001b]1337;File=inline=1'; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + if (opts.width) { + ret += ';width=' + opts.width; + } -var _global; + if (opts.height) { + ret += ';height=' + opts.height; + } -function _load_global() { - return _global = __webpack_require__(59); -} + if (opts.preserveAspectRatio === false) { + ret += ';preserveAspectRatio=0'; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return ret + ':' + buf.toString('base64') + '\u0007'; +}; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +x.iTerm = {}; -function setFlags(commander) {} +x.iTerm.setCwd = function (cwd) { + return '\u001b]50;CurrentDir=' + (cwd || process.cwd()) + '\u0007'; +}; -function hasWrapper(commander, args) { - return true; -} /***/ }), -/* 338 */ +/* 371 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/* WEBPACK VAR INJECTION */(function(module) { +function assembleStyles () { + var styles = { + modifiers: { + reset: [0, 0], + bold: [1, 22], // 21 isn't widely supported and 22 does the same thing + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + colors: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39] + }, + bgColors: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49] + } + }; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = undefined; - -var _toArray2; - -function _load_toArray() { - return _toArray2 = _interopRequireDefault(__webpack_require__(67)); -} - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const env = yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).makeEnv)(`exec`, config.cwd, config); - - if (args.length < 1) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('execMissingCommand')); - } - - var _args = (0, (_toArray2 || _load_toArray()).default)(args); - - const execName = _args[0], - rest = _args.slice(1); - - yield (_child || _load_child()).spawn(execName, rest, { stdio: 'inherit', env }); - }); - - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); - -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; - -var _errors; + // fix humans + styles.colors.grey = styles.colors.gray; -function _load_errors() { - return _errors = __webpack_require__(3); -} + Object.keys(styles).forEach(function (groupName) { + var group = styles[groupName]; -var _child; + Object.keys(group).forEach(function (styleName) { + var style = group[styleName]; -function _load_child() { - return _child = _interopRequireWildcard(__webpack_require__(45)); -} + styles[styleName] = group[styleName] = { + open: '\u001b[' + style[0] + 'm', + close: '\u001b[' + style[1] + 'm' + }; + }); -var _executeLifecycleScript; + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + }); -function _load_executeLifecycleScript() { - return _executeLifecycleScript = __webpack_require__(62); + return styles; } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function setFlags(commander) {} +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); -function hasWrapper(commander, args) { - return true; -} +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 339 */ +/* 372 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/*! + * arr-diff <https://github.com/jonschlinkert/arr-diff> + * + * Copyright (c) 2014 Jon Schlinkert, contributors. + * Licensed under the MIT License + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.examples = exports.run = undefined; - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - let manifest; - if (flags.useManifest) { - manifest = yield config.readJson(flags.useManifest); - } else { - manifest = yield config.readRootManifest(); - } - if (!manifest.name) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('noName')); - } - if (!manifest.version) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('noVersion')); - } +var flatten = __webpack_require__(373); +var slice = [].slice; - const entry = { - name: manifest.name, - version: manifest.version, - resolved: flags.resolved, - registry: flags.registry || manifest._registry, - optionalDependencies: manifest.optionalDependencies, - dependencies: manifest.dependencies - }; - const pattern = flags.pattern || `${entry.name}@${entry.version}`; - console.log((0, (_stringify || _load_stringify()).default)({ - [pattern]: (0, (_wrapper || _load_wrapper()).implodeEntry)(pattern, entry) - })); - }); +/** + * Return the difference between the first array and + * additional arrays. + * + * ```js + * var diff = require('{%= name %}'); + * + * var a = ['a', 'b', 'c', 'd']; + * var b = ['b', 'c']; + * + * console.log(diff(a, b)) + * //=> ['a', 'd'] + * ``` + * + * @param {Array} `a` + * @param {Array} `b` + * @return {Array} + * @api public + */ - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); +function diff(arr, arrays) { + var argsLen = arguments.length; + var len = arr.length, i = -1; + var res = [], arrays; -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; + if (argsLen === 1) { + return arr; + } -var _errors; + if (argsLen > 2) { + arrays = flatten(slice.call(arguments, 1)); + } -function _load_errors() { - return _errors = __webpack_require__(3); + while (++i < len) { + if (!~arrays.indexOf(arr[i])) { + res.push(arr[i]); + } + } + return res; } -var _wrapper; +/** + * Expose `diff` + */ -function _load_wrapper() { - return _wrapper = __webpack_require__(14); -} +module.exports = diff; -var _stringify; -function _load_stringify() { - return _stringify = _interopRequireDefault(__webpack_require__(81)); -} +/***/ }), +/* 373 */ +/***/ (function(module, exports, __webpack_require__) { -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +"use strict"; +/*! + * arr-flatten <https://github.com/jonschlinkert/arr-flatten> + * + * Copyright (c) 2014-2015, 2017, Jon Schlinkert. + * Released under the MIT License. + */ -function hasWrapper(commander, args) { - return false; -} -function setFlags(commander) { - commander.option('--use-manifest <location>', 'description'); - commander.option('--resolved <resolved>', 'description'); - commander.option('--registry <registry>', 'description'); + +module.exports = function flatten(arr) { + return flat(arr, []); +}; + +function flat(arr, acc) { + var len = arr.length; + var idx = -1; + + while (++idx < len) { + var cur = arr[idx]; + if (Array.isArray(cur)) { + flat(cur, acc); + } else { + acc.push(cur); + } + } + return acc; } -const examples = exports.examples = ['generate-lock-entry', 'generate-lock-entry --use-manifest ./package.json', 'generate-lock-entry --resolved local-file.tgz#hash']; /***/ }), -/* 340 */ +/* 374 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +module.exports = function (arr, predicate, ctx) { + if (typeof Array.prototype.findIndex === 'function') { + return arr.findIndex(predicate, ctx); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hasWrapper = hasWrapper; -exports.setFlags = setFlags; -exports.run = run; + if (typeof predicate !== 'function') { + throw new TypeError('predicate must be a function'); + } -var _index; + var list = Object(arr); + var len = list.length; -function _load_index() { - return _index = _interopRequireDefault(__webpack_require__(190)); -} + if (len === 0) { + return -1; + } -var _constants; + for (var i = 0; i < len; i++) { + if (predicate.call(ctx, list[i], i, list)) { + return i; + } + } -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + return -1; +}; -var _misc; -function _load_misc() { - return _misc = __webpack_require__(10); -} +/***/ }), +/* 375 */ +/***/ (function(module, exports, __webpack_require__) { -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +"use strict"; +/*! + * array-unique <https://github.com/jonschlinkert/array-unique> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const chalk = __webpack_require__(15); -function hasWrapper(flags, args) { - return false; -} +module.exports = function unique(arr) { + if (!Array.isArray(arr)) { + throw new TypeError('array-unique expects an array.'); + } -function setFlags(commander) {} + var len = arr.length; + var i = -1; -function run(config, reporter, commander, args) { - if (args.length) { - const commandName = args.shift(); - if (Object.prototype.hasOwnProperty.call((_index || _load_index()).default, commandName)) { - const command = (_index || _load_index()).default[commandName]; - if (command) { - command.setFlags(commander); - const examples = command && command.examples || []; - if (examples.length) { - commander.on('--help', () => { - console.log(' Examples:\n'); - for (const example of examples) { - console.log(` $ yarn ${example}`); - } - console.log(); - }); - } - commander.on('--help', () => console.log(' ' + command.getDocsInfo + '\n')); - commander.help(); - return Promise.resolve(); + while (i++ < len) { + var j = i + 1; + + for (; j < arr.length; ++j) { + if (arr[i] === arr[j]) { + arr.splice(j--, 1); } } } + return arr; +}; - commander.on('--help', () => { - const getDocsLink = name => `${(_constants || _load_constants()).YARN_DOCS}${name || ''}`; - console.log(' Commands:\n'); - for (const name of Object.keys((_index || _load_index()).default).sort((_misc || _load_misc()).sortAlpha)) { - if ((_index || _load_index()).default[name].useless) { - continue; - } - console.log(` - ${(0, (_misc || _load_misc()).hyphenate)(name)}`); - } - console.log('\n Run `' + chalk.bold('yarn help COMMAND') + '` for more information on specific commands.'); - console.log(' Visit ' + chalk.bold(getDocsLink()) + ' to learn more about Yarn.\n'); - }); +/***/ }), +/* 376 */ +/***/ (function(module, exports, __webpack_require__) { - commander.help(); - return Promise.resolve(); +// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. + +var errors = __webpack_require__(154); +var types = __webpack_require__(155); + +var Reader = __webpack_require__(377); +var Writer = __webpack_require__(378); + + +///--- Exports + +module.exports = { + + Reader: Reader, + + Writer: Writer + +}; + +for (var t in types) { + if (types.hasOwnProperty(t)) + module.exports[t] = types[t]; +} +for (var e in errors) { + if (errors.hasOwnProperty(e)) + module.exports[e] = errors[e]; } + /***/ }), -/* 341 */ +/* 377 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. +var assert = __webpack_require__(18); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.Import = exports.noArguments = undefined; +var ASN1 = __webpack_require__(155); +var errors = __webpack_require__(154); -var _asyncToGenerator2; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +///--- Globals -let run = exports.run = (() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const imp = new Import(flags, config, reporter, new (_wrapper || _load_wrapper()).default({})); - yield imp.init(); - }); +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - return function run(_x2, _x3, _x4, _x5) { - return _ref3.apply(this, arguments); - }; -})(); -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; -var _install; +///--- API -function _load_install() { - return _install = __webpack_require__(23); -} +function Reader(data) { + if (!data || !Buffer.isBuffer(data)) + throw new TypeError('data must be a node Buffer'); -var _check; + this._buf = data; + this._size = data.length; -function _load_check() { - return _check = __webpack_require__(188); + // These hold the "current" state + this._len = 0; + this._offset = 0; } -var _errors; +Object.defineProperty(Reader.prototype, 'length', { + enumerable: true, + get: function () { return (this._len); } +}); -function _load_errors() { - return _errors = __webpack_require__(3); -} +Object.defineProperty(Reader.prototype, 'offset', { + enumerable: true, + get: function () { return (this._offset); } +}); -var _baseResolver; +Object.defineProperty(Reader.prototype, 'remain', { + get: function () { return (this._size - this._offset); } +}); -function _load_baseResolver() { - return _baseResolver = _interopRequireDefault(__webpack_require__(83)); -} +Object.defineProperty(Reader.prototype, 'buffer', { + get: function () { return (this._buf.slice(this._offset)); } +}); -var _hostedGitResolver; -function _load_hostedGitResolver() { - return _hostedGitResolver = _interopRequireDefault(__webpack_require__(52)); -} +/** + * Reads a single byte and advances offset; you can pass in `true` to make this + * a "peek" operation (i.e., get the byte, but don't advance the offset). + * + * @param {Boolean} peek true means don't move offset. + * @return {Number} the next byte, null if not enough data. + */ +Reader.prototype.readByte = function(peek) { + if (this._size - this._offset < 1) + return null; -var _hostedGitResolver2; + var b = this._buf[this._offset] & 0xff; -function _load_hostedGitResolver2() { - return _hostedGitResolver2 = __webpack_require__(52); -} + if (!peek) + this._offset += 1; -var _gistResolver; + return b; +}; -function _load_gistResolver() { - return _gistResolver = _interopRequireDefault(__webpack_require__(125)); -} -var _gistResolver2; +Reader.prototype.peek = function() { + return this.readByte(true); +}; -function _load_gistResolver2() { - return _gistResolver2 = __webpack_require__(125); -} -var _gitResolver; +/** + * Reads a (potentially) variable length off the BER buffer. This call is + * not really meant to be called directly, as callers have to manipulate + * the internal buffer afterwards. + * + * As a result of this call, you can call `Reader.length`, until the + * next thing called that does a readLength. + * + * @return {Number} the amount of offset to advance the buffer. + * @throws {InvalidAsn1Error} on bad ASN.1 + */ +Reader.prototype.readLength = function(offset) { + if (offset === undefined) + offset = this._offset; -function _load_gitResolver() { - return _gitResolver = _interopRequireDefault(__webpack_require__(61)); -} + if (offset >= this._size) + return null; -var _fileResolver; + var lenB = this._buf[offset++] & 0xff; + if (lenB === null) + return null; -function _load_fileResolver() { - return _fileResolver = _interopRequireDefault(__webpack_require__(204)); -} + if ((lenB & 0x80) == 0x80) { + lenB &= 0x7f; -var _packageResolver; + if (lenB == 0) + throw newInvalidAsn1Error('Indefinite length not supported'); -function _load_packageResolver() { - return _packageResolver = _interopRequireDefault(__webpack_require__(201)); -} + if (lenB > 4) + throw newInvalidAsn1Error('encoding too long'); -var _packageRequest; + if (this._size - offset < lenB) + return null; -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); -} + this._len = 0; + for (var i = 0; i < lenB; i++) + this._len = (this._len << 8) + (this._buf[offset++] & 0xff); -var _packageFetcher; + } else { + // Wasn't a variable length + this._len = lenB; + } -function _load_packageFetcher() { - return _packageFetcher = _interopRequireWildcard(__webpack_require__(200)); -} + return offset; +}; -var _packageLinker; -function _load_packageLinker() { - return _packageLinker = _interopRequireDefault(__webpack_require__(122)); -} +/** + * Parses the next sequence in this BER buffer. + * + * To get the length of the sequence, call `Reader.length`. + * + * @return {Number} the sequence's tag. + */ +Reader.prototype.readSequence = function(tag) { + var seq = this.peek(); + if (seq === null) + return null; + if (tag !== undefined && tag !== seq) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + seq.toString(16)); -var _packageCompatibility; + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; -function _load_packageCompatibility() { - return _packageCompatibility = _interopRequireWildcard(__webpack_require__(199)); -} + this._offset = o; + return seq; +}; -var _wrapper; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} +Reader.prototype.readInt = function() { + return this._readTag(ASN1.Integer); +}; -var _fs; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} +Reader.prototype.readBoolean = function() { + return (this._readTag(ASN1.Boolean) === 0 ? false : true); +}; -var _misc; -function _load_misc() { - return _misc = _interopRequireWildcard(__webpack_require__(10)); -} +Reader.prototype.readEnumeration = function() { + return this._readTag(ASN1.Enumeration); +}; -var _constants; -function _load_constants() { - return _constants = __webpack_require__(8); -} +Reader.prototype.readString = function(tag, retbuf) { + if (!tag) + tag = ASN1.OctetString; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var b = this.peek(); + if (b === null) + return null; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); -const NPM_REGISTRY = /http[s]:\/\/registry.npmjs.org/g; + var o = this.readLength(this._offset + 1); // stored in `length` -const invariant = __webpack_require__(5); -const path = __webpack_require__(1); -const uuid = __webpack_require__(58); + if (o === null) + return null; -const noArguments = exports.noArguments = true; + if (this.length > this._size - o) + return null; -class ImportResolver extends (_baseResolver || _load_baseResolver()).default { - getCwd() { - if (this.request.parentRequest) { - const parent = this.resolver.getStrictResolvedPattern(this.request.parentRequest.pattern); - invariant(parent._loc, 'expected package location'); - return path.dirname(parent._loc); - } - return this.config.cwd; - } + this._offset = o; - resolveHostedGit(info, Resolver) { - var _PackageRequest$norma = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern); + if (this.length === 0) + return retbuf ? new Buffer(0) : ''; - const range = _PackageRequest$norma.range; + var str = this._buf.slice(this._offset, this._offset + this.length); + this._offset += this.length; - const exploded = (0, (_hostedGitResolver2 || _load_hostedGitResolver2()).explodeHostedGitFragment)(range, this.reporter); - const hash = info.gitHead; - invariant(hash, 'expected package gitHead'); - const url = Resolver.getTarballUrl(exploded, hash); - info._uid = hash; - info._remote = { - resolved: url, - type: 'tarball', - registry: this.registry, - reference: url, - hash: null - }; - return info; - } + return retbuf ? str : str.toString('utf8'); +}; - resolveGist(info, Resolver) { - var _PackageRequest$norma2 = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern); +Reader.prototype.readOID = function(tag) { + if (!tag) + tag = ASN1.OID; - const range = _PackageRequest$norma2.range; + var b = this.readString(tag, true); + if (b === null) + return null; - var _explodeGistFragment = (0, (_gistResolver2 || _load_gistResolver2()).explodeGistFragment)(range, this.reporter); + var values = []; + var value = 0; - const id = _explodeGistFragment.id; + for (var i = 0; i < b.length; i++) { + var byte = b[i] & 0xff; - const hash = info.gitHead; - invariant(hash, 'expected package gitHead'); - const url = `https://gist.github.com/${id}.git`; - info._uid = hash; - info._remote = { - resolved: `${url}#${hash}`, - type: 'git', - registry: this.registry, - reference: url, - hash - }; - return info; + value <<= 7; + value += byte & 0x7f; + if ((byte & 0x80) == 0) { + values.push(value); + value = 0; + } } - resolveGit(info, Resolver) { - const url = info._resolved; - const hash = info.gitHead; - invariant(url, 'expected package _resolved'); - invariant(hash, 'expected package gitHead'); - info._uid = hash; - info._remote = { - resolved: `${url}#${hash}`, - type: 'git', - registry: this.registry, - reference: url, - hash - }; - return info; - } + value = values.shift(); + values.unshift(value % 40); + values.unshift((value / 40) >> 0); - resolveFile(info, Resolver) { - var _PackageRequest$norma3 = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern); + return values.join('.'); +}; - const range = _PackageRequest$norma3.range; - let loc = (_misc || _load_misc()).removePrefix(range, 'file:'); - if (!path.isAbsolute(loc)) { - loc = path.join(this.config.cwd, loc); - } - info._uid = info.version; - info._remote = { - type: 'copy', - registry: this.registry, - hash: `${uuid.v4()}-${new Date().getTime()}`, - reference: loc - }; - return info; - } +Reader.prototype._readTag = function(tag) { + assert.ok(tag !== undefined); - resolveRegistry(info) { - let url = info._resolved; - const hash = info._shasum; - invariant(url, 'expected package _resolved'); - invariant(hash, 'expected package _shasum'); - if (this.config.getOption('registry') === (_constants || _load_constants()).YARN_REGISTRY) { - url = url.replace(NPM_REGISTRY, (_constants || _load_constants()).YARN_REGISTRY); - } - info._uid = info.version; - info._remote = { - resolved: `${url}#${hash}`, - type: 'tarball', - registry: this.registry, - reference: url, - hash - }; - return info; - } + var b = this.peek(); + + if (b === null) + return null; - resolveImport(info) { - var _PackageRequest$norma4 = (_packageRequest || _load_packageRequest()).default.normalizePattern(this.pattern); + if (b !== tag) + throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) + + ': got 0x' + b.toString(16)); - const range = _PackageRequest$norma4.range; + var o = this.readLength(this._offset + 1); // stored in `length` + if (o === null) + return null; - const Resolver = (_packageRequest || _load_packageRequest()).default.getExoticResolver(range); - if (Resolver && Resolver.prototype instanceof (_hostedGitResolver || _load_hostedGitResolver()).default) { - return this.resolveHostedGit(info, Resolver); - } else if (Resolver && Resolver === (_gistResolver || _load_gistResolver()).default) { - return this.resolveGist(info, Resolver); - } else if (Resolver && Resolver === (_gitResolver || _load_gitResolver()).default) { - return this.resolveGit(info, Resolver); - } else if (Resolver && Resolver === (_fileResolver || _load_fileResolver()).default) { - return this.resolveFile(info, Resolver); - } - return this.resolveRegistry(info); - } + if (this.length > 4) + throw newInvalidAsn1Error('Integer too long: ' + this.length); - resolveLocation(loc) { - var _this = this; + if (this.length > this._size - o) + return null; + this._offset = o; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const info = yield _this.config.tryManifest(loc, 'npm', false); - if (!info) { - return null; - } - return _this.resolveImport(info); - })(); + var fb = this._buf[this._offset]; + var value = 0; + + for (var i = 0; i < this.length; i++) { + value <<= 8; + value |= (this._buf[this._offset++] & 0xff); } - resolve() { - var _this2 = this; + if ((fb & 0x80) == 0x80 && i !== 4) + value -= (1 << (i * 8)); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - var _PackageRequest$norma5 = (_packageRequest || _load_packageRequest()).default.normalizePattern(_this2.pattern); + return value >> 0; +}; - const name = _PackageRequest$norma5.name; - let cwd = _this2.getCwd(); - while (!path.relative(_this2.config.cwd, cwd).startsWith('..')) { - const loc = path.join(cwd, 'node_modules', name); - const info = yield _this2.config.getCache(`import-resolver-${loc}`, function () { - return _this2.resolveLocation(loc); - }); - if (info) { - return info; - } - cwd = path.resolve(cwd, '../..'); - } - throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('importResolveFailed', name, _this2.getCwd())); - })(); - } -} -class ImportPackageRequest extends (_packageRequest || _load_packageRequest()).default { - constructor(req, resolver) { - super(req, resolver); - this.import = this.parentRequest instanceof ImportPackageRequest ? this.parentRequest.import : true; - } +///--- Exported API - getRootName() { - return this.resolver instanceof ImportPackageResolver && this.resolver.rootName || 'root'; - } +module.exports = Reader; - getParentHumanName() { - return [this.getRootName()].concat(this.getParentNames()).join(' > '); - } - reportResolvedRangeMatch(info, resolved) { - if (info.version === resolved.version) { - return; - } - this.reporter.warn(this.reporter.lang('importResolvedRangeMatch', resolved.version, resolved.name, info.version, this.getParentHumanName())); - } +/***/ }), +/* 378 */ +/***/ (function(module, exports, __webpack_require__) { - findVersionInfo() { - if (!this.import) { - this.reporter.verbose(this.reporter.lang('skippingImport', this.pattern, this.getParentHumanName())); - return super.findVersionInfo(); - } - const resolver = new ImportResolver(this, this.pattern); - return resolver.resolve().catch(() => { - this.import = false; - this.reporter.warn(this.reporter.lang('importFailed', this.pattern, this.getParentHumanName())); - return super.findVersionInfo(); - }); - } -} +// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved. -class ImportPackageResolver extends (_packageResolver || _load_packageResolver()).default { - constructor(config, lockfile) { - super(config, lockfile); - this.next = []; - this.rootName = 'root'; - } +var assert = __webpack_require__(18); +var ASN1 = __webpack_require__(155); +var errors = __webpack_require__(154); - find(req) { - this.next.push(req); - return Promise.resolve(); - } - findOne(req) { - var _this3 = this; +///--- Globals - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (_this3.activity) { - _this3.activity.tick(req.pattern); - } - const request = new ImportPackageRequest(req, _this3); - yield request.find({ fresh: false }); - })(); - } +var newInvalidAsn1Error = errors.newInvalidAsn1Error; - findAll(deps) { - var _this4 = this; +var DEFAULT_OPTS = { + size: 1024, + growthFactor: 8 +}; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield Promise.all(deps.map(function (dep) { - return _this4.findOne(dep); - })); - deps = _this4.next; - _this4.next = []; - if (!deps.length) { - // all required package versions have been discovered, so now packages that - // resolved to existing versions can be resolved to their best available version - _this4.resolvePackagesWithExistingVersions(); - return; - } - yield _this4.findAll(deps); - })(); - } - resetOptional() { - for (const pattern in this.patterns) { - const ref = this.patterns[pattern]._reference; - invariant(ref, 'expected reference'); - ref.optional = null; - for (const req of ref.requests) { - ref.addOptional(req.optional); - } - } - } +///--- Helpers - init(deps) { - var _this5 = this; +function merge(from, to) { + assert.ok(from); + assert.equal(typeof(from), 'object'); + assert.ok(to); + assert.equal(typeof(to), 'object'); - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { isFlat: false, isFrozen: false, workspaceLayout: undefined }; + var keys = Object.getOwnPropertyNames(from); + keys.forEach(function(key) { + if (to[key]) + return; - let isFlat = _ref.isFlat, - isFrozen = _ref.isFrozen, - workspaceLayout = _ref.workspaceLayout; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this5.flat = Boolean(isFlat); - const activity = _this5.activity = _this5.reporter.activity(); - yield _this5.findAll(deps); - _this5.resetOptional(); - activity.end(); - _this5.activity = null; - })(); - } + var value = Object.getOwnPropertyDescriptor(from, key); + Object.defineProperty(to, key, value); + }); + + return to; } -class Import extends (_install || _load_install()).Install { - constructor(flags, config, reporter, lockfile) { - super(flags, config, reporter, lockfile); - this.resolver = new ImportPackageResolver(this.config, this.lockfile); - this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver); - } - init() { - var _this6 = this; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (yield (_fs || _load_fs()).exists(path.join(_this6.config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME))) { - throw new (_errors || _load_errors()).MessageError(_this6.reporter.lang('lockfileExists')); - } - yield (0, (_check || _load_check()).verifyTreeCheck)(_this6.config, _this6.reporter, {}, []); +///--- API - var _ref2 = yield _this6.fetchRequestFromCwd(); +function Writer(options) { + options = merge(DEFAULT_OPTS, options || {}); - const requests = _ref2.requests, - patterns = _ref2.patterns, - manifest = _ref2.manifest; + this._buf = new Buffer(options.size || 1024); + this._size = this._buf.length; + this._offset = 0; + this._options = options; - if (manifest.name && _this6.resolver instanceof ImportPackageResolver) { - _this6.resolver.rootName = manifest.name; - } - yield _this6.resolver.init(requests, { isFlat: _this6.flags.flat, isFrozen: _this6.flags.frozenLockfile }); - const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this6.resolver.getManifests(), _this6.config); - _this6.resolver.updateManifests(manifests); - yield (_packageCompatibility || _load_packageCompatibility()).check(_this6.resolver.getManifests(), _this6.config, _this6.flags.ignoreEngines); - yield _this6.linker.resolvePeerModules(); - yield _this6.saveLockfileAndIntegrity(patterns); - return patterns; - })(); - } + // A list of offsets in the buffer where we need to insert + // sequence tag/len pairs. + this._seq = []; } -exports.Import = Import; -function setFlags(commander) {} +Object.defineProperty(Writer.prototype, 'buffer', { + get: function () { + if (this._seq.length) + throw new InvalidAsn1Error(this._seq.length + ' unended sequence(s)'); -function hasWrapper(commander, args) { - return true; -} + return (this._buf.slice(0, this._offset)); + } +}); -/***/ }), -/* 342 */ -/***/ (function(module, exports, __webpack_require__) { +Writer.prototype.writeByte = function(b) { + if (typeof(b) !== 'number') + throw new TypeError('argument must be a Number'); -"use strict"; + this._ensure(1); + this._buf[this._offset++] = b; +}; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = undefined; +Writer.prototype.writeInt = function(i, tag) { + if (typeof(i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof(tag) !== 'number') + tag = ASN1.Integer; -var _asyncToGenerator2; + var sz = 4; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) && + (sz > 1)) { + sz--; + i <<= 8; + } -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (args.length > 2) { - reporter.error(reporter.lang('tooManyArguments', 2)); - return; - } + if (sz > 4) + throw new InvalidAsn1Error('BER ints cannot be > 0xffffffff'); - let packageName = args.shift() || '.'; + this._ensure(2 + sz); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = sz; - // Handle the case when we are referencing a local package. - if (packageName === '.') { - packageName = (yield config.readRootManifest()).name; - } + while (sz-- > 0) { + this._buf[this._offset++] = ((i & 0xff000000) >>> 24); + i <<= 8; + } - const packageInput = (_npmRegistry || _load_npmRegistry()).default.escapeName(packageName); +}; - var _parsePackageName = (0, (_parsePackageName2 || _load_parsePackageName()).default)(packageInput); - const name = _parsePackageName.name, - version = _parsePackageName.version; +Writer.prototype.writeNull = function() { + this.writeByte(ASN1.Null); + this.writeByte(0x00); +}; - // pass application/json Accept to get full metadata for info command - let result = yield config.registries.npm.request(name, { - headers: { Accept: 'application/json' } - }); - if (!result) { - reporter.error(reporter.lang('infoFail')); - return; - } +Writer.prototype.writeEnumeration = function(i, tag) { + if (typeof(i) !== 'number') + throw new TypeError('argument must be a Number'); + if (typeof(tag) !== 'number') + tag = ASN1.Enumeration; - result = clean(result); + return this.writeInt(i, tag); +}; - const versions = result.versions; - // $FlowFixMe - result.versions = Object.keys(versions).sort(semver.compareLoose); - result.version = version || result.versions[result.versions.length - 1]; - result = Object.assign(result, versions[result.version]); - const fieldPath = args.shift(); - const fields = fieldPath ? fieldPath.split('.') : []; +Writer.prototype.writeBoolean = function(b, tag) { + if (typeof(b) !== 'boolean') + throw new TypeError('argument must be a Boolean'); + if (typeof(tag) !== 'number') + tag = ASN1.Boolean; - // Readmes can be long so exclude them unless explicitly asked for. - if (fields[0] !== 'readme') { - delete result.readme; - } + this._ensure(3); + this._buf[this._offset++] = tag; + this._buf[this._offset++] = 0x01; + this._buf[this._offset++] = b ? 0xff : 0x00; +}; - result = fields.reduce(function (prev, cur) { - return prev && prev[cur]; - }, result); - reporter.inspect(result); - }); - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); +Writer.prototype.writeString = function(s, tag) { + if (typeof(s) !== 'string') + throw new TypeError('argument must be a string (was: ' + typeof(s) + ')'); + if (typeof(tag) !== 'number') + tag = ASN1.OctetString; -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; + var len = Buffer.byteLength(s); + this.writeByte(tag); + this.writeLength(len); + if (len) { + this._ensure(len); + this._buf.write(s, this._offset); + this._offset += len; + } +}; -var _npmRegistry; -function _load_npmRegistry() { - return _npmRegistry = _interopRequireDefault(__webpack_require__(43)); -} +Writer.prototype.writeBuffer = function(buf, tag) { + if (typeof(tag) !== 'number') + throw new TypeError('tag must be a number'); + if (!Buffer.isBuffer(buf)) + throw new TypeError('argument must be a buffer'); -var _parsePackageName2; + this.writeByte(tag); + this.writeLength(buf.length); + this._ensure(buf.length); + buf.copy(this._buf, this._offset, 0, buf.length); + this._offset += buf.length; +}; -function _load_parsePackageName() { - return _parsePackageName2 = _interopRequireDefault(__webpack_require__(390)); -} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +Writer.prototype.writeStringArray = function(strings) { + if ((!strings instanceof Array)) + throw new TypeError('argument must be an Array[String]'); -const semver = __webpack_require__(27); + var self = this; + strings.forEach(function(s) { + self.writeString(s); + }); +}; -function clean(object) { - if (Array.isArray(object)) { - const result = []; - object.forEach(item => { - item = clean(item); - if (item) { - result.push(item); - } - }); - return result; - } else if (typeof object === 'object') { - const result = {}; - for (const key in object) { - if (key.startsWith('_')) { - continue; - } +// This is really to solve DER cases, but whatever for now +Writer.prototype.writeOID = function(s, tag) { + if (typeof(s) !== 'string') + throw new TypeError('argument must be a string'); + if (typeof(tag) !== 'number') + tag = ASN1.OID; - const item = clean(object[key]); - if (item) { - result[key] = item; - } + if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) + throw new Error('argument is not a valid OID string'); + + function encodeOctet(bytes, octet) { + if (octet < 128) { + bytes.push(octet); + } else if (octet < 16384) { + bytes.push((octet >>> 7) | 0x80); + bytes.push(octet & 0x7F); + } else if (octet < 2097152) { + bytes.push((octet >>> 14) | 0x80); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else if (octet < 268435456) { + bytes.push((octet >>> 21) | 0x80); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); + } else { + bytes.push(((octet >>> 28) | 0x80) & 0xFF); + bytes.push(((octet >>> 21) | 0x80) & 0xFF); + bytes.push(((octet >>> 14) | 0x80) & 0xFF); + bytes.push(((octet >>> 7) | 0x80) & 0xFF); + bytes.push(octet & 0x7F); } - return result; - } else if (object) { - return object; - } else { - return null; } -} - -function setFlags(commander) {} -function hasWrapper(commander, args) { - return true; -} - -/***/ }), -/* 343 */ -/***/ (function(module, exports, __webpack_require__) { + var tmp = s.split('.'); + var bytes = []; + bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); + tmp.slice(2).forEach(function(b) { + encodeOctet(bytes, parseInt(b, 10)); + }); -"use strict"; + var self = this; + this._ensure(2 + bytes.length); + this.writeByte(tag); + this.writeLength(bytes.length); + bytes.forEach(function(b) { + self.writeByte(b); + }); +}; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.getGitConfigInfo = exports.run = undefined; +Writer.prototype.writeLength = function(len) { + if (typeof(len) !== 'number') + throw new TypeError('argument must be a Number'); -var _asyncToGenerator2; + this._ensure(4); -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + if (len <= 0x7f) { + this._buf[this._offset++] = len; + } else if (len <= 0xff) { + this._buf[this._offset++] = 0x81; + this._buf[this._offset++] = len; + } else if (len <= 0xffff) { + this._buf[this._offset++] = 0x82; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else if (len <= 0xffffff) { + this._buf[this._offset++] = 0x83; + this._buf[this._offset++] = len >> 16; + this._buf[this._offset++] = len >> 8; + this._buf[this._offset++] = len; + } else { + throw new InvalidAsn1ERror('Length too long (> 4 bytes)'); + } +}; -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const manifests = yield config.getRootManifests(); +Writer.prototype.startSequence = function(tag) { + if (typeof(tag) !== 'number') + tag = ASN1.Sequence | ASN1.Constructor; - let repository = {}; - const author = { - name: config.getOption('init-author-name'), - email: config.getOption('init-author-email'), - url: config.getOption('init-author-url') - }; - if (yield (_fs || _load_fs()).exists(path.join(config.cwd, '.git'))) { - // get git origin of the cwd - try { - repository = { - type: 'git', - url: yield (_child || _load_child()).spawn('git', ['config', 'remote.origin.url'], { - cwd: config.cwd - }) - }; - } catch (ex) { - // Ignore - Git repo may not have an origin URL yet (eg. if it only exists locally) - } + this.writeByte(tag); + this._seq.push(this._offset); + this._ensure(3); + this._offset += 3; +}; - if (author.name === undefined) { - author.name = yield getGitConfigInfo('user.name'); - } - if (author.email === undefined) { - author.email = yield getGitConfigInfo('user.email'); - } - } +Writer.prototype.endSequence = function() { + var seq = this._seq.pop(); + var start = seq + 3; + var len = this._offset - start; - const keys = [{ - key: 'name', - question: 'name', - default: path.basename(config.cwd), - validation: (_validate || _load_validate()).isValidPackageName, - validationError: 'invalidPackageName' - }, { - key: 'version', - question: 'version', - default: String(config.getOption('init-version')) - }, { - key: 'description', - question: 'description', - default: '' - }, { - key: 'main', - question: 'entry point', - default: 'index.js' - }, { - key: 'repository', - question: 'repository url', - default: (0, (_util || _load_util()).extractRepositoryUrl)(repository) - }, { - key: 'author', - question: 'author', - default: (0, (_util || _load_util()).stringifyPerson)(author) - }, { - key: 'license', - question: 'license', - default: String(config.getOption('init-license')) - }]; + if (len <= 0x7f) { + this._shift(start, len, -2); + this._buf[seq] = len; + } else if (len <= 0xff) { + this._shift(start, len, -1); + this._buf[seq] = 0x81; + this._buf[seq + 1] = len; + } else if (len <= 0xffff) { + this._buf[seq] = 0x82; + this._buf[seq + 1] = len >> 8; + this._buf[seq + 2] = len; + } else if (len <= 0xffffff) { + this._shift(start, len, 1); + this._buf[seq] = 0x83; + this._buf[seq + 1] = len >> 16; + this._buf[seq + 2] = len >> 8; + this._buf[seq + 3] = len; + } else { + throw new InvalidAsn1Error('Sequence too long'); + } +}; - // get answers - const pkg = {}; - for (const entry of keys) { - const yes = flags.yes; - const manifestKey = entry.key; - let question = entry.question, - def = entry.default; +Writer.prototype._shift = function(start, len, shift) { + assert.ok(start !== undefined); + assert.ok(len !== undefined); + assert.ok(shift); - for (const registryName of (_index || _load_index()).registryNames) { - const object = manifests[registryName].object; + this._buf.copy(this._buf, start + shift, start, start + len); + this._offset += shift; +}; - let val = objectPath.get(object, manifestKey); - if (!val) { - break; - } - if (typeof val === 'object') { - if (manifestKey === 'author') { - val = (0, (_util || _load_util()).stringifyPerson)(val); - } else if (manifestKey === 'repository') { - val = (0, (_util || _load_util()).extractRepositoryUrl)(val); - } - } - def = val; - } +Writer.prototype._ensure = function(len) { + assert.ok(len); - if (def) { - question += ` (${def})`; - } + if (this._size - this._offset < len) { + var sz = this._size * this._options.growthFactor; + if (sz - this._offset < len) + sz += len; - let answer; - let validAnswer = false; + var buf = new Buffer(sz); - if (yes) { - answer = def; - } else { - // loop until a valid answer is provided, if validation is on entry - if (entry.validation) { - while (!validAnswer) { - answer = (yield reporter.question(question)) || def; - // validate answer - if (entry.validation(String(answer))) { - validAnswer = true; - } else { - reporter.error(reporter.lang('invalidPackageName')); - } - } - } else { - answer = (yield reporter.question(question)) || def; - } - } + this._buf.copy(buf, 0, 0, this._offset); + this._buf = buf; + this._size = sz; + } +}; - if (answer) { - objectPath.set(pkg, manifestKey, answer); - } - } - // save answers - const targetManifests = []; - for (const registryName of (_index || _load_index()).registryNames) { - const info = manifests[registryName]; - if (info.exists) { - targetManifests.push(info); - } - } - if (!targetManifests.length) { - targetManifests.push(manifests.npm); - } - for (const targetManifest of targetManifests) { - Object.assign(targetManifest.object, pkg); - reporter.success(`Saved ${path.basename(targetManifest.loc)}`); - } - yield config.saveRootManifests(manifests); - }); +///--- Exported API - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); +module.exports = Writer; -let getGitConfigInfo = exports.getGitConfigInfo = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (credential) { - let spawn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_child || _load_child()).spawn; - try { - // try to get author default based on git config - return yield spawn('git', ['config', credential]); - } catch (e) { - return ''; - } - }); +/***/ }), +/* 379 */ +/***/ (function(module, exports, __webpack_require__) { - return function getGitConfigInfo(_x5) { - return _ref2.apply(this, arguments); - }; -})(); +module.exports = +{ + parallel : __webpack_require__(381), + serial : __webpack_require__(382), + serialOrdered : __webpack_require__(251) +}; -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; -var _util; +/***/ }), +/* 380 */ +/***/ (function(module, exports) { -function _load_util() { - return _util = __webpack_require__(130); -} +module.exports = defer; -var _index; +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); -function _load_index() { - return _index = __webpack_require__(24); + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } } -var _child; -function _load_child() { - return _child = _interopRequireWildcard(__webpack_require__(45)); -} +/***/ }), +/* 381 */ +/***/ (function(module, exports, __webpack_require__) { -var _fs; +var iterate = __webpack_require__(248) + , initState = __webpack_require__(249) + , terminator = __webpack_require__(250) + ; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} +// Public API +module.exports = parallel; -var _validate; +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); -function _load_validate() { - return _validate = _interopRequireWildcard(__webpack_require__(63)); + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } + + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; + } + + return terminator.bind(state, callback); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), +/* 382 */ +/***/ (function(module, exports, __webpack_require__) { -const objectPath = __webpack_require__(247); +var serialOrdered = __webpack_require__(251); -const path = __webpack_require__(1); +// Public API +module.exports = serial; -function setFlags(commander) { - commander.option('-y, --yes', 'use default options'); +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); } -function hasWrapper(commander, args) { - return true; -} /***/ }), -/* 344 */ +/* 383 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +/*! + * Copyright 2010 LearnBoost <dev@learnboost.com> + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.examples = exports.setFlags = exports.run = undefined; +/** + * Module dependencies. + */ -var _slicedToArray2; +var crypto = __webpack_require__(8) + , parse = __webpack_require__(14).parse + ; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} +/** + * Valid keys. + */ -var _extends2; +var keys = + [ 'acl' + , 'location' + , 'logging' + , 'notification' + , 'partNumber' + , 'policy' + , 'requestPayment' + , 'torrent' + , 'uploadId' + , 'uploads' + , 'versionId' + , 'versioning' + , 'versions' + , 'website' + ] -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(36)); +/** + * Return an "Authorization" header value with the given `options` + * in the form of "AWS <key>:<signature>" + * + * @param {Object} options + * @return {String} + * @api private + */ + +function authorization (options) { + return 'AWS ' + options.key + ':' + sign(options) } -var _asyncToGenerator2; +module.exports = authorization +module.exports.authorization = authorization -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +/** + * Simple HMAC-SHA1 Wrapper + * + * @param {Object} options + * @return {String} + * @api private + */ -let getManifests = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags) { - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); - const install = new (_install || _load_install()).Install((0, (_extends2 || _load_extends()).default)({ skipIntegrityCheck: true }, flags), config, new (_baseReporter || _load_baseReporter()).default(), lockfile); - yield install.hydrate(true); +function hmacSha1 (options) { + return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') +} - let manifests = install.resolver.getManifests(); +module.exports.hmacSha1 = hmacSha1 - // sort by name - manifests = manifests.sort(function (a, b) { - if (!a.name && !b.name) { - return 0; - } +/** + * Create a base64 sha1 HMAC for `options`. + * + * @param {Object} options + * @return {String} + * @api private + */ - if (!a.name) { - return 1; - } +function sign (options) { + options.message = stringToSign(options) + return hmacSha1(options) +} +module.exports.sign = sign - if (!b.name) { - return -1; - } +/** + * Create a base64 sha1 HMAC for `options`. + * + * Specifically to be used with S3 presigned URLs + * + * @param {Object} options + * @return {String} + * @api private + */ - return a.name.localeCompare(b.name); - }); +function signQuery (options) { + options.message = queryStringToSign(options) + return hmacSha1(options) +} +module.exports.signQuery= signQuery - // filter ignored manifests - manifests = manifests.filter(function (manifest) { - const ref = manifest._reference; - return !!ref && !ref.ignore; - }); +/** + * Return a string for sign() with the given `options`. + * + * Spec: + * + * <verb>\n + * <md5>\n + * <content-type>\n + * <date>\n + * [headers\n] + * <resource> + * + * @param {Object} options + * @return {String} + * @api private + */ - return manifests; - }); +function stringToSign (options) { + var headers = options.amazonHeaders || '' + if (headers) headers += '\n' + var r = + [ options.verb + , options.md5 + , options.contentType + , options.date ? options.date.toUTCString() : '' + , headers + options.resource + ] + return r.join('\n') +} +module.exports.queryStringToSign = stringToSign - return function getManifests(_x, _x2) { - return _ref.apply(this, arguments); - }; -})(); +/** + * Return a string for sign() with the given `options`, but is meant exclusively + * for S3 presigned URLs + * + * Spec: + * + * <date>\n + * <resource> + * + * @param {Object} options + * @return {String} + * @api private + */ -exports.hasWrapper = hasWrapper; +function queryStringToSign (options){ + return 'GET\n\n\n' + options.date + '\n' + options.resource +} +module.exports.queryStringToSign = queryStringToSign -var _baseReporter; +/** + * Perform the following: + * + * - ignore non-amazon headers + * - lowercase fields + * - sort lexicographically + * - trim whitespace between ":" + * - join with newline + * + * @param {Object} headers + * @return {String} + * @api private + */ -function _load_baseReporter() { - return _baseReporter = _interopRequireDefault(__webpack_require__(51)); +function canonicalizeHeaders (headers) { + var buf = [] + , fields = Object.keys(headers) + ; + for (var i = 0, len = fields.length; i < len; ++i) { + var field = fields[i] + , val = headers[field] + , field = field.toLowerCase() + ; + if (0 !== field.indexOf('x-amz')) continue + buf.push(field + ':' + val) + } + return buf.sort().join('\n') } +module.exports.canonicalizeHeaders = canonicalizeHeaders -var _install; +/** + * Perform the following: + * + * - ignore non sub-resources + * - sort lexicographically + * + * @param {String} resource + * @return {String} + * @api private + */ -function _load_install() { - return _install = __webpack_require__(23); +function canonicalizeResource (resource) { + var url = parse(resource, true) + , path = url.pathname + , buf = [] + ; + + Object.keys(url.query).forEach(function(key){ + if (!~keys.indexOf(key)) return + var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) + buf.push(key + val) + }) + + return path + (buf.length ? '?' + buf.sort().join('&') : '') } +module.exports.canonicalizeResource = canonicalizeResource + -var _wrapper; +/***/ }), +/* 384 */ +/***/ (function(module, exports, __webpack_require__) { -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} +var aws4 = exports, + url = __webpack_require__(14), + querystring = __webpack_require__(150), + crypto = __webpack_require__(8), + lru = __webpack_require__(385), + credentialsCache = lru(1000) -var _buildSubCommands2; +// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html -function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); +function hmac(key, string, encoding) { + return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding) } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const invariant = __webpack_require__(5); +function hash(string, encoding) { + return crypto.createHash('sha256').update(string, 'utf8').digest(encoding) +} -function hasWrapper(flags, args) { - return args[0] != 'generate-disclaimer'; +// This function assumes the string has already been percent encoded +function encodeRfc3986(urlEncodedString) { + return urlEncodedString.replace(/[!'()*]/g, function(c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase() + }) } -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('licenses', { - ls(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const manifests = yield getManifests(config, flags); +// request: { path | body, [host], [method], [headers], [service], [region] } +// credentials: { accessKeyId, secretAccessKey, [sessionToken] } +function RequestSigner(request, credentials) { - if (flags.json) { - const body = []; + if (typeof request === 'string') request = url.parse(request) - for (const _ref2 of manifests) { - const name = _ref2.name, - version = _ref2.version, - license = _ref2.license, - repository = _ref2.repository, - homepage = _ref2.homepage, - author = _ref2.author; + var headers = request.headers = (request.headers || {}), + hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host) - const url = repository ? repository.url : homepage; - const vendorUrl = homepage || author && author.url; - const vendorName = author && author.name; - body.push([name, version, license || 'Unknown', url || 'Unknown', vendorUrl || 'Unknown', vendorName || 'Unknown']); - } + this.request = request + this.credentials = credentials || this.defaultCredentials() - reporter.table(['Name', 'Version', 'License', 'URL', 'VendorUrl', 'VendorName'], body); - } else { - const trees = []; - - for (const _ref3 of manifests) { - const name = _ref3.name, - version = _ref3.version, - license = _ref3.license, - repository = _ref3.repository, - homepage = _ref3.homepage; - - const children = []; - children.push({ - name: `${reporter.format.bold('License:')} ${license || reporter.format.red('UNKNOWN')}` - }); + this.service = request.service || hostParts[0] || '' + this.region = request.region || hostParts[1] || 'us-east-1' - const url = repository ? repository.url : homepage; - if (url) { - children.push({ name: `${reporter.format.bold('URL:')} ${url}` }); - } + // SES uses a different domain from the service name + if (this.service === 'email') this.service = 'ses' - trees.push({ - name: `${name}@${version}`, - children - }); - } + if (!request.method && request.body) + request.method = 'POST' - reporter.tree('licenses', trees); - } - })(); - }, + if (!headers.Host && !headers.host) { + headers.Host = request.hostname || request.host || this.createHost() - generateDisclaimer(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const manifests = yield getManifests(config, flags); - const manifest = yield config.readRootManifest(); + // If a port is specified explicitly, use it as is + if (request.port) + headers.Host += ':' + request.port + } + if (!request.hostname && !request.host) + request.hostname = headers.Host || headers.host - // Create a map of license text to manifest so that packages with exactly - // the same license text are grouped together. - const manifestsByLicense = new Map(); - for (const manifest of manifests) { - const licenseText = manifest.licenseText; + this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT' +} - if (!licenseText) { - continue; - } +RequestSigner.prototype.matchHost = function(host) { + var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com$/) + var hostParts = (match || []).slice(1, 3) - if (!manifestsByLicense.has(licenseText)) { - manifestsByLicense.set(licenseText, new Map()); - } + // ES's hostParts are sometimes the other way round, if the value that is expected + // to be region equals ‘es’ switch them back + // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com + if (hostParts[1] === 'es') + hostParts = hostParts.reverse() - const byLicense = manifestsByLicense.get(licenseText); - invariant(byLicense, 'expected value'); - byLicense.set(manifest.name, manifest); - } + return hostParts +} - console.log('THE FOLLOWING SETS FORTH ATTRIBUTION NOTICES FOR THIRD PARTY SOFTWARE THAT MAY BE CONTAINED ' + `IN PORTIONS OF THE ${String(manifest.name).toUpperCase().replace(/-/g, ' ')} PRODUCT.`); - console.log(); +// http://docs.aws.amazon.com/general/latest/gr/rande.html +RequestSigner.prototype.isSingleRegion = function() { + // Special case for S3 and SimpleDB in us-east-1 + if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true - for (const _ref4 of manifestsByLicense) { - var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2); + return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts'] + .indexOf(this.service) >= 0 +} - const licenseText = _ref5[0]; - const manifests = _ref5[1]; +RequestSigner.prototype.createHost = function() { + var region = this.isSingleRegion() ? '' : + (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region, + service = this.service === 'ses' ? 'email' : this.service + return service + region + '.amazonaws.com' +} - console.log('-----'); - console.log(); +RequestSigner.prototype.prepareRequest = function() { + this.parsePath() - const names = []; - const urls = []; - for (const _ref6 of manifests) { - var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2); + var request = this.request, headers = request.headers, query - const name = _ref7[0]; - const repository = _ref7[1].repository; + if (request.signQuery) { - names.push(name); - if (repository && repository.url) { - urls.push(manifests.size === 1 ? repository.url : `${repository.url} (${name})`); - } - } + this.parsedPath.query = query = this.parsedPath.query || {} - const heading = []; - heading.push(`The following software may be included in this product: ${names.join(', ')}.`); - if (urls.length > 0) { - heading.push(`A copy of the source code may be downloaded from ${urls.join(', ')}.`); - } - heading.push('This software contains the following license and notice below:'); + if (this.credentials.sessionToken) + query['X-Amz-Security-Token'] = this.credentials.sessionToken - console.log(heading.join(' ')); - console.log(); + if (this.service === 's3' && !query['X-Amz-Expires']) + query['X-Amz-Expires'] = 86400 - if (licenseText) { - console.log(licenseText.trim()); - } else { - // what do we do here? base it on `license`? - } + if (query['X-Amz-Date']) + this.datetime = query['X-Amz-Date'] + else + query['X-Amz-Date'] = this.getDateTime() - console.log(); - } - })(); - } -}); + query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256' + query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString() + query['X-Amz-SignedHeaders'] = this.signedHeaders() -const run = _buildSubCommands.run, - setFlags = _buildSubCommands.setFlags, - examples = _buildSubCommands.examples; -exports.run = run; -exports.setFlags = setFlags; -exports.examples = examples; + } else { -/***/ }), -/* 345 */ -/***/ (function(module, exports, __webpack_require__) { + if (!request.doNotModifyHeaders && !this.isCodeCommitGit) { + if (request.body && !headers['Content-Type'] && !headers['content-type']) + headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8' -"use strict"; + if (request.body && !headers['Content-Length'] && !headers['content-length']) + headers['Content-Length'] = Buffer.byteLength(request.body) + if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token']) + headers['X-Amz-Security-Token'] = this.credentials.sessionToken -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = undefined; + if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256']) + headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex') -var _asyncToGenerator2; + if (headers['X-Amz-Date'] || headers['x-amz-date']) + this.datetime = headers['X-Amz-Date'] || headers['x-amz-date'] + else + headers['X-Amz-Date'] = this.getDateTime() + } -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + delete headers.Authorization + delete headers.authorization + } } -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - yield config.registries.yarn.saveHomeConfig({ - username: undefined, - email: undefined - }); - - reporter.success(reporter.lang('clearedCredentials')); - }); - - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); - -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; +RequestSigner.prototype.sign = function() { + if (!this.parsedPath) this.prepareRequest() -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (this.request.signQuery) { + this.parsedPath.query['X-Amz-Signature'] = this.signature() + } else { + this.request.headers.Authorization = this.authHeader() + } -function setFlags(commander) {} + this.request.path = this.formatPath() -function hasWrapper(commander, args) { - return true; + return this.request } -/***/ }), -/* 346 */ -/***/ (function(module, exports, __webpack_require__) { +RequestSigner.prototype.getDateTime = function() { + if (!this.datetime) { + var headers = this.request.headers, + date = new Date(headers.Date || headers.date || new Date) -"use strict"; + this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '') + // Remove the trailing 'Z' on the timestamp string for CodeCommit git access + if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1) + } + return this.datetime +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = exports.requireLockfile = undefined; +RequestSigner.prototype.getDate = function() { + return this.getDateTime().substr(0, 8) +} -var _asyncToGenerator2; +RequestSigner.prototype.authHeader = function() { + return [ + 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(), + 'SignedHeaders=' + this.signedHeaders(), + 'Signature=' + this.signature(), + ].join(', ') +} -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +RequestSigner.prototype.signature = function() { + var date = this.getDate(), + cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(), + kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey) + if (!kCredentials) { + kDate = hmac('AWS4' + this.credentials.secretAccessKey, date) + kRegion = hmac(kDate, this.region) + kService = hmac(kRegion, this.service) + kCredentials = hmac(kService, 'aws4_request') + credentialsCache.set(cacheKey, kCredentials) + } + return hmac(kCredentials, this.stringToSign(), 'hex') } -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.cwd); - const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); - let deps = yield (_packageRequest || _load_packageRequest()).default.getOutdatedPackages(lockfile, install, config, reporter); +RequestSigner.prototype.stringToSign = function() { + return [ + 'AWS4-HMAC-SHA256', + this.getDateTime(), + this.credentialString(), + hash(this.canonicalString(), 'hex'), + ].join('\n') +} - if (args.length) { - const requested = new Set(args); +RequestSigner.prototype.canonicalString = function() { + if (!this.parsedPath) this.prepareRequest() - deps = deps.filter(function (_ref2) { - let name = _ref2.name; - return requested.has(name); - }); - } + var pathStr = this.parsedPath.path, + query = this.parsedPath.query, + headers = this.request.headers, + queryStr = '', + normalizePath = this.service !== 's3', + decodePath = this.service === 's3' || this.request.doNotEncodePath, + decodeSlashesInPath = this.service === 's3', + firstValOnly = this.service === 's3', + bodyHash - const getNameFromHint = function (hint) { - return hint ? `${hint}Dependencies` : 'dependencies'; - }; - const getColorFromVersion = function (_ref3) { - let current = _ref3.current, - wanted = _ref3.wanted, - name = _ref3.name; - return current === wanted ? reporter.format.yellow(name) : reporter.format.red(name); - }; + if (this.service === 's3' && this.request.signQuery) { + bodyHash = 'UNSIGNED-PAYLOAD' + } else if (this.isCodeCommitGit) { + bodyHash = '' + } else { + bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] || + hash(this.request.body || '', 'hex') + } - if (deps.length) { - const body = deps.map(function (info) { - return [getColorFromVersion(info), info.current, reporter.format.green(info.wanted), reporter.format.magenta(info.latest), getNameFromHint(info.hint), reporter.format.cyan(info.url)]; - }); + if (query) { + queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) { + if (!key) return obj + obj[key] = !Array.isArray(query[key]) ? query[key] : + (firstValOnly ? query[key][0] : query[key].slice().sort()) + return obj + }, {}))) + } + if (pathStr !== '/') { + if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/') + pathStr = pathStr.split('/').reduce(function(path, piece) { + if (normalizePath && piece === '..') { + path.pop() + } else if (!normalizePath || piece !== '.') { + if (decodePath) piece = querystring.unescape(piece) + path.push(encodeRfc3986(querystring.escape(piece))) + } + return path + }, []).join('/') + if (pathStr[0] !== '/') pathStr = '/' + pathStr + if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/') + } - reporter.table(['Package', 'Current', 'Wanted', 'Latest', 'Package Type', 'URL'], body); - return 1; - } - return 0; - }); + return [ + this.request.method || 'GET', + pathStr, + queryStr, + this.canonicalHeaders() + '\n', + this.signedHeaders(), + bodyHash, + ].join('\n') +} - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); +RequestSigner.prototype.canonicalHeaders = function() { + var headers = this.request.headers + function trimAll(header) { + return header.toString().trim().replace(/\s+/g, ' ') + } + return Object.keys(headers) + .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 }) + .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) }) + .join('\n') +} -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; +RequestSigner.prototype.signedHeaders = function() { + return Object.keys(this.request.headers) + .map(function(key) { return key.toLowerCase() }) + .sort() + .join(';') +} -var _packageRequest; +RequestSigner.prototype.credentialString = function() { + return [ + this.getDate(), + this.region, + this.service, + 'aws4_request', + ].join('/') +} -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); +RequestSigner.prototype.defaultCredentials = function() { + var env = process.env + return { + accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY, + secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY, + sessionToken: env.AWS_SESSION_TOKEN, + } } -var _wrapper; +RequestSigner.prototype.parsePath = function() { + var path = this.request.path || '/', + queryIx = path.indexOf('?'), + query = null -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} + if (queryIx >= 0) { + query = querystring.parse(path.slice(queryIx + 1)) + path = path.slice(0, queryIx) + } -var _install; + // S3 doesn't always encode characters > 127 correctly and + // all services don't encode characters > 255 correctly + // So if there are non-reserved chars (and it's not already all % encoded), just encode them all + if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) { + path = path.split('/').map(function(piece) { + return querystring.escape(querystring.unescape(piece)) + }).join('/') + } -function _load_install() { - return _install = __webpack_require__(23); + this.parsedPath = { + path: path, + query: query, + } } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +RequestSigner.prototype.formatPath = function() { + var path = this.parsedPath.path, + query = this.parsedPath.query -const requireLockfile = exports.requireLockfile = true; + if (!query) return path -function setFlags(commander) { - commander.usage('outdated [packages ...]'); -} + // Services don't support empty query string keys + if (query[''] != null) delete query[''] -function hasWrapper(commander, args) { - return true; + return path + '?' + encodeRfc3986(querystring.stringify(query)) } -/***/ }), -/* 347 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; +aws4.RequestSigner = RequestSigner +aws4.sign = function(request, credentials) { + return new RequestSigner(request, credentials).sign() +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.examples = exports.hasWrapper = exports.setFlags = exports.run = exports.mutate = undefined; -var _asyncToGenerator2; +/***/ }), +/* 385 */ +/***/ (function(module, exports) { -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +module.exports = function(size) { + return new LruCache(size) } -let mutate = exports.mutate = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args, config, reporter, buildMessages, mutator) { - if (args.length !== 2 && args.length !== 1) { - return false; - } - - const username = args.shift(); - const name = yield (0, (_tag || _load_tag()).getName)(args, config); - if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName')); - } +function LruCache(size) { + this.capacity = size | 0 + this.map = Object.create(null) + this.list = new DoublyLinkedList() +} - const msgs = buildMessages(username, name); - reporter.step(1, 3, reporter.lang('loggingIn')); - const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); +LruCache.prototype.get = function(key) { + var node = this.map[key] + if (node == null) return undefined + this.used(node) + return node.val +} - reporter.step(2, 3, msgs.info); - const user = yield config.registries.npm.request(`-/user/org.couchdb.user:${username}`); - let error = false; - if (user) { - // get package - const pkg = yield config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(name)); - if (pkg) { - pkg.maintainers = pkg.maintainers || []; - error = mutator({ name: user.name, email: user.email }, pkg); - } else { - error = true; - reporter.error(reporter.lang('unknownPackage', name)); - } +LruCache.prototype.set = function(key, val) { + var node = this.map[key] + if (node != null) { + node.val = val + } else { + if (!this.capacity) this.prune() + if (!this.capacity) return false + node = new DoublyLinkedNode(key, val) + this.map[key] = node + this.capacity-- + } + this.used(node) + return true +} - // update package - if (pkg && !error) { - const res = yield config.registries.npm.request(`${(_npmRegistry || _load_npmRegistry()).default.escapeName(name)}/-rev/${pkg._rev}`, { - method: 'PUT', - body: { - _id: pkg._id, - _rev: pkg._rev, - maintainers: pkg.maintainers - } - }); +LruCache.prototype.used = function(node) { + this.list.moveToFront(node) +} - if (res != null && res.success) { - reporter.success(msgs.success); - } else { - error = true; - reporter.error(msgs.error); - } - } - } else { - error = true; - reporter.error(reporter.lang('unknownUser', username)); - } +LruCache.prototype.prune = function() { + var node = this.list.pop() + if (node != null) { + delete this.map[node.key] + this.capacity++ + } +} - reporter.step(3, 3, reporter.lang('revokingToken')); - yield revoke(); - if (error) { - throw new Error(); - } else { - return true; - } - }); +function DoublyLinkedList() { + this.firstNode = null + this.lastNode = null +} - return function mutate(_x, _x2, _x3, _x4, _x5) { - return _ref.apply(this, arguments); - }; -})(); +DoublyLinkedList.prototype.moveToFront = function(node) { + if (this.firstNode == node) return -var _errors; + this.remove(node) -function _load_errors() { - return _errors = __webpack_require__(3); + if (this.firstNode == null) { + this.firstNode = node + this.lastNode = node + node.prev = null + node.next = null + } else { + node.prev = null + node.next = this.firstNode + node.next.prev = node + this.firstNode = node + } } -var _buildSubCommands2; +DoublyLinkedList.prototype.pop = function() { + var lastNode = this.lastNode + if (lastNode != null) { + this.remove(lastNode) + } + return lastNode +} -function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); +DoublyLinkedList.prototype.remove = function(node) { + if (this.firstNode == node) { + this.firstNode = node.next + } else if (node.prev != null) { + node.prev.next = node.next + } + if (this.lastNode == node) { + this.lastNode = node.prev + } else if (node.next != null) { + node.next.prev = node.prev + } } -var _validate; -function _load_validate() { - return _validate = __webpack_require__(63); +function DoublyLinkedNode(key, val) { + this.key = key + this.val = val + this.prev = null + this.next = null } -var _tag; -function _load_tag() { - return _tag = __webpack_require__(194); -} +/***/ }), +/* 386 */ +/***/ (function(module, exports, __webpack_require__) { -var _login; +"use strict"; -function _load_login() { - return _login = __webpack_require__(60); -} -var _npmRegistry; +Object.defineProperty(exports, "__esModule", { + value: true +}); -function _load_npmRegistry() { - return _npmRegistry = _interopRequireDefault(__webpack_require__(43)); +exports.default = function (message) { + return { + useless: true, + run() { + throw new (_errors || _load_errors()).MessageError(message); + }, + setFlags: () => {}, + hasWrapper: () => true + }; +}; + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +/***/ }), +/* 387 */ +/***/ (function(module, exports, __webpack_require__) { -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('owner', { - add(config, reporter, flags, args) { - return mutate(args, config, reporter, (username, name) => ({ - info: reporter.lang('ownerAdding', username, name), - success: reporter.lang('ownerAdded'), - error: reporter.lang('ownerAddingFailed') - }), (user, pkg) => { - for (const owner of pkg.maintainers) { - if (owner.name === user) { - reporter.error(reporter.lang('ownerAlready')); - return true; - } - } +"use strict"; - pkg.maintainers.push(user); - return false; - }); - }, +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.examples = exports.hasWrapper = exports.setFlags = exports.run = undefined; - rm(config, reporter, flags, args) { - return mutate(args, config, reporter, (username, name) => ({ - info: reporter.lang('ownerRemoving', username, name), - success: reporter.lang('ownerRemoved'), - error: reporter.lang('ownerRemoveError') - }), (user, pkg) => { - let found = false; +var _buildSubCommands2; - pkg.maintainers = pkg.maintainers.filter(o => { - const match = o.name === user.name; - found = found || match; - return !match; - }); +function _load_buildSubCommands() { + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); +} - if (!found) { - reporter.error(reporter.lang('userNotAnOwner', user.name)); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return found; - }); +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('access', { + public() { + return Promise.reject(new Error('TODO')); }, - ls(config, reporter, flags, args) { - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (args.length > 1) { - return false; - } + restricted() { + return Promise.reject(new Error('TODO')); + }, - const name = yield (0, (_tag || _load_tag()).getName)(args, config); + grant() { + return Promise.reject(new Error('TODO')); + }, - reporter.step(1, 3, reporter.lang('loggingIn')); - const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); + revoke() { + return Promise.reject(new Error('TODO')); + }, - reporter.step(2, 3, reporter.lang('ownerGetting', name)); - const pkg = yield config.registries.npm.request(name); - if (pkg) { - const owners = pkg.maintainers; - if (!owners || !owners.length) { - reporter.warn(reporter.lang('ownerNone')); - } else { - for (const owner of owners) { - reporter.info(`${owner.name} <${owner.email}>`); - } - } - } else { - reporter.error(reporter.lang('ownerGettingFailed')); - } + lsPackages() { + return Promise.reject(new Error('TODO')); + }, - reporter.step(3, 3, reporter.lang('revokingToken')); - yield revoke(); + lsCollaborators() { + return Promise.reject(new Error('TODO')); + }, - if (pkg) { - return true; - } else { - throw new Error(); - } - })(); + edit() { + return Promise.reject(new Error('TODO')); } -}, ['add <user> [[<@scope>/]<pkg>]', 'rm <user> [[<@scope>/]<pkg>]', 'ls [<@scope>/]<pkg>']); +}, ['access public [<package>]', 'access restricted [<package>]', 'access grant <read-only|read-write> <scope:team> [<package>]', 'access revoke <scope:team> [<package>]', 'access ls-packages [<user>|<scope>|<scope:team>]', 'access ls-collaborators [<package> [<user>]]', 'access edit [<package>]']); const run = _buildSubCommands.run, setFlags = _buildSubCommands.setFlags, @@ -76337,7 +80485,7 @@ exports.hasWrapper = hasWrapper; exports.examples = examples; /***/ }), -/* 348 */ +/* 388 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76346,217 +80494,34 @@ exports.examples = examples; Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = undefined; - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -let publish = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, pkg, flags, dir) { - // validate access argument - const access = flags.access; - if (access && access !== 'public' && access !== 'restricted') { - throw new (_errors || _load_errors()).MessageError(config.reporter.lang('invalidAccess')); - } - - // get tarball stream - const stat = yield (_fs || _load_fs()).lstat(dir); - let stream; - if (stat.isDirectory()) { - stream = yield (0, (_pack || _load_pack()).pack)(config, dir); - } else if (stat.isFile()) { - stream = fs2.createReadStream(dir); - } else { - throw new Error("Don't know how to handle this file type"); - } - const buffer = yield new Promise(function (resolve, reject) { - const data = []; - invariant(stream, 'expected stream'); - stream.on('data', data.push.bind(data)).on('end', function () { - return resolve(Buffer.concat(data)); - }).on('error', reject); - }); - - // copy normalized package and remove internal keys as they may be sensitive or yarn specific - pkg = Object.assign({}, pkg); - for (const key in pkg) { - if (key[0] === '_') { - delete pkg[key]; - } - } - - const tag = flags.tag || 'latest'; - const tbName = `${pkg.name}-${pkg.version}.tgz`; - const tbURI = `${pkg.name}/-/${tbName}`; - - // TODO this might modify package.json, do we need to reload it? - yield config.executeLifecycleScript('prepublish'); - yield config.executeLifecycleScript('prepublishOnly'); - yield config.executeLifecycleScript('prepare'); - - // create body - const root = { - _id: pkg.name, - access: flags.access, - name: pkg.name, - description: pkg.description, - 'dist-tags': { - [tag]: pkg.version - }, - versions: { - [pkg.version]: pkg - }, - readme: pkg.readme || '', - _attachments: { - [tbName]: { - content_type: 'application/octet-stream', - data: buffer.toString('base64'), - length: buffer.length - } - } - }; - - pkg._id = `${pkg.name}@${pkg.version}`; - pkg.dist = pkg.dist || {}; - pkg.dist.shasum = crypto.createHash('sha1').update(buffer).digest('hex'); - - const registry = String(config.getOption('registry')); - pkg.dist.tarball = url.resolve(registry, tbURI).replace(/^https:\/\//, 'http://'); - - // publish package - const res = yield config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(pkg.name), { - method: 'PUT', - body: root - }); - - if (res !== null && (0, (_misc || _load_misc()).has2xxResponse)(res)) { - yield config.executeLifecycleScript('publish'); - yield config.executeLifecycleScript('postpublish'); - } else { - throw new (_errors || _load_errors()).MessageError(config.reporter.lang('publishFail')); - } - }); - - return function publish(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); - -let run = exports.run = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - // validate package fields that are required for publishing - const pkg = yield config.readRootManifest(); - if (pkg.private) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('publishPrivate')); - } - if (!pkg.name) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('noName')); - } - - // validate arguments - const dir = args[0] || config.cwd; - if (args.length > 1) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('tooManyArguments', 1)); - } - if (!(yield (_fs || _load_fs()).exists(dir))) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownFolderOrTarball')); - } - - // - reporter.step(1, 4, reporter.lang('bumpingVersion')); - const commitVersion = yield (0, (_version || _load_version()).setVersion)(config, reporter, flags, args, false); - - // - reporter.step(2, 4, reporter.lang('loggingIn')); - const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, pkg.name); - - // - reporter.step(3, 4, reporter.lang('publishing')); - yield publish(config, pkg, flags, dir); - yield commitVersion(); - reporter.success(reporter.lang('published')); - - // - reporter.step(4, 4, reporter.lang('revokingToken')); - yield revoke(); - }); - - return function run(_x5, _x6, _x7, _x8) { - return _ref2.apply(this, arguments); - }; -})(); - -exports.setFlags = setFlags; exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; +exports.run = run; -var _npmRegistry; - -function _load_npmRegistry() { - return _npmRegistry = _interopRequireDefault(__webpack_require__(43)); -} - -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); -} - -var _version; - -function _load_version() { - return _version = __webpack_require__(197); -} - -var _fs; - -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} - -var _pack; - -function _load_pack() { - return _pack = __webpack_require__(119); -} - -var _login; - -function _load_login() { - return _login = __webpack_require__(60); -} - -var _misc; +var _yarnResolver; -function _load_misc() { - return _misc = __webpack_require__(10); +function _load_yarnResolver() { + return _yarnResolver = _interopRequireDefault(__webpack_require__(270)); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const invariant = __webpack_require__(5); +const path = __webpack_require__(0); -const crypto = __webpack_require__(7); -const url = __webpack_require__(11); -const fs2 = __webpack_require__(6); - -function setFlags(commander) { - (0, (_version || _load_version()).setFlags)(commander); - commander.usage('publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>]'); - commander.option('--access [access]', 'access'); - commander.option('--tag [tag]', 'tag'); +function hasWrapper(commander) { + return false; } -function hasWrapper(commander, args) { - return true; +function setFlags(commander) {} + +function run(config, reporter, flags, args) { + const binFolder = path.join(config.cwd, config.registries[(_yarnResolver || _load_yarnResolver()).default.registry].folder, '.bin'); + reporter.log(binFolder); + return Promise.resolve(); } /***/ }), -/* 349 */ +/* 389 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76565,185 +80530,189 @@ function hasWrapper(commander, args) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = undefined; - -var _slicedToArray2; - -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} +exports.examples = exports.setFlags = exports.run = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -let run = exports.run = (() => { +let list = (() => { var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - let runCommand = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args) { - const action = args.shift(); - const actions = [`pre${action}`, action, `post${action}`]; - - // build up list of commands - const cmds = []; - for (const action of actions) { - const cmd = scripts[action]; - if (cmd) { - cmds.push([action, cmd]); - } - } + let readCacheMetadata = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let parentDir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : config.cacheFolder; + let metadataFile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_constants || _load_constants()).METADATA_FILENAME; - if (cmds.length) { - // propagate YARN_SILENT env variable to executed commands - process.env.YARN_SILENT = '1'; - for (const _ref3 of cmds) { - var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2); - - const stage = _ref4[0]; - const cmd = _ref4[1]; + const folders = yield (_fs || _load_fs()).readdir(parentDir); + const packagesMetadata = []; - // only tack on trailing arguments for default script, ignore for pre and post - #1595 - const defaultScriptCmd = cmd + joinArgs(args); - const cmdWithArgs = stage === action ? defaultScriptCmd : cmd; - yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execCommand)(stage, config, cmdWithArgs, config.cwd); + for (const folder of folders) { + if (folder[0] === '.') { + continue; } - } else if (action === 'env') { - reporter.info(`${JSON.stringify(process.env, null, 2)}`); - } else { - let suggestion; - for (const commandName in scripts) { - const steps = leven(commandName, action); - if (steps < 2) { - suggestion = commandName; - } - } + const loc = path.join(config.cacheFolder, parentDir.replace(config.cacheFolder, ''), folder); + // Check if this is a scoped package + if (!(yield (_fs || _load_fs()).exists(path.join(loc, metadataFile)))) { + // If so, recurrently read scoped packages metadata + packagesMetadata.push(...(yield readCacheMetadata(loc))); + } else { + var _ref3 = yield config.readPackageMetadata(loc); - let msg = `Command ${JSON.stringify(action)} not found.`; - if (suggestion) { - msg += ` Did you mean ${JSON.stringify(suggestion)}?`; + const registry = _ref3.registry, + manifest = _ref3.package, + remote = _ref3.remote; + + packagesMetadata.push([manifest.name, manifest.version, registry, remote && remote.resolved || '']); } - throw new (_errors || _load_errors()).MessageError(msg); } + + return packagesMetadata; }); - return function runCommand(_x5) { + return function readCacheMetadata() { return _ref2.apply(this, arguments); }; })(); - // list possible scripts if none specified - - - // build up a list of possible scripts - const pkg = yield config.readManifest(config.cwd); - const scripts = (0, (_map || _load_map()).default)(); - const binCommands = []; - const visitedBinFolders = new Set(); - let pkgCommands = []; - for (const registry of Object.keys((_index || _load_index()).registries)) { - const binFolder = path.join(config.cwd, config.registries[registry].folder, '.bin'); - if (!visitedBinFolders.has(binFolder)) { - if (yield (_fs || _load_fs()).exists(binFolder)) { - for (const name of yield (_fs || _load_fs()).readdir(binFolder)) { - binCommands.push(name); - scripts[name] = `"${path.join(binFolder, name)}"`; - } - } - visitedBinFolders.add(binFolder); - } - } - const pkgScripts = pkg.scripts; - const cmdHints = {}; - if (pkgScripts) { - // inherit `scripts` from manifest - pkgCommands = Object.keys(pkgScripts).sort(); - - // add command hints (what the actual yarn command will do) - for (const cmd of pkgCommands) { - cmdHints[cmd] = pkgScripts[cmd] || ''; - } - - Object.assign(scripts, pkg.scripts); - } + const body = yield readCacheMetadata(); - if (args.length === 0) { - reporter.error(reporter.lang('commandNotSpecified')); - reporter.info(`${reporter.lang('binCommands') + binCommands.join(', ')}`); - reporter.info(`${reporter.lang('possibleCommands')}`); - reporter.list('possibleCommands', pkgCommands, cmdHints); - yield reporter.question(reporter.lang('commandQuestion')).then(function (answer) { - return runCommand(answer.split(' ')); - }, function () { - return reporter.error(reporter.lang('commandNotSpecified')); - }); - return Promise.resolve(); - } else { - return runCommand(args); - } + reporter.table(['Name', 'Version', 'Registry', 'Resolved'], body); }); - return function run(_x, _x2, _x3, _x4) { + return function list(_x, _x2, _x3, _x4) { return _ref.apply(this, arguments); }; })(); -exports.setFlags = setFlags; exports.hasWrapper = hasWrapper; -var _executeLifecycleScript; +var _buildSubCommands2; -function _load_executeLifecycleScript() { - return _executeLifecycleScript = __webpack_require__(62); +function _load_buildSubCommands() { + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); } -var _errors; +var _fs; -function _load_errors() { - return _errors = __webpack_require__(3); +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} + +var _constants; + +function _load_constants() { + return _constants = __webpack_require__(6); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const path = __webpack_require__(0); + +function hasWrapper(flags, args) { + return args[0] !== 'dir'; } -var _index; +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('cache', { + ls(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + reporter.warn(`\`yarn cache ls\` is deprecated. Please use \`yarn cache list\`.`); + yield list(config, reporter, flags, args); + })(); + }, + + list(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield list(config, reporter, flags, args); + })(); + }, + + dir(config, reporter) { + reporter.log(config.cacheFolder, { force: true }); + }, + + clean(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + let getPackageCachefolders = (() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (packageName) { + let parentDir = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : config.cacheFolder; + let metadataFile = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (_constants || _load_constants()).METADATA_FILENAME; -function _load_index() { - return _index = __webpack_require__(53); -} + const folders = yield (_fs || _load_fs()).readdir(parentDir); + const packageFolders = []; -var _fs; + for (const folder of folders) { + if (folder[0] === '.') { + continue; + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + const loc = path.join(config.cacheFolder, parentDir.replace(config.cacheFolder, ''), folder); + // Check if this is a scoped package + if (!(yield (_fs || _load_fs()).exists(path.join(loc, metadataFile)))) { + // If so, recurrently read scoped packages metadata + packageFolders.push(...(yield getPackageCachefolders(packageName, loc))); + } else { + var _ref5 = yield config.readPackageMetadata(loc); -var _map; + const manifest = _ref5.package; -function _load_map() { - return _map = _interopRequireDefault(__webpack_require__(25)); -} + if (packageName === manifest.name) { + packageFolders.push(loc); + } + } + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return packageFolders; + }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return function getPackageCachefolders(_x7) { + return _ref4.apply(this, arguments); + }; + })(); -const leven = __webpack_require__(552); + if (config.cacheFolder) { + const activity = reporter.activity(); -const path = __webpack_require__(1); + if (args.length > 0) { + // Clear named package from cache + const folders = yield getPackageCachefolders(args[0]); -// Copied from https://github.com/npm/npm/blob/63f153c743f9354376bfb9dad42bd028a320fd1f/lib/run-script.js#L175 -function joinArgs(args) { - return args.reduce((joinedArgs, arg) => joinedArgs + ' "' + arg.replace(/"/g, '\\"') + '"', ''); -} + if (folders.length === 0) { + activity.end(); + reporter.warn(reporter.lang('couldntClearPackageFromCache', args[0])); + return; + } -function setFlags(commander) {} + for (const folder of folders) { + yield (_fs || _load_fs()).unlink(folder); + } + activity.end(); + reporter.success(reporter.lang('clearedPackageFromCache', args[0])); + } else { + // Clear all cache + yield (_fs || _load_fs()).unlink(config._cacheRootFolder); + yield (_fs || _load_fs()).mkdirp(config.cacheFolder); + activity.end(); + reporter.success(reporter.lang('clearedCache')); + } + } + })(); + } +}); -function hasWrapper(commander, args) { - return true; -} +const run = _buildSubCommands.run, + setFlags = _buildSubCommands.setFlags, + examples = _buildSubCommands.examples; +exports.run = run; +exports.setFlags = setFlags; +exports.examples = examples; /***/ }), -/* 350 */ +/* 390 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76752,213 +80721,106 @@ function hasWrapper(commander, args) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.examples = exports.hasWrapper = exports.setFlags = exports.run = undefined; +exports.examples = exports.setFlags = exports.run = undefined; -var _extends2; +var _slicedToArray2; -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(36)); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _toArray2; - -function _load_toArray() { - return _toArray2 = _interopRequireDefault(__webpack_require__(67)); -} +exports.hasWrapper = hasWrapper; var _buildSubCommands2; function _load_buildSubCommands() { - return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(35)); -} - -var _login; - -function _load_login() { - return _login = __webpack_require__(60); + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function explodeScopeTeam(arg, requireTeam, reporter) { - var _arg$split = arg.split(':'), - _arg$split2 = (0, (_toArray2 || _load_toArray()).default)(_arg$split); - - const scope = _arg$split2[0], - team = _arg$split2[1], - parts = _arg$split2.slice(2); - - if (parts.length) { - return false; - } - - if (requireTeam && !team) { - return false; - } - - return { - scope: scope || '', - team: team || '', - user: '' - }; +function hasWrapper(flags, args) { + return args[0] !== 'get'; } +/* eslint object-shorthand: 0 */ -function wrapRequired(callback, requireTeam) { - return (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (!args.length) { - return false; - } - - const parts = explodeScopeTeam(args[0], requireTeam, reporter); - if (!parts) { +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('config', { + set(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (args.length === 0 || args.length > 2) { return false; } - reporter.step(1, 3, reporter.lang('loggingIn')); - const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter); + var _args = (0, (_slicedToArray2 || _load_slicedToArray()).default)(args, 2); - const res = yield callback(parts, config, reporter, flags, args); - if (!res) { - return res; - } + const key = _args[0]; + var _args$ = _args[1]; + const val = _args$ === undefined ? true : _args$; - reporter.step(3, 3, reporter.lang('revokingToken')); - yield revoke(); + const yarnConfig = config.registries.yarn; + yield yarnConfig.saveHomeConfig({ [key]: val }); + reporter.success(reporter.lang('configSet', key, val)); return true; - }); - - return function (_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; - })(); -} - -function wrapRequiredTeam(callback) { - let requireTeam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - - return wrapRequired(function (parts, config, reporter, flags, args) { - if (args.length === 1) { - return callback(parts, config, reporter, flags, args); - } else { - return false; - } - }, requireTeam); -} + })(); + }, -function wrapRequiredUser(callback) { - return wrapRequired(function (parts, config, reporter, flags, args) { - if (args.length === 2) { - return callback((0, (_extends2 || _load_extends()).default)({ - user: args[1] - }, parts), config, reporter, flags, args); - } else { + get(config, reporter, flags, args) { + if (args.length !== 1) { return false; } - }, true); -} - -var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('team', { - create: wrapRequiredTeam((() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { - reporter.step(2, 3, reporter.lang('teamCreating')); - reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}`, { - method: 'PUT', - body: { - team: parts.team - } - }))); - return true; - }); - - return function (_x6, _x7, _x8, _x9, _x10) { - return _ref2.apply(this, arguments); - }; - })()), - destroy: wrapRequiredTeam((() => { - var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { - reporter.step(2, 3, reporter.lang('teamRemoving')); - reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}`, { - method: 'DELETE' - }))); - return true; - }); + reporter.log(String(config.getOption(args[0]))); + return true; + }, - return function (_x11, _x12, _x13, _x14, _x15) { - return _ref3.apply(this, arguments); - }; - })()), + delete: (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (args.length !== 1) { + return false; + } - add: wrapRequiredUser((() => { - var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { - reporter.step(2, 3, reporter.lang('teamAddingUser')); - reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user`, { - method: 'PUT', - body: { - user: parts.user - } - }))); + const key = args[0]; + const yarnConfig = config.registries.yarn; + yield yarnConfig.saveHomeConfig({ [key]: undefined }); + reporter.success(reporter.lang('configDelete', key)); return true; }); - return function (_x16, _x17, _x18, _x19, _x20) { - return _ref4.apply(this, arguments); + return function _delete(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); }; - })()), + })(), - rm: wrapRequiredUser((() => { - var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { - reporter.step(2, 3, reporter.lang('teamRemovingUser')); - reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user`, { - method: 'DELETE', - body: { - user: parts.user - } - }))); - return true; - }); + list(config, reporter, flags, args) { + if (args.length) { + return false; + } - return function (_x21, _x22, _x23, _x24, _x25) { - return _ref5.apply(this, arguments); - }; - })()), + reporter.info(reporter.lang('configYarn')); + reporter.inspect(config.registries.yarn.config); - ls: wrapRequiredTeam((() => { - var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { - reporter.step(2, 3, reporter.lang('teamListing')); - const uriParams = '?format=cli'; - if (parts.team) { - reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user${uriParams}`))); - } else { - reporter.inspect((yield config.registries.npm.request(`org/${parts.scope}/team${uriParams}`))); - } - return true; - }); + reporter.info(reporter.lang('configNpm')); + reporter.inspect(config.registries.npm.config); - return function (_x26, _x27, _x28, _x29, _x30) { - return _ref6.apply(this, arguments); - }; - })(), false) -}, ['create <scope:team>', 'destroy <scope:team>', 'add <scope:team> <user>', 'rm <scope:team> <user>', 'ls <scope>|<scope:team>']); + return true; + } +}); const run = _buildSubCommands.run, setFlags = _buildSubCommands.setFlags, - hasWrapper = _buildSubCommands.hasWrapper, examples = _buildSubCommands.examples; exports.run = run; exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; exports.examples = examples; /***/ }), -/* 351 */ +/* 391 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -76969,55 +80831,38 @@ Object.defineProperty(exports, "__esModule", { }); exports.run = undefined; +var _toArray2; + +function _load_toArray() { + return _toArray2 = _interopRequireDefault(__webpack_require__(99)); +} + var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } let run = exports.run = (() => { var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (args.length) { - for (const name of args) { - const linkLoc = path.join(config.linkFolder, name); - if (yield (_fs || _load_fs()).exists(linkLoc)) { - yield (_fs || _load_fs()).unlink(path.join((yield (0, (_link || _load_link()).getRegistryFolder)(config, name)), name)); - reporter.success(reporter.lang('linkDisusing', name)); - reporter.info(reporter.lang('linkDisusingMessage', name)); - } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name)); - } - } - } else { - // remove from registry - const manifest = yield config.readRootManifest(); - const name = manifest.name; - if (!name) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownPackageName')); - } - - const linkLoc = path.join(config.linkFolder, name); - if (yield (_fs || _load_fs()).exists(linkLoc)) { - // If there is a `bin` defined in the package.json, - // link each bin to the global bin - if (manifest.bin) { - const globalBinFolder = (0, (_global || _load_global()).getBinFolder)(config, flags); - for (const binName in manifest.bin) { - const binDestLoc = path.join(globalBinFolder, binName); - if (yield (_fs || _load_fs()).exists(binDestLoc)) { - yield (_fs || _load_fs()).unlink(binDestLoc); - } - } - } + var _args = (0, (_toArray2 || _load_toArray()).default)(args); - yield (_fs || _load_fs()).unlink(linkLoc); + const builderName = _args[0], + rest = _args.slice(1); - reporter.success(reporter.lang('linkUnregistered', name)); - reporter.info(reporter.lang('linkUnregisteredMessage', name)); - } else { - throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name)); - } + if (!builderName) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName')); } + + const packageName = builderName.replace(/^(@[^\/]+\/)?/, '$1create-'); + const commandName = packageName.replace(/^@[^\/]+\//, ''); + + yield (0, (_global || _load_global()).run)(config, reporter, {}, ['add', packageName]); + + const binFolder = yield (0, (_global || _load_global()).getBinFolder)(config, {}); + const command = path.resolve(binFolder, path.basename(commandName)); + + yield (_child || _load_child()).spawn(command, [...rest], { stdio: `inherit`, shell: true }); }); return function run(_x, _x2, _x3, _x4) { @@ -77034,29 +80879,23 @@ function _load_errors() { return _errors = __webpack_require__(3); } -var _fs; - -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} - -var _link; +var _child; -function _load_link() { - return _link = __webpack_require__(191); +function _load_child() { + return _child = _interopRequireWildcard(__webpack_require__(48)); } var _global; function _load_global() { - return _global = __webpack_require__(59); + return _global = __webpack_require__(92); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const path = __webpack_require__(1); +const path = __webpack_require__(0); function setFlags(commander) {} @@ -77065,7 +80904,7 @@ function hasWrapper(commander, args) { } /***/ }), -/* 352 */ +/* 392 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -77076,24 +80915,32 @@ Object.defineProperty(exports, "__esModule", { }); exports.run = undefined; +var _toArray2; + +function _load_toArray() { + return _toArray2 = _interopRequireDefault(__webpack_require__(99)); +} + var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } let run = exports.run = (() => { var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const versions = { yarn: (_yarnVersion || _load_yarnVersion()).version }; + const env = yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).makeEnv)(`exec`, config.cwd, config); - const pkg = yield config.maybeReadManifest(config.cwd); - if (pkg && pkg.name && pkg.version) { - versions[pkg.name] = pkg.version; + if (args.length < 1) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('execMissingCommand')); } - Object.assign(versions, process.versions); + var _args = (0, (_toArray2 || _load_toArray()).default)(args); - reporter.inspect(versions); + const execName = _args[0], + rest = _args.slice(1); + + yield (_child || _load_child()).spawn(execName, rest, { stdio: 'inherit', env }); }); return function run(_x, _x2, _x3, _x4) { @@ -77104,12 +80951,26 @@ let run = exports.run = (() => { exports.setFlags = setFlags; exports.hasWrapper = hasWrapper; -var _yarnVersion; +var _errors; -function _load_yarnVersion() { - return _yarnVersion = __webpack_require__(65); +function _load_errors() { + return _errors = __webpack_require__(3); +} + +var _child; + +function _load_child() { + return _child = _interopRequireWildcard(__webpack_require__(48)); +} + +var _executeLifecycleScript; + +function _load_executeLifecycleScript() { + return _executeLifecycleScript = __webpack_require__(97); } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function setFlags(commander) {} @@ -77119,7 +80980,7 @@ function hasWrapper(commander, args) { } /***/ }), -/* 353 */ +/* 393 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -77128,247 +80989,195 @@ function hasWrapper(commander, args) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.run = exports.requireLockfile = undefined; - -var _slicedToArray2; - -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} +exports.examples = exports.run = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -let cleanQuery = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, query) { - // if a location was passed then turn it into a hash query - if (path.isAbsolute(query) && (yield (_fs || _load_fs()).exists(query))) { - // absolute path - query = path.relative(config.cwd, query); +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + let manifest; + if (flags.useManifest) { + manifest = yield config.readJson(flags.useManifest); + } else { + manifest = yield config.readRootManifest(); + } + if (!manifest.name) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('noName')); + } + if (!manifest.version) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('noVersion')); } - // remove references to node_modules with hashes - query = query.replace(/([\\/]|^)node_modules[\\/]/g, '#'); - - // remove trailing hashes - query = query.replace(/^#+/g, ''); - - // remove trailing paths from each part of the query, skip second part of path for scoped packages - let queryParts = query.split('#'); - queryParts = queryParts.map(function (part) { - let parts = part.split(/[\\/]/g); - - if (part[0] === '@') { - parts = parts.slice(0, 2); - } else { - parts = parts.slice(0, 1); - } - - return parts.join('/'); - }); - query = queryParts.join('#'); - - return query; + const entry = { + name: manifest.name, + version: manifest.version, + resolved: flags.resolved, + registry: flags.registry || manifest._registry, + optionalDependencies: manifest.optionalDependencies, + dependencies: manifest.dependencies + }; + const pattern = flags.pattern || `${entry.name}@${entry.version}`; + reporter.log((0, (_lockfile || _load_lockfile()).stringify)({ + [pattern]: (0, (_lockfile || _load_lockfile()).implodeEntry)(pattern, entry) + })); }); - return function cleanQuery(_x, _x2) { + return function run(_x, _x2, _x3, _x4) { return _ref.apply(this, arguments); }; })(); -let getPackageSize = (() => { - var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (tuple) { - var _tuple = (0, (_slicedToArray2 || _load_slicedToArray()).default)(tuple, 1); - - const loc = _tuple[0]; - +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; - const files = yield (_fs || _load_fs()).walk(loc, null, new Set([(_constants || _load_constants()).METADATA_FILENAME, (_constants || _load_constants()).TARBALL_FILENAME])); +var _errors; - const sizes = yield Promise.all(files.map(function (walkFile) { - return (_fs || _load_fs()).getFileSizeOnDisk(walkFile.absolute); - })); +function _load_errors() { + return _errors = __webpack_require__(3); +} - return sum(sizes); - }); +var _lockfile; - return function getPackageSize(_x3) { - return _ref2.apply(this, arguments); - }; -})(); +function _load_lockfile() { + return _lockfile = __webpack_require__(12); +} -let run = exports.run = (() => { - var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - if (!args.length) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('missingWhyDependency')); - } - if (args.length > 1) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('tooManyArguments', 1)); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - const query = yield cleanQuery(config, args[0]); +function hasWrapper(commander, args) { + return false; +} - reporter.step(1, 4, reporter.lang('whyStart', args[0]), emoji.get('thinking_face')); +function setFlags(commander) { + commander.option('--use-manifest <location>', 'description'); + commander.option('--resolved <resolved>', 'description'); + commander.option('--registry <registry>', 'description'); +} - // init - reporter.step(2, 4, reporter.lang('whyInitGraph'), emoji.get('truck')); - const lockfile = yield (_wrapper || _load_wrapper()).default.fromDirectory(config.lockfileFolder, reporter); - const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); +const examples = exports.examples = ['generate-lock-entry', 'generate-lock-entry --use-manifest ./package.json', 'generate-lock-entry --resolved local-file.tgz#hash']; - var _ref7 = yield install.fetchRequestFromCwd(); +/***/ }), +/* 394 */ +/***/ (function(module, exports, __webpack_require__) { - const depRequests = _ref7.requests, - patterns = _ref7.patterns; +"use strict"; - yield install.resolver.init(depRequests, { isFlat: install.flags.flat, isFrozen: install.flags.frozenLockfile }); - const hoisted = yield install.linker.getFlatHoistedTree(patterns); - // finding - reporter.step(3, 4, reporter.lang('whyFinding'), emoji.get('mag')); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.hasWrapper = hasWrapper; +exports.setFlags = setFlags; +exports.run = run; - let match; - for (const _ref8 of hoisted) { - var _ref9 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref8, 2); +var _index; - const loc = _ref9[0]; - const info = _ref9[1]; +function _load_index() { + return _index = _interopRequireDefault(__webpack_require__(231)); +} - if (info.key === query || info.previousKeys.indexOf(query) >= 0) { - match = [loc, info]; - break; - } - } +var _constants; - if (!match) { - reporter.error(reporter.lang('whyUnknownMatch')); - return; - } +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} - var _match = match, - _match2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_match, 2); +var _misc; - const matchInfo = _match2[1]; +function _load_misc() { + return _misc = __webpack_require__(10); +} - const matchRef = matchInfo.pkg._reference; - invariant(matchRef, 'expected reference'); +var _aliases; - const matchPatterns = matchRef.patterns; - const matchRequests = matchRef.requests; +function _load_aliases() { + return _aliases = _interopRequireDefault(__webpack_require__(252)); +} - const reasons = []; - // reason: dependency of these modules - for (const request of matchRequests) { - const parentRequest = request.parentRequest; - if (!parentRequest) { - continue; - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - const dependent = install.resolver.getResolvedPattern(parentRequest.pattern); - if (!dependent) { - continue; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - const chain = []; +const chalk = __webpack_require__(20); - let delegator = parentRequest; - do { - chain.push(install.resolver.getStrictResolvedPattern(delegator.pattern).name); - } while (delegator = delegator.parentRequest); +function hasWrapper(flags, args) { + return false; +} - reasons.push({ - type: 'whyDependedOn', - typeSimple: 'whyDependedOnSimple', - value: chain.reverse().join('#') - }); - } +function setFlags(commander) {} - // reason: exists in manifest - let rootType; - for (const pattern of matchPatterns) { - rootType = install.rootPatternsToOrigin[pattern]; - if (rootType) { - reasons.push({ - type: 'whySpecified', - typeSimple: 'whySpecifiedSimple', - value: rootType - }); +function run(config, reporter, commander, args) { + if (args.length) { + const commandName = args.shift(); + if (Object.prototype.hasOwnProperty.call((_index || _load_index()).default, commandName)) { + const command = (_index || _load_index()).default[commandName]; + if (command) { + command.setFlags(commander); + const examples = (command && command.examples || []).map(example => ` $ yarn ${example}`); + if (examples.length) { + commander.on('--help', () => { + reporter.log(reporter.lang('helpExamples', reporter.rawText(examples.join('\n')))); + }); + } + // eslint-disable-next-line yarn-internal/warn-language + commander.on('--help', () => reporter.log(' ' + command.getDocsInfo + '\n')); + commander.help(); + return Promise.resolve(); } } + } - // reason: this is hoisted from these modules - for (const pattern of matchInfo.previousKeys) { - if (pattern !== matchInfo.key) { - reasons.push({ - type: 'whyHoistedFrom', - typeSimple: 'whyHoistedFromSimple', - value: pattern - }); + commander.on('--help', () => { + const commandsText = []; + for (const name of Object.keys((_index || _load_index()).default).sort((_misc || _load_misc()).sortAlpha)) { + if ((_index || _load_index()).default[name].useless || Object.keys((_aliases || _load_aliases()).default).map(key => (_aliases || _load_aliases()).default[key]).indexOf(name) > -1) { + continue; + } + if ((_aliases || _load_aliases()).default[name]) { + commandsText.push(` - ${(0, (_misc || _load_misc()).hyphenate)(name)} / ${(_aliases || _load_aliases()).default[name]}`); + } else { + commandsText.push(` - ${(0, (_misc || _load_misc()).hyphenate)(name)}`); } } + reporter.log(reporter.lang('helpCommands', reporter.rawText(commandsText.join('\n')))); + reporter.log(reporter.lang('helpCommandsMore', reporter.rawText(chalk.bold('yarn help COMMAND')))); + reporter.log(reporter.lang('helpLearnMore', reporter.rawText(chalk.bold((_constants || _load_constants()).YARN_DOCS)))); + }); - // package sizes - reporter.step(4, 4, reporter.lang('whyCalculating'), emoji.get('aerial_tramway')); - - let packageSize = 0; - let directSizes = []; - let transitiveSizes = []; - try { - packageSize = yield getPackageSize(match); - } catch (e) {} - - const dependencies = Array.from(collect(hoisted, new Set(), match)); - const transitiveDependencies = Array.from(collect(hoisted, new Set(), match, { recursive: true })); - - try { - directSizes = yield Promise.all(dependencies.map(getPackageSize)); - transitiveSizes = yield Promise.all(transitiveDependencies.map(getPackageSize)); - } catch (e) {} - - const transitiveKeys = new Set(transitiveDependencies.map(function (_ref10) { - var _ref11 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref10, 2); + commander.help(); + return Promise.resolve(); +} - let info = _ref11[1]; - return info.key; - })); - const sharedDependencies = getSharedDependencies(hoisted, transitiveKeys); +/***/ }), +/* 395 */ +/***/ (function(module, exports, __webpack_require__) { - // - // reason: hoisted - if (query === matchInfo.originalKey) { - reporter.info(reporter.lang('whyHoistedTo', matchInfo.key)); - } +"use strict"; - if (reasons.length === 1) { - reporter.info(reporter.lang(reasons[0].typeSimple, reasons[0].value)); - } else if (reasons.length > 1) { - reporter.info(reporter.lang('whyReasons')); - reporter.list('reasons', reasons.map(function (reason) { - return reporter.lang(reason.type, reason.value); - })); - } else { - reporter.error(reporter.lang('whyWhoKnows')); - } - if (packageSize) { - // stats: file size of this dependency without any dependencies - reporter.info(reporter.lang('whyDiskSizeWithout', bytes(packageSize))); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.Import = exports.noArguments = undefined; - // stats: file size of this dependency including dependencies that aren't shared - reporter.info(reporter.lang('whyDiskSizeUnique', bytes(packageSize + sum(directSizes)))); +var _asyncToGenerator2; - // stats: file size of this dependency including dependencies - reporter.info(reporter.lang('whyDiskSizeTransitive', bytes(packageSize + sum(transitiveSizes)))); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - // stats: shared transitive dependencies - reporter.info(reporter.lang('whySharedDependencies', sharedDependencies.size)); - } +let run = exports.run = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const imp = new Import(flags, config, reporter, new (_lockfile || _load_lockfile()).default({ cache: {} })); + yield imp.init(); }); - return function run(_x5, _x6, _x7, _x8) { - return _ref6.apply(this, arguments); + return function run(_x2, _x3, _x4, _x5) { + return _ref3.apply(this, arguments); }; })(); @@ -77378,307 +81187,455 @@ exports.hasWrapper = hasWrapper; var _install; function _load_install() { - return _install = __webpack_require__(23); + return _install = __webpack_require__(31); } -var _constants; +var _check; -function _load_constants() { - return _constants = __webpack_require__(8); +function _load_check() { + return _check = __webpack_require__(254); } -var _fs; +var _errors; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); +function _load_errors() { + return _errors = __webpack_require__(3); } -var _wrapper; +var _index; -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); +function _load_index() { + return _index = __webpack_require__(35); } -var _errors; +var _baseResolver; -function _load_errors() { - return _errors = __webpack_require__(3); +function _load_baseResolver() { + return _baseResolver = _interopRequireDefault(__webpack_require__(95)); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _hostedGitResolver; -const requireLockfile = exports.requireLockfile = true; +function _load_hostedGitResolver() { + return _hostedGitResolver = _interopRequireDefault(__webpack_require__(78)); +} -const invariant = __webpack_require__(5); -const bytes = __webpack_require__(404); -const emoji = __webpack_require__(246); -const path = __webpack_require__(1); +var _hostedGitResolver2; -function sum(array) { - return array.length ? array.reduce((a, b) => a + b, 0) : 0; +function _load_hostedGitResolver2() { + return _hostedGitResolver2 = __webpack_require__(78); } -function collect(hoistManifests, allDependencies, dependency) { - var _ref3 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { recursive: false }; +var _gistResolver; - let recursive = _ref3.recursive; +function _load_gistResolver() { + return _gistResolver = _interopRequireDefault(__webpack_require__(163)); +} - var _dependency = (0, (_slicedToArray2 || _load_slicedToArray()).default)(dependency, 2); +var _gistResolver2; - const depInfo = _dependency[1]; +function _load_gistResolver2() { + return _gistResolver2 = __webpack_require__(163); +} - const deps = depInfo.pkg.dependencies; +var _gitResolver; - if (!deps) { - return allDependencies; - } +function _load_gitResolver() { + return _gitResolver = _interopRequireDefault(__webpack_require__(96)); +} - const dependencyKeys = new Set(Object.keys(deps)); - const directDependencies = []; +var _fileResolver; - for (const dep of hoistManifests) { - var _dep = (0, (_slicedToArray2 || _load_slicedToArray()).default)(dep, 2); +function _load_fileResolver() { + return _fileResolver = _interopRequireDefault(__webpack_require__(162)); +} - const info = _dep[1]; +var _packageResolver; +function _load_packageResolver() { + return _packageResolver = _interopRequireDefault(__webpack_require__(264)); +} - if (!allDependencies.has(dep) && dependencyKeys.has(info.key)) { - allDependencies.add(dep); - directDependencies.push(dep); - } - } +var _packageRequest; - if (recursive) { - directDependencies.forEach(dependency => collect(hoistManifests, allDependencies, dependency, { recursive: true })); - } +function _load_packageRequest() { + return _packageRequest = _interopRequireDefault(__webpack_require__(94)); +} - return allDependencies; +var _packageFetcher; + +function _load_packageFetcher() { + return _packageFetcher = _interopRequireWildcard(__webpack_require__(263)); } -function getSharedDependencies(hoistManifests, transitiveKeys) { - const sharedDependencies = new Set(); - for (const _ref4 of hoistManifests) { - var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2); +var _packageLinker; - const info = _ref5[1]; +function _load_packageLinker() { + return _packageLinker = _interopRequireDefault(__webpack_require__(159)); +} - if (!transitiveKeys.has(info.key) && info.pkg.dependencies) { - Object.keys(info.pkg.dependencies).forEach(dependency => { - if (transitiveKeys.has(dependency) && !sharedDependencies.has(dependency)) { - sharedDependencies.add(dependency); - } - }); - } - } - return sharedDependencies; +var _packageCompatibility; + +function _load_packageCompatibility() { + return _packageCompatibility = _interopRequireWildcard(__webpack_require__(262)); } -function setFlags(commander) {} +var _lockfile; -function hasWrapper(commander, args) { - return true; +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); } -/***/ }), -/* 354 */ -/***/ (function(module, exports, __webpack_require__) { +var _normalizePattern6; -"use strict"; +function _load_normalizePattern() { + return _normalizePattern6 = __webpack_require__(30); +} +var _fs; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.run = undefined; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} -var _toArray2; +var _misc; -function _load_toArray() { - return _toArray2 = _interopRequireDefault(__webpack_require__(67)); +function _load_misc() { + return _misc = _interopRequireWildcard(__webpack_require__(10)); } -var _asyncToGenerator2; +var _constants; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function _load_constants() { + return _constants = __webpack_require__(6); } -let run = exports.run = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { - const workspaceRootFolder = config.workspaceRootFolder; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (!workspaceRootFolder) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceRootNotFound', config.cwd)); - } +const NPM_REGISTRY = /http[s]:\/\/registry.npmjs.org/g; - if (args.length < 1) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceMissingWorkspace')); - } +const invariant = __webpack_require__(7); +const path = __webpack_require__(0); +const uuid = __webpack_require__(88); - if (args.length < 2) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceMissingCommand')); +const noArguments = exports.noArguments = true; + +class ImportResolver extends (_baseResolver || _load_baseResolver()).default { + getCwd() { + if (this.request.parentRequest) { + const parent = this.resolver.getStrictResolvedPattern(this.request.parentRequest.pattern); + invariant(parent._loc, 'expected package location'); + return path.dirname(parent._loc); } + return this.config.cwd; + } - const manifest = yield config.findManifest(workspaceRootFolder, false); - invariant(manifest && manifest.workspaces, 'We must find a manifest with a "workspaces" property'); + resolveHostedGit(info, Resolver) { + var _normalizePattern = (0, (_normalizePattern6 || _load_normalizePattern()).normalizePattern)(this.pattern); - const workspaces = yield config.resolveWorkspaces(workspaceRootFolder, manifest); + const range = _normalizePattern.range; - var _args = (0, (_toArray2 || _load_toArray()).default)(args); + const exploded = (0, (_hostedGitResolver2 || _load_hostedGitResolver2()).explodeHostedGitFragment)(range, this.reporter); + const hash = info.gitHead; + invariant(hash, 'expected package gitHead'); + const url = Resolver.getTarballUrl(exploded, hash); + info._uid = hash; + info._remote = { + resolved: url, + type: 'tarball', + registry: this.registry, + reference: url, + hash: null + }; + return info; + } - const workspaceName = _args[0], - rest = _args.slice(1); + resolveGist(info, Resolver) { + var _normalizePattern2 = (0, (_normalizePattern6 || _load_normalizePattern()).normalizePattern)(this.pattern); - if (!Object.prototype.hasOwnProperty.call(workspaces, workspaceName)) { - throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceUnknownWorkspace', workspaceName)); - } + const range = _normalizePattern2.range; - try { - yield (_child || _load_child()).spawn(process.argv[0], [process.argv[1], ...rest], { stdio: 'inherit' }); - } catch (err) { - throw err; - } - }); + var _explodeGistFragment = (0, (_gistResolver2 || _load_gistResolver2()).explodeGistFragment)(range, this.reporter); - return function run(_x, _x2, _x3, _x4) { - return _ref.apply(this, arguments); - }; -})(); + const id = _explodeGistFragment.id; -exports.setFlags = setFlags; -exports.hasWrapper = hasWrapper; + const hash = info.gitHead; + invariant(hash, 'expected package gitHead'); + const url = `https://gist.github.com/${id}.git`; + info._uid = hash; + info._remote = { + resolved: `${url}#${hash}`, + type: 'git', + registry: this.registry, + reference: url, + hash + }; + return info; + } -var _errors; + resolveGit(info, Resolver) { + const url = info._resolved; + const hash = info.gitHead; + invariant(url, 'expected package _resolved'); + invariant(hash, 'expected package gitHead'); + info._uid = hash; + info._remote = { + resolved: `${url}#${hash}`, + type: 'git', + registry: this.registry, + reference: url, + hash + }; + return info; + } -function _load_errors() { - return _errors = __webpack_require__(3); -} + resolveFile(info, Resolver) { + var _normalizePattern3 = (0, (_normalizePattern6 || _load_normalizePattern()).normalizePattern)(this.pattern); -var _child; + const range = _normalizePattern3.range; -function _load_child() { - return _child = _interopRequireWildcard(__webpack_require__(45)); -} + let loc = (_misc || _load_misc()).removePrefix(range, 'file:'); + if (!path.isAbsolute(loc)) { + loc = path.join(this.config.cwd, loc); + } + info._uid = info.version; + info._remote = { + type: 'copy', + registry: this.registry, + hash: `${uuid.v4()}-${new Date().getTime()}`, + reference: loc + }; + return info; + } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + resolveRegistry(info) { + let url = info._resolved; + const hash = info._shasum; + invariant(url, 'expected package _resolved'); + invariant(hash, 'expected package _shasum'); + if (this.config.getOption('registry') === (_constants || _load_constants()).YARN_REGISTRY) { + url = url.replace(NPM_REGISTRY, (_constants || _load_constants()).YARN_REGISTRY); + } + info._uid = info.version; + info._remote = { + resolved: `${url}#${hash}`, + type: 'tarball', + registry: this.registry, + reference: url, + hash + }; + return info; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + resolveImport(info) { + var _normalizePattern4 = (0, (_normalizePattern6 || _load_normalizePattern()).normalizePattern)(this.pattern); -const invariant = __webpack_require__(5); + const range = _normalizePattern4.range; -function setFlags(commander) {} + const Resolver = (0, (_index || _load_index()).getExoticResolver)(range); + if (Resolver && Resolver.prototype instanceof (_hostedGitResolver || _load_hostedGitResolver()).default) { + return this.resolveHostedGit(info, Resolver); + } else if (Resolver && Resolver === (_gistResolver || _load_gistResolver()).default) { + return this.resolveGist(info, Resolver); + } else if (Resolver && Resolver === (_gitResolver || _load_gitResolver()).default) { + return this.resolveGit(info, Resolver); + } else if (Resolver && Resolver === (_fileResolver || _load_fileResolver()).default) { + return this.resolveFile(info, Resolver); + } + return this.resolveRegistry(info); + } -function hasWrapper(commander, args) { - return true; -} + resolveLocation(loc) { + var _this = this; -/***/ }), -/* 355 */ -/***/ (function(module, exports, __webpack_require__) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const info = yield _this.config.tryManifest(loc, 'npm', false); + if (!info) { + return null; + } + return _this.resolveImport(info); + })(); + } -"use strict"; + resolve() { + var _this2 = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _normalizePattern5 = (0, (_normalizePattern6 || _load_normalizePattern()).normalizePattern)(_this2.pattern); -Object.defineProperty(exports, "__esModule", { - value: true -}); + const name = _normalizePattern5.name; -var _extends2; + let cwd = _this2.getCwd(); + while (!path.relative(_this2.config.cwd, cwd).startsWith('..')) { + const loc = path.join(cwd, 'node_modules', name); + const info = yield _this2.config.getCache(`import-resolver-${loc}`, function () { + return _this2.resolveLocation(loc); + }); + if (info) { + return info; + } + cwd = path.resolve(cwd, '../..'); + } + throw new (_errors || _load_errors()).MessageError(_this2.reporter.lang('importResolveFailed', name, _this2.getCwd())); + })(); + } +} -function _load_extends() { - return _extends2 = _interopRequireDefault(__webpack_require__(36)); +class ImportPackageRequest extends (_packageRequest || _load_packageRequest()).default { + constructor(req, resolver) { + super(req, resolver); + this.import = this.parentRequest instanceof ImportPackageRequest ? this.parentRequest.import : true; + } + + getRootName() { + return this.resolver instanceof ImportPackageResolver && this.resolver.rootName || 'root'; + } + + getParentHumanName() { + return [this.getRootName()].concat(this.parentNames).join(' > '); + } + + reportResolvedRangeMatch(info, resolved) { + if (info.version === resolved.version) { + return; + } + this.reporter.warn(this.reporter.lang('importResolvedRangeMatch', resolved.version, resolved.name, info.version, this.getParentHumanName())); + } + + findVersionInfo() { + if (!this.import) { + this.reporter.verbose(this.reporter.lang('skippingImport', this.pattern, this.getParentHumanName())); + return super.findVersionInfo(); + } + const resolver = new ImportResolver(this, this.pattern); + return resolver.resolve().catch(() => { + this.import = false; + this.reporter.warn(this.reporter.lang('importFailed', this.pattern, this.getParentHumanName())); + return super.findVersionInfo(); + }); + } } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +class ImportPackageResolver extends (_packageResolver || _load_packageResolver()).default { + constructor(config, lockfile) { + super(config, lockfile); + this.next = []; + this.rootName = 'root'; + } -const shorthands = { - c: 'config', - i: 'install', - la: 'list', - ll: 'list', - ln: 'link', - ls: 'list', - r: 'remove', - rb: 'rebuild', - rm: 'remove', - t: 'test', - tst: 'test', - un: 'remove', - up: 'upgrade', - v: 'version' -}; - -const affordances = { - 'add-user': 'login', - adduser: 'login', - author: 'owner', - 'dist-tag': 'tag', - 'dist-tags': 'tag', - isntall: 'install', - 'run-script': 'run', - runScript: 'run', - show: 'info', - uninstall: 'remove', - update: 'upgrade', - verison: 'version', - view: 'info' -}; - -exports.default = (0, (_extends2 || _load_extends()).default)({}, shorthands, affordances); + find(req) { + this.next.push(req); + return Promise.resolve(); + } -/***/ }), -/* 356 */ -/***/ (function(module, exports, __webpack_require__) { + findOne(req) { + var _this3 = this; -"use strict"; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (_this3.activity) { + _this3.activity.tick(req.pattern); + } + const request = new ImportPackageRequest(req, _this3); + yield request.find({ fresh: false }); + })(); + } + findAll(deps) { + var _this4 = this; -Object.defineProperty(exports, "__esModule", { - value: true -}); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield Promise.all(deps.map(function (dep) { + return _this4.findOne(dep); + })); + deps = _this4.next; + _this4.next = []; + if (!deps.length) { + // all required package versions have been discovered, so now packages that + // resolved to existing versions can be resolved to their best available version + _this4.resolvePackagesWithExistingVersions(); + return; + } + yield _this4.findAll(deps); + })(); + } -var _asyncToGenerator2; + resetOptional() { + for (const pattern in this.patterns) { + const ref = this.patterns[pattern]._reference; + invariant(ref, 'expected reference'); + ref.optional = null; + for (const req of ref.requests) { + ref.addOptional(req.optional); + } + } + } -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + init(deps) { + var _this5 = this; -var _baseFetcher; + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { isFlat: false, isFrozen: false, workspaceLayout: undefined }; -function _load_baseFetcher() { - return _baseFetcher = _interopRequireDefault(__webpack_require__(79)); + let isFlat = _ref.isFlat, + isFrozen = _ref.isFrozen, + workspaceLayout = _ref.workspaceLayout; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this5.flat = Boolean(isFlat); + const activity = _this5.activity = _this5.reporter.activity(); + yield _this5.findAll(deps); + _this5.resetOptional(); + activity.end(); + _this5.activity = null; + })(); + } } -var _fs; +class Import extends (_install || _load_install()).Install { + constructor(flags, config, reporter, lockfile) { + super(flags, config, reporter, lockfile); + this.resolver = new ImportPackageResolver(this.config, this.lockfile); + this.linker = new (_packageLinker || _load_packageLinker()).default(config, this.resolver); + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + init() { + var _this6 = this; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (yield (_fs || _load_fs()).exists(path.join(_this6.config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME))) { + throw new (_errors || _load_errors()).MessageError(_this6.reporter.lang('lockfileExists')); + } + yield (0, (_check || _load_check()).verifyTreeCheck)(_this6.config, _this6.reporter, {}, []); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + var _ref2 = yield _this6.fetchRequestFromCwd(); -class CopyFetcher extends (_baseFetcher || _load_baseFetcher()).default { - _fetch() { - var _this = this; + const requests = _ref2.requests, + patterns = _ref2.patterns, + manifest = _ref2.manifest; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield (_fs || _load_fs()).copy(_this.reference, _this.dest, _this.reporter); - return { - hash: _this.hash || '', - resolved: null - }; + if (manifest.name && _this6.resolver instanceof ImportPackageResolver) { + _this6.resolver.rootName = manifest.name; + } + yield _this6.resolver.init(requests, { isFlat: _this6.flags.flat, isFrozen: _this6.flags.frozenLockfile }); + const manifests = yield (_packageFetcher || _load_packageFetcher()).fetch(_this6.resolver.getManifests(), _this6.config); + _this6.resolver.updateManifests(manifests); + yield (_packageCompatibility || _load_packageCompatibility()).check(_this6.resolver.getManifests(), _this6.config, _this6.flags.ignoreEngines); + yield _this6.linker.resolvePeerModules(); + yield _this6.saveLockfileAndIntegrity(patterns); + return patterns; })(); } } -exports.default = CopyFetcher; + +exports.Import = Import; +function setFlags(commander) {} + +function hasWrapper(commander, args) { + return true; +} /***/ }), -/* 357 */ +/* 396 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -77687,455 +81644,382 @@ exports.default = CopyFetcher; Object.defineProperty(exports, "__esModule", { value: true }); - -var _slicedToArray2; - -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} +exports.run = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _errors; - -function _load_errors() { - return _errors = __webpack_require__(3); -} +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (args.length > 2) { + reporter.error(reporter.lang('tooManyArguments', 2)); + return; + } -var _baseFetcher; + let packageName = args.shift() || '.'; -function _load_baseFetcher() { - return _baseFetcher = _interopRequireDefault(__webpack_require__(79)); -} + // Handle the case when we are referencing a local package. + if (packageName === '.') { + packageName = (yield config.readRootManifest()).name; + } -var _git; + const packageInput = (_npmRegistry || _load_npmRegistry()).default.escapeName(packageName); -function _load_git() { - return _git = _interopRequireDefault(__webpack_require__(127)); -} + var _parsePackageName = (0, (_parsePackageName2 || _load_parsePackageName()).default)(packageInput); -var _fs; + const name = _parsePackageName.name, + version = _parsePackageName.version; -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + // pass application/json Accept to get full metadata for info command -var _constants; + let result = yield config.registries.npm.request(name, { + headers: { Accept: 'application/json' } + }); + if (!result) { + reporter.error(reporter.lang('infoFail')); + return; + } -function _load_constants() { - return _constants = _interopRequireWildcard(__webpack_require__(8)); -} + result = clean(result); -var _crypto; + const versions = result.versions; + // $FlowFixMe + result.versions = Object.keys(versions).sort(semver.compareLoose); + result.version = version || result.versions[result.versions.length - 1]; + result = Object.assign(result, versions[result.version]); -function _load_crypto() { - return _crypto = _interopRequireWildcard(__webpack_require__(85)); -} + const fieldPath = args.shift(); + const fields = fieldPath ? fieldPath.split('.') : []; -var _install; + // Readmes can be long so exclude them unless explicitly asked for. + if (fields[0] !== 'readme') { + delete result.readme; + } -function _load_install() { - return _install = __webpack_require__(23); -} + result = fields.reduce(function (prev, cur) { + return prev && prev[cur]; + }, result); + reporter.inspect(result); + }); -var _wrapper; + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); -function _load_wrapper() { - return _wrapper = _interopRequireDefault(__webpack_require__(14)); -} +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; -var _config; +var _npmRegistry; -function _load_config() { - return _config = _interopRequireDefault(__webpack_require__(120)); +function _load_npmRegistry() { + return _npmRegistry = _interopRequireDefault(__webpack_require__(52)); } -var _pack; +var _parsePackageName2; -function _load_pack() { - return _pack = __webpack_require__(119); +function _load_parsePackageName() { + return _parsePackageName2 = _interopRequireDefault(__webpack_require__(443)); } -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const tarFs = __webpack_require__(109); -const url = __webpack_require__(11); -const path = __webpack_require__(1); -const fs = __webpack_require__(6); - -const invariant = __webpack_require__(5); - -const PACKED_FLAG = '1'; - -class GitFetcher extends (_baseFetcher || _load_baseFetcher()).default { - setupMirrorFromCache() { - var _this = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const tarballMirrorPath = _this.getTarballMirrorPath(); - const tarballCachePath = _this.getTarballCachePath(); - - if (tarballMirrorPath == null) { - return; - } - - if (!(yield (_fs || _load_fs()).exists(tarballMirrorPath)) && (yield (_fs || _load_fs()).exists(tarballCachePath))) { - // The tarball doesn't exists in the offline cache but does in the cache; we import it to the mirror - yield (_fs || _load_fs()).mkdirp(path.dirname(tarballMirrorPath)); - yield (_fs || _load_fs()).copy(tarballCachePath, tarballMirrorPath, _this.reporter); - } - })(); - } - - getLocalAvailabilityStatus() { - var _this2 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - // Some mirrors might still have files named "./reponame" instead of "./reponame-commit" - const tarballLegacyMirrorPath = _this2.getTarballMirrorPath({ - withCommit: false - }); - const tarballModernMirrorPath = _this2.getTarballMirrorPath(); - const tarballCachePath = _this2.getTarballCachePath(); +const semver = __webpack_require__(22); - if (tarballLegacyMirrorPath != null && (yield (_fs || _load_fs()).exists(tarballLegacyMirrorPath))) { - return true; +function clean(object) { + if (Array.isArray(object)) { + const result = []; + object.forEach(item => { + item = clean(item); + if (item) { + result.push(item); } - - if (tarballModernMirrorPath != null && (yield (_fs || _load_fs()).exists(tarballModernMirrorPath))) { - return true; + }); + return result; + } else if (typeof object === 'object') { + const result = {}; + for (const key in object) { + if (key.startsWith('_')) { + continue; } - if (yield (_fs || _load_fs()).exists(tarballCachePath)) { - return true; + const item = clean(object[key]); + if (item) { + result[key] = item; } - - return false; - })(); + } + return result; + } else if (object) { + return object; + } else { + return null; } +} - getTarballMirrorPath() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref$withCommit = _ref.withCommit; - - let withCommit = _ref$withCommit === undefined ? true : _ref$withCommit; - - var _url$parse = url.parse(this.reference); - - const pathname = _url$parse.pathname; +function setFlags(commander) {} +function hasWrapper(commander, args) { + return true; +} - if (pathname == null) { - return null; - } +/***/ }), +/* 397 */ +/***/ (function(module, exports, __webpack_require__) { - const hash = this.hash; +"use strict"; - const packageFilename = withCommit && hash ? `${path.basename(pathname)}-${hash}` : `${path.basename(pathname)}`; - return this.config.getOfflineMirrorPath(packageFilename); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.getGitConfigInfo = exports.run = undefined; - getTarballCachePath() { - return path.join(this.dest, (_constants || _load_constants()).TARBALL_FILENAME); - } +var _asyncToGenerator2; - fetchFromLocal(override) { - var _this3 = this; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const tarballLegacyMirrorPath = _this3.getTarballMirrorPath({ - withCommit: false - }); - const tarballModernMirrorPath = _this3.getTarballMirrorPath(); - const tarballCachePath = _this3.getTarballCachePath(); +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const manifests = yield config.getRootManifests(); - const tarballMirrorPath = tarballModernMirrorPath && (yield (_fs || _load_fs()).exists(tarballModernMirrorPath)) ? tarballModernMirrorPath : tarballLegacyMirrorPath && (yield (_fs || _load_fs()).exists(tarballLegacyMirrorPath)) ? tarballLegacyMirrorPath : null; + let repository = {}; + const author = { + name: config.getOption('init-author-name'), + email: config.getOption('init-author-email'), + url: config.getOption('init-author-url') + }; + if (yield (_fs || _load_fs()).exists(path.join(config.cwd, '.git'))) { + // get git origin of the cwd + try { + repository = { + type: 'git', + url: yield (_child || _load_child()).spawn('git', ['config', 'remote.origin.url'], { + cwd: config.cwd + }) + }; + } catch (ex) { + // Ignore - Git repo may not have an origin URL yet (eg. if it only exists locally) + } - const tarballPath = override || tarballMirrorPath || tarballCachePath; + if (author.name === undefined) { + author.name = yield getGitConfigInfo('user.name'); + } - if (!tarballPath || !(yield (_fs || _load_fs()).exists(tarballPath))) { - throw new (_errors || _load_errors()).MessageError(_this3.reporter.lang('tarballNotInNetworkOrCache', _this3.reference, tarballPath)); + if (author.email === undefined) { + author.email = yield getGitConfigInfo('user.email'); } + } - return new Promise(function (resolve, reject) { - const untarStream = _this3._createUntarStream(_this3.dest); + const keys = [{ + key: 'name', + question: 'name', + default: path.basename(config.cwd), + validation: (_validate || _load_validate()).isValidPackageName, + validationError: 'invalidPackageName' + }, { + key: 'version', + question: 'version', + default: String(config.getOption('init-version')) + }, { + key: 'description', + question: 'description', + default: '' + }, { + key: 'main', + question: 'entry point', + default: 'index.js' + }, { + key: 'repository', + question: 'repository url', + default: (0, (_util || _load_util()).extractRepositoryUrl)(repository) + }, { + key: 'author', + question: 'author', + default: (0, (_util || _load_util()).stringifyPerson)(author) + }, { + key: 'license', + question: 'license', + default: String(config.getOption('init-license')) + }, { + key: 'private', + question: 'private', + default: '', + inputFormatter: yn + }]; - const hashStream = new (_crypto || _load_crypto()).HashStream(); + // get answers + const pkg = {}; + for (const entry of keys) { + const yes = flags.yes, + privateFlag = flags.private; + const manifestKey = entry.key; + let question = entry.question, + def = entry.default; - const cachedStream = fs.createReadStream(tarballPath); - cachedStream.pipe(hashStream).pipe(untarStream).on('finish', function () { - const expectHash = _this3.hash; - invariant(expectHash, 'Commit hash required'); - const actualHash = hashStream.getHash(); + for (const registryName of (_index || _load_index()).registryNames) { + const object = manifests[registryName].object; - // This condition is disabled because "expectHash" actually is the commit hash - // This is a design issue that we'll need to fix (https://github.com/yarnpkg/yarn/pull/3449) - if (true) { - resolve({ - hash: expectHash - }); - } else { - reject(new (_errors || _load_errors()).SecurityError(_this3.reporter.lang('fetchBadHash', expectHash, actualHash))); + let val = objectPath.get(object, manifestKey); + if (!val) { + break; + } + if (typeof val === 'object') { + if (manifestKey === 'author') { + val = (0, (_util || _load_util()).stringifyPerson)(val); + } else if (manifestKey === 'repository') { + val = (0, (_util || _load_util()).extractRepositoryUrl)(val); } - }).on('error', function (err) { - reject(new (_errors || _load_errors()).MessageError(this.reporter.lang('fetchErrorCorrupt', err.message, tarballPath))); - }); - }); - })(); - } - - fetchFromExternal() { - var _this4 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const hash = _this4.hash; - invariant(hash, 'Commit hash required'); - - const gitUrl = (_git || _load_git()).default.npmUrlToGitUrl(_this4.reference); - const git = new (_git || _load_git()).default(_this4.config, gitUrl, hash); - yield git.init(); - - const manifestFile = yield git.getFile('package.json'); - if (!manifestFile) { - throw new (_errors || _load_errors()).MessageError(_this4.reporter.lang('couldntFindPackagejson', gitUrl)); + } + def = val; } - const scripts = JSON.parse(manifestFile).scripts; - const hasPrepareScript = Boolean(scripts && scripts.prepare); - if (hasPrepareScript) { - yield _this4.fetchFromInstallAndPack(git); - } else { - yield _this4.fetchFromGitArchive(git); + if (manifestKey === 'private' && privateFlag) { + def = true; } - return { - hash - }; - })(); - } - - fetchFromInstallAndPack(git) { - var _this5 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const prepareDirectory = _this5.config.getTemp(`${(_crypto || _load_crypto()).hash(git.gitUrl.repository)}.${git.hash}.prepare`); - yield (_fs || _load_fs()).unlink(prepareDirectory); - - yield git.clone(prepareDirectory); - - var _ref2 = yield Promise.all([(_config || _load_config()).default.create({ - cwd: prepareDirectory, - disablePrepublish: true - }, _this5.reporter), (_wrapper || _load_wrapper()).default.fromDirectory(prepareDirectory, _this5.reporter)]), - _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2); - - const prepareConfig = _ref3[0], - prepareLockFile = _ref3[1]; - - yield (0, (_install || _load_install()).install)(prepareConfig, _this5.reporter, {}, prepareLockFile); - - const tarballMirrorPath = _this5.getTarballMirrorPath(); - const tarballCachePath = _this5.getTarballCachePath(); - - if (tarballMirrorPath) { - yield _this5._packToTarball(prepareConfig, tarballMirrorPath); - } - if (tarballCachePath) { - yield _this5._packToTarball(prepareConfig, tarballCachePath); + if (def) { + question += ` (${def.toString()})`; } - yield _this5._packToDirectory(prepareConfig, _this5.dest); - - yield (_fs || _load_fs()).unlink(prepareDirectory); - })(); - } - - _packToTarball(config, path) { - var _this6 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const tarballStream = yield _this6._createTarballStream(config); - yield new Promise(function (resolve, reject) { - const writeStream = fs.createWriteStream(path); - tarballStream.on('error', reject); - writeStream.on('error', reject); - writeStream.on('end', resolve); - writeStream.on('open', function () { - tarballStream.pipe(writeStream); - }); - writeStream.once('finish', resolve); - }); - })(); - } - - _packToDirectory(config, dest) { - var _this7 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const tarballStream = yield _this7._createTarballStream(config); - yield new Promise(function (resolve, reject) { - const untarStream = _this7._createUntarStream(dest); - tarballStream.on('error', reject); - untarStream.on('error', reject); - untarStream.on('end', resolve); - untarStream.once('finish', resolve); - tarballStream.pipe(untarStream); - }); - })(); - } + let answer; + let validAnswer = false; - _createTarballStream(config) { - let savedPackedHeader = false; - return (0, (_pack || _load_pack()).packTarball)(config, { - mapHeader(header) { - if (!savedPackedHeader) { - savedPackedHeader = true; - header.pax = header.pax || {}; - // add a custom data on the first header - // in order to distinguish a tar from "git archive" and a tar from "pack" command - header.pax.packed = PACKED_FLAG; + if (yes) { + answer = def; + } else { + // loop until a valid answer is provided, if validation is on entry + if (entry.validation) { + while (!validAnswer) { + answer = (yield reporter.question(question)) || def; + // validate answer + if (entry.validation(String(answer))) { + validAnswer = true; + } else { + reporter.error(reporter.lang('invalidPackageName')); + } + } + } else { + answer = (yield reporter.question(question)) || def; } - return header; } - }); - } - _createUntarStream(dest) { - const PREFIX = 'package/'; - let isPackedTarball = undefined; - return tarFs.extract(dest, { - dmode: 0o555, // all dirs should be readable - fmode: 0o444, // all files should be readable - chown: false, // don't chown. just leave as it is - map: header => { - if (isPackedTarball === undefined) { - isPackedTarball = header.pax && header.pax.packed === PACKED_FLAG; - } - if (isPackedTarball) { - header.name = header.name.substr(PREFIX.length); + if (answer) { + if (entry.inputFormatter) { + answer = entry.inputFormatter(answer); } + objectPath.set(pkg, manifestKey, answer); } - }); - } - - fetchFromGitArchive(git) { - var _this8 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield git.clone(_this8.dest); - const tarballMirrorPath = _this8.getTarballMirrorPath(); - const tarballCachePath = _this8.getTarballCachePath(); + } - if (tarballMirrorPath) { - yield git.archive(tarballMirrorPath); - } + if (pkg.repository && (_githubResolver || _load_githubResolver()).default.isVersion(pkg.repository)) { + pkg.repository = `https://github.com/${pkg.repository}`; + } - if (tarballCachePath) { - yield git.archive(tarballCachePath); + // save answers + const targetManifests = []; + for (const registryName of (_index || _load_index()).registryNames) { + const info = manifests[registryName]; + if (info.exists) { + targetManifests.push(info); } - })(); - } + } + if (!targetManifests.length) { + targetManifests.push(manifests.npm); + } + for (const targetManifest of targetManifests) { + Object.assign(targetManifest.object, pkg); + reporter.success(`Saved ${path.basename(targetManifest.loc)}`); + } - _fetch() { - var _this9 = this; + yield config.saveRootManifests(manifests); + }); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (yield _this9.getLocalAvailabilityStatus()) { - return _this9.fetchFromLocal(); - } else { - return _this9.fetchFromExternal(); - } - })(); - } -} -exports.default = GitFetcher; + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); -/***/ }), -/* 358 */ -/***/ (function(module, exports, __webpack_require__) { +let getGitConfigInfo = exports.getGitConfigInfo = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (credential) { + let spawn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : (_child || _load_child()).spawn; -"use strict"; + try { + // try to get author default based on git config + return yield spawn('git', ['config', credential]); + } catch (e) { + return ''; + } + }); + return function getGitConfigInfo(_x5) { + return _ref2.apply(this, arguments); + }; +})(); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.tarball = exports.git = exports.copy = exports.base = undefined; +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; -var _baseFetcher; +var _util; -function _load_baseFetcher() { - return _baseFetcher = _interopRequireDefault(__webpack_require__(79)); +function _load_util() { + return _util = __webpack_require__(168); } -var _copyFetcher; +var _index; -function _load_copyFetcher() { - return _copyFetcher = _interopRequireDefault(__webpack_require__(356)); +function _load_index() { + return _index = __webpack_require__(34); } -var _gitFetcher; +var _githubResolver; -function _load_gitFetcher() { - return _gitFetcher = _interopRequireDefault(__webpack_require__(357)); +function _load_githubResolver() { + return _githubResolver = _interopRequireDefault(__webpack_require__(268)); } -var _tarballFetcher; +var _child; -function _load_tarballFetcher() { - return _tarballFetcher = _interopRequireDefault(__webpack_require__(198)); +function _load_child() { + return _child = _interopRequireWildcard(__webpack_require__(48)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _fs; -exports.base = (_baseFetcher || _load_baseFetcher()).default; -exports.copy = (_copyFetcher || _load_copyFetcher()).default; -exports.git = (_gitFetcher || _load_gitFetcher()).default; -exports.tarball = (_tarballFetcher || _load_tarballFetcher()).default; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} -/***/ }), -/* 359 */ -/***/ (function(module, exports, __webpack_require__) { +var _validate; -"use strict"; +function _load_validate() { + return _validate = _interopRequireWildcard(__webpack_require__(98)); +} +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -Object.defineProperty(exports, "__esModule", { - value: true -}); -const semver = __webpack_require__(27); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// This isn't really a "proper" constraint resolver. We just return the highest semver -// version in the versions passed that satisfies the input range. This vastly reduces -// the complexity and is very efficient for package resolution. +const objectPath = __webpack_require__(300); +const path = __webpack_require__(0); +const yn = __webpack_require__(652); -class PackageConstraintResolver { - constructor(config, reporter) { - this.reporter = reporter; - this.config = config; - } +function setFlags(commander) { + commander.option('-y, --yes', 'use default options'); + commander.option('-p, --private', 'use default options and private true'); +} - reduce(versions, range) { - if (range === 'latest') { - // Usually versions are already ordered and the last one is the latest - return Promise.resolve(versions[versions.length - 1]); - } else { - return Promise.resolve(semver.maxSatisfying(versions, range, this.config.looseSemver)); - } - } +function hasWrapper(commander, args) { + return true; } -exports.default = PackageConstraintResolver; /***/ }), -/* 360 */ +/* 398 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78144,577 +82028,302 @@ exports.default = PackageConstraintResolver; Object.defineProperty(exports, "__esModule", { value: true }); -exports.HoistManifest = undefined; +exports.examples = exports.setFlags = exports.run = undefined; var _slicedToArray2; function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } -var _misc; +var _extends2; -function _load_misc() { - return _misc = __webpack_require__(10); +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const invariant = __webpack_require__(5); -const path = __webpack_require__(1); - -let historyCounter = 0; - -class HoistManifest { - constructor(key, parts, pkg, loc, isRequired, isIncompatible) { - this.isRequired = isRequired; - this.isIncompatible = isIncompatible; - this.loc = loc; - this.pkg = pkg; - - this.key = key; - this.parts = parts; - this.originalKey = key; - this.previousKeys = []; - - this.history = []; - this.addHistory(`Start position = ${key}`); - } +var _asyncToGenerator2; - addHistory(msg) { - this.history.push(`${++historyCounter}: ${msg}`); - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -exports.HoistManifest = HoistManifest; -class PackageHoister { - constructor(config, resolver) { - this.resolver = resolver; - this.config = config; - - this.taintedKeys = new Map(); - this.levelQueue = []; - this.tree = new Map(); - } - - /** - * Taint this key and prevent any modules from being hoisted to it. - */ - - taintKey(key, info) { - const existingTaint = this.taintedKeys.get(key); - if (existingTaint && existingTaint.loc !== info.loc) { - return false; - } else { - this.taintedKeys.set(key, info); - return true; - } - } - - /** - * Implode an array of ancestry parts into a key. - */ - - implodeKey(parts) { - return parts.join('#'); - } - - /** - * Seed the hoister with patterns taken from the included resolver. - */ - - seed(patterns) { - this.prepass(patterns); - - for (const pattern of this.resolver.dedupePatterns(patterns)) { - this._seed(pattern, { isDirectRequire: true }); - } - - while (true) { - let queue = this.levelQueue; - if (!queue.length) { - this._propagateRequired(); - return; - } - - this.levelQueue = []; - - // sort queue to get determinism between runs - queue = queue.sort((_ref, _ref2) => { - var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 1); - - let aPattern = _ref4[0]; - - var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1); - - let bPattern = _ref3[0]; - - return (0, (_misc || _load_misc()).sortAlpha)(aPattern, bPattern); - }); - - // - const infos = []; - for (const _ref5 of queue) { - var _ref6 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref5, 2); +let getManifests = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, flags) { + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.cwd); + const install = new (_install || _load_install()).Install((0, (_extends2 || _load_extends()).default)({ skipIntegrityCheck: true }, flags), config, new (_baseReporter || _load_baseReporter()).default(), lockfile); + yield install.hydrate(true); - const pattern = _ref6[0]; - const parent = _ref6[1]; + let manifests = install.resolver.getManifests(); - const info = this._seed(pattern, { isDirectRequire: false, parent }); - if (info) { - infos.push(info); - } + // sort by name + manifests = manifests.sort(function (a, b) { + if (!a.name && !b.name) { + return 0; } - // - for (const info of infos) { - this.hoist(info); + if (!a.name) { + return 1; } - } - } - - /** - * Seed the hoister with a specific pattern. - */ - - _seed(pattern, _ref7) { - let isDirectRequire = _ref7.isDirectRequire, - parent = _ref7.parent; - - // - const pkg = this.resolver.getStrictResolvedPattern(pattern); - const ref = pkg._reference; - invariant(ref, 'expected reference'); - - // - let parentParts = []; - const isIncompatible = ref.incompatible; - let isRequired = isDirectRequire && !ref.ignore && !isIncompatible; - if (parent) { - if (!this.tree.get(parent.key)) { - return null; - } - // non ignored dependencies inherit parent's ignored status - // parent may transition from ignored to non ignored when hoisted if it is used in another non ignored branch - if (!isDirectRequire && !isIncompatible && parent.isRequired) { - isRequired = true; + if (!b.name) { + return -1; } - parentParts = parent.parts; - } - - // - const loc = this.config.generateHardModulePath(ref); - const parts = parentParts.concat(pkg.name); - const key = this.implodeKey(parts); - const info = new HoistManifest(key, parts, pkg, loc, isRequired, isIncompatible); - - // - this.tree.set(key, info); - this.taintKey(key, info); - - // - for (const depPattern of ref.dependencies) { - this.levelQueue.push([depPattern, info]); - } - return info; - } - - /** - * Propagate inherited ignore statuses from non-ignored to ignored packages - */ + return a.name.localeCompare(b.name); + }); - _propagateRequired() { - // - const toVisit = []; + // filter ignored manifests + manifests = manifests.filter(function (manifest) { + const ref = manifest._reference; + return !!ref && !ref.ignore; + }); - // enumerate all non-ignored packages - for (const entry of this.tree.entries()) { - if (entry[1].isRequired) { - toVisit.push(entry[1]); - } - } + return manifests; + }); - // visit them - while (toVisit.length) { - const info = toVisit.shift(); - const ref = info.pkg._reference; - invariant(ref, 'expected reference'); + return function getManifests(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); - for (const depPattern of ref.dependencies) { - const depinfo = this._lookupDependency(info, depPattern); - if (depinfo && !depinfo.isRequired && !depinfo.isIncompatible) { - depinfo.isRequired = true; - depinfo.addHistory(`Mark as non-ignored because of usage by ${info.key}`); - toVisit.push(depinfo); - } - } - } - } +let list = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const manifests = yield getManifests(config, flags); - /** - * Looks up the package a dependency resolves to - */ + if (flags.json) { + const body = []; - _lookupDependency(info, depPattern) { - // - const pkg = this.resolver.getStrictResolvedPattern(depPattern); - const ref = pkg._reference; - invariant(ref, 'expected reference'); + for (const _ref3 of manifests) { + const name = _ref3.name, + version = _ref3.version, + license = _ref3.license, + repository = _ref3.repository, + homepage = _ref3.homepage, + author = _ref3.author; - // - for (let i = info.parts.length; i >= 0; i--) { - const checkParts = info.parts.slice(0, i).concat(pkg.name); - const checkKey = this.implodeKey(checkParts); - const existing = this.tree.get(checkKey); - if (existing) { - return existing; + const url = repository ? repository.url : homepage; + const vendorUrl = homepage || author && author.url; + const vendorName = author && author.name; + body.push([name, version, license || 'Unknown', url || 'Unknown', vendorUrl || 'Unknown', vendorName || 'Unknown']); } - } - - return null; - } - - /** - * Find the highest position we can hoist this module to. - */ - - getNewParts(key, info, parts) { - let stepUp = false; - - const fullKey = this.implodeKey(parts); - const stack = []; // stack of removed parts - const name = parts.pop(); - - // - for (let i = parts.length - 1; i >= 0; i--) { - const checkParts = parts.slice(0, i).concat(name); - const checkKey = this.implodeKey(checkParts); - info.addHistory(`Looked at ${checkKey} for a match`); - const existing = this.tree.get(checkKey); - if (existing) { - if (existing.loc === info.loc) { - // switch to non ignored if earlier deduped version was ignored (must be compatible) - if (!existing.isRequired && info.isRequired) { - existing.addHistory(`Deduped ${fullKey} to this item, marking as required`); - existing.isRequired = true; - } else { - existing.addHistory(`Deduped ${fullKey} to this item`); - } + reporter.table(['Name', 'Version', 'License', 'URL', 'VendorUrl', 'VendorName'], body); + } else { + const trees = []; + + for (const _ref4 of manifests) { + const name = _ref4.name, + version = _ref4.version, + license = _ref4.license, + repository = _ref4.repository, + homepage = _ref4.homepage; + + const children = []; + children.push({ + name: `${reporter.format.bold('License:')} ${license || reporter.format.red('UNKNOWN')}` + }); - return { parts: checkParts, duplicate: true }; - } else { - // everything above will be shadowed and this is a conflict - info.addHistory(`Found a collision at ${checkKey}`); - break; + const url = repository ? repository.url : homepage; + if (url) { + children.push({ name: `${reporter.format.bold('URL:')} ${url}` }); } - } - - const existingTaint = this.taintedKeys.get(checkKey); - if (existingTaint && existingTaint.loc !== info.loc) { - info.addHistory(`Broken by ${checkKey}`); - break; - } - } - - // remove redundant parts that wont collide - while (parts.length) { - const checkParts = parts.concat(name); - const checkKey = this.implodeKey(checkParts); - - // - const existing = this.tree.get(checkKey); - if (existing) { - stepUp = true; - break; - } - - // check if we're trying to hoist ourselves to a previously unflattened module key, - // this will result in a conflict and we'll need to move ourselves up - if (key !== checkKey && this.taintedKeys.has(checkKey)) { - stepUp = true; - break; - } - - // - stack.push(parts.pop()); - } - // - parts.push(name); - - // - const isValidPosition = parts => { - const key = this.implodeKey(parts); - const existing = this.tree.get(key); - if (existing && existing.loc === info.loc) { - return true; - } - - // ensure there's no taint or the taint is us - const existingTaint = this.taintedKeys.get(key); - if (existingTaint && existingTaint.loc !== info.loc) { - return false; + trees.push({ + name: `${name}@${version}`, + children + }); } - return true; - }; - - // we need to special case when we attempt to hoist to the top level as the `existing` logic - // wont be hit in the above `while` loop and we could conflict - if (!isValidPosition(parts)) { - stepUp = true; - } - - // sometimes we need to step up to a parent module to install ourselves - while (stepUp && stack.length) { - info.addHistory(`Stepping up from ${this.implodeKey(parts)}`); - - parts.pop(); // remove `name` - parts.push(stack.pop(), name); - - if (isValidPosition(parts)) { - info.addHistory(`Found valid position ${this.implodeKey(parts)}`); - stepUp = false; - } + reporter.tree('licenses', trees); } + }); - return { parts, duplicate: false }; - } - - /** - * Hoist all seeded patterns to their highest positions. - */ - - hoist(info) { - const key = info.key, - rawParts = info.parts; - - // remove this item from the `tree` map so we can ignore it - - this.tree.delete(key); - - var _getNewParts = this.getNewParts(key, info, rawParts.slice()); - - const parts = _getNewParts.parts, - duplicate = _getNewParts.duplicate; - - const newKey = this.implodeKey(parts); - const oldKey = key; - if (duplicate) { - info.addHistory(`Satisfied from above by ${newKey}`); - this.declareRename(info, rawParts, parts); - return; - } + return function list(_x3, _x4, _x5, _x6) { + return _ref2.apply(this, arguments); + }; +})(); - // update to the new key - if (oldKey === newKey) { - info.addHistory("Didn't hoist - conflicts above"); - this.setKey(info, oldKey, parts); - return; - } +exports.hasWrapper = hasWrapper; - // - this.declareRename(info, rawParts, parts); - this.setKey(info, newKey, parts); - } +var _baseReporter; - /** - * Declare that a module has been hoisted and update our internal references. - */ +function _load_baseReporter() { + return _baseReporter = _interopRequireDefault(__webpack_require__(77)); +} - declareRename(info, oldParts, newParts) { - // go down the tree from our new position reserving our name - this.taintParents(info, oldParts.slice(0, -1), newParts.length - 1); - } +var _install; - /** - * Crawl upwards through a list of ancestry parts and taint a package name. - */ +function _load_install() { + return _install = __webpack_require__(31); +} - taintParents(info, processParts, start) { - for (let i = start; i < processParts.length; i++) { - const parts = processParts.slice(0, i).concat(info.pkg.name); - const key = this.implodeKey(parts); +var _lockfile; - if (this.taintKey(key, info)) { - info.addHistory(`Tainted ${key} to prevent collisions`); - } - } - } +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} - /** - * Update the key of a module and update our references. - */ +var _buildSubCommands2; - setKey(info, newKey, parts) { - const oldKey = info.key; +function _load_buildSubCommands() { + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); +} - info.key = newKey; - info.parts = parts; - this.tree.set(newKey, info); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (oldKey === newKey) { - return; - } +const invariant = __webpack_require__(7); - info.previousKeys.push(newKey); - info.addHistory(`New position = ${newKey}`); - } +function hasWrapper(flags, args) { + return args[0] != 'generate-disclaimer'; +} - /** - * Perform a prepass and if there's multiple versions of the same package, hoist the one with - * the most dependents to the top. - */ +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('licenses', { + ls(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + reporter.warn(`\`yarn licenses ls\` is deprecated. Please use \`yarn licenses list\`.`); + yield list(config, reporter, flags, args); + })(); + }, - prepass(patterns) { - patterns = this.resolver.dedupePatterns(patterns).sort(); + list(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield list(config, reporter, flags, args); + })(); + }, - const occurences = {}; + generateDisclaimer(config, reporter, flags, args) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + /* eslint-disable no-console */ - // add an occuring package to the above data structure - const add = (pattern, ancestry) => { - const pkg = this.resolver.getStrictResolvedPattern(pattern); - if (ancestry.indexOf(pkg) >= 0) { - // prevent recursive dependencies - return; - } + // `reporter.log` dumps a bunch of ANSI escapes to clear the current line and + // is for abstracting the console output so it can be consumed by other tools + // (JSON output being the primary one). This command is only for text consumption + // and you should just be dumping it to a TXT file. Using a reporter here has the + // potential to mess up the output since it might print ansi escapes. + const manifests = yield getManifests(config, flags); + const manifest = yield config.readRootManifest(); - const ref = pkg._reference; - invariant(ref, 'expected reference'); + // Create a map of license text to manifest so that packages with exactly + // the same license text are grouped together. + const manifestsByLicense = new Map(); + for (const manifest of manifests) { + const licenseText = manifest.licenseText; - const versions = occurences[pkg.name] = occurences[pkg.name] || {}; - const version = versions[pkg.version] = versions[pkg.version] || { - occurences: new Set(), - pattern - }; - version.occurences.add(ancestry[ancestry.length - 1]); + if (!licenseText) { + continue; + } - for (const depPattern of ref.dependencies) { - add(depPattern, ancestry.concat(pkg)); + if (!manifestsByLicense.has(licenseText)) { + manifestsByLicense.set(licenseText, new Map()); + } + + const byLicense = manifestsByLicense.get(licenseText); + invariant(byLicense, 'expected value'); + byLicense.set(manifest.name, manifest); } - }; - // get a list of root package names since we can't hoist other dependencies to these spots! - const rootPackageNames = new Set(); - for (const pattern of patterns) { - const pkg = this.resolver.getStrictResolvedPattern(pattern); - rootPackageNames.add(pkg.name); - } + console.log('THE FOLLOWING SETS FORTH ATTRIBUTION NOTICES FOR THIRD PARTY SOFTWARE THAT MAY BE CONTAINED ' + `IN PORTIONS OF THE ${String(manifest.name).toUpperCase().replace(/-/g, ' ')} PRODUCT.`); + console.log(); - // seed occurences - for (const pattern of patterns) { - add(pattern, []); - } + for (const _ref5 of manifestsByLicense) { + var _ref6 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref5, 2); - for (const packageName of Object.keys(occurences).sort()) { - const versionOccurences = occurences[packageName]; - const versions = Object.keys(versionOccurences); + const licenseText = _ref6[0]; + const manifests = _ref6[1]; - if (versions.length === 1) { - // only one package type so we'll hoist this to the top anyway - continue; - } + console.log('-----'); + console.log(); - if (this.tree.get(packageName)) { - // a transitive dependency of a previously hoisted dependency exists - continue; - } + const names = []; + const urls = []; + for (const _ref7 of manifests) { + var _ref8 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref7, 2); - if (rootPackageNames.has(packageName)) { - // can't replace top level packages - continue; - } + const name = _ref8[0]; + const repository = _ref8[1].repository; - let mostOccurenceCount; - let mostOccurencePattern; - for (const version of Object.keys(versionOccurences).sort()) { - var _versionOccurences$ve = versionOccurences[version]; - const occurences = _versionOccurences$ve.occurences, - pattern = _versionOccurences$ve.pattern; + names.push(name); + if (repository && repository.url) { + urls.push(manifests.size === 1 ? repository.url : `${repository.url} (${name})`); + } + } - const occurenceCount = occurences.size; + const heading = []; + heading.push(`The following software may be included in this product: ${names.join(', ')}.`); + if (urls.length > 0) { + heading.push(`A copy of the source code may be downloaded from ${urls.join(', ')}.`); + } + heading.push('This software contains the following license and notice below:'); - if (!mostOccurenceCount || occurenceCount > mostOccurenceCount) { - mostOccurenceCount = occurenceCount; - mostOccurencePattern = pattern; + console.log(heading.join(' ')); + console.log(); + + if (licenseText) { + console.log(licenseText.trim()); + } else { + // what do we do here? base it on `license`? } - } - invariant(mostOccurencePattern, 'expected most occuring pattern'); - invariant(mostOccurenceCount, 'expected most occuring count'); - // only hoist this module if it occured more than once - if (mostOccurenceCount > 1) { - this._seed(mostOccurencePattern, { isDirectRequire: false }); + console.log(); } - } + })(); } +}); - /** - * Produce a flattened list of module locations and manifests. - */ +const run = _buildSubCommands.run, + setFlags = _buildSubCommands.setFlags, + examples = _buildSubCommands.examples; +exports.run = run; +exports.setFlags = setFlags; +exports.examples = examples; - init() { - const flatTree = []; +/***/ }), +/* 399 */ +/***/ (function(module, exports, __webpack_require__) { - // - for (const _ref8 of this.tree.entries()) { - var _ref9 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref8, 2); +"use strict"; - const key = _ref9[0]; - const info = _ref9[1]; - // decompress the location and push it to the flat tree. this path could be made - const parts = []; - const keyParts = key.split('#'); - for (let i = 0; i < keyParts.length; i++) { - const key = keyParts.slice(0, i + 1).join('#'); - const hoisted = this.tree.get(key); - invariant(hoisted, 'expected hoisted manifest'); - parts.push(this.config.getFolder(hoisted.pkg)); - parts.push(keyParts[i]); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = undefined; - if (this.config.modulesFolder) { - // remove the first part which will be the folder name and replace it with a - // hardcoded modules folder - parts.splice(0, 1, this.config.modulesFolder); - } else { - // first part will be the registry-specific module folder - parts.splice(0, 0, this.config.lockfileFolder); - } +var _asyncToGenerator2; - const loc = path.join(...parts); - flatTree.push([loc, info]); - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - // remove ignored modules from the tree - const visibleFlatTree = []; - for (const _ref10 of flatTree) { - var _ref11 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref10, 2); +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + yield config.registries.yarn.saveHomeConfig({ + username: undefined, + email: undefined + }); - const loc = _ref11[0]; - const info = _ref11[1]; + reporter.success(reporter.lang('clearedCredentials')); + }); - const ref = info.pkg._reference; - invariant(ref, 'expected reference'); + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); - if (!info.isRequired) { - info.addHistory('Deleted as this module was ignored'); - } else { - visibleFlatTree.push([loc, info]); - } - } - return visibleFlatTree; - } -} +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; -exports.default = PackageHoister; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function setFlags(commander) {} + +function hasWrapper(commander, args) { + return true; +} /***/ }), -/* 361 */ +/* 400 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -78723,334 +82332,337 @@ exports.default = PackageHoister; Object.defineProperty(exports, "__esModule", { value: true }); - -var _slicedToArray2; - -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} +exports.run = exports.requireLockfile = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _executeLifecycleScript; +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.cwd); + const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); + let deps = yield (_packageRequest || _load_packageRequest()).default.getOutdatedPackages(lockfile, install, config, reporter); -function _load_executeLifecycleScript() { - return _executeLifecycleScript = _interopRequireDefault(__webpack_require__(62)); -} + if (args.length) { + const requested = new Set(args); -var _fs; + deps = deps.filter(function (_ref2) { + let name = _ref2.name; + return requested.has(name); + }); + } -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + const getNameFromHint = function (hint) { + return hint ? `${hint}Dependencies` : 'dependencies'; + }; + const colorizeName = function (_ref3) { + let current = _ref3.current, + wanted = _ref3.wanted, + name = _ref3.name; + return reporter.format[(0, (_colorForVersions || _load_colorForVersions()).default)(current, wanted)](name); + }; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (deps.length) { + const body = deps.map(function (info) { + return [colorizeName(info), info.current, (0, (_colorizeDiff || _load_colorizeDiff()).default)(info.current, info.wanted, reporter), reporter.format.magenta(info.latest), getNameFromHint(info.hint), reporter.format.cyan(info.url)]; + }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + reporter.table(['Package', 'Current', 'Wanted', 'Latest', 'Package Type', 'URL'], body); + return 1; + } + return 0; + }); -const invariant = __webpack_require__(5); + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); -const INSTALL_STAGES = ['preinstall', 'install', 'postinstall']; +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; -class PackageInstallScripts { - constructor(config, resolver, force) { - this.installed = 0; - this.resolver = resolver; - this.reporter = config.reporter; - this.config = config; - this.force = force; - this.artifacts = {}; - } +var _packageRequest; - setArtifacts(artifacts) { - this.artifacts = artifacts; - } +function _load_packageRequest() { + return _packageRequest = _interopRequireDefault(__webpack_require__(94)); +} - getArtifacts() { - return this.artifacts; - } +var _lockfile; - getInstallCommands(pkg) { - const scripts = pkg.scripts; - if (scripts) { - const cmds = []; - for (const stage of INSTALL_STAGES) { - const cmd = scripts[stage]; - if (cmd) { - cmds.push([stage, cmd]); - } - } - return cmds; - } else { - return []; - } - } +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} - walk(loc) { - var _this = this; +var _install; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const files = yield (_fs || _load_fs()).walk(loc, null, new Set(_this.config.registryFolders)); - const mtimes = new Map(); - for (const file of files) { - mtimes.set(file.relative, file.mtime); - } - return mtimes; - })(); - } +function _load_install() { + return _install = __webpack_require__(31); +} - saveBuildArtifacts(loc, pkg, beforeFiles, spinner) { - var _this2 = this; +var _colorForVersions; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const afterFiles = yield _this2.walk(loc); +function _load_colorForVersions() { + return _colorForVersions = _interopRequireDefault(__webpack_require__(271)); +} - // work out what files have been created/modified - const buildArtifacts = []; - for (const _ref of afterFiles) { - var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); +var _colorizeDiff; - const file = _ref2[0]; - const mtime = _ref2[1]; +function _load_colorizeDiff() { + return _colorizeDiff = _interopRequireDefault(__webpack_require__(272)); +} - if (!beforeFiles.has(file) || beforeFiles.get(file) !== mtime) { - buildArtifacts.push(file); - } - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (!buildArtifacts.length) { - // nothing else to do here since we have no build artifacts - return; - } +const requireLockfile = exports.requireLockfile = true; - // set build artifacts - const ref = pkg._reference; - invariant(ref, 'expected reference'); - _this2.artifacts[`${pkg.name}@${pkg.version}`] = buildArtifacts; - })(); - } +function setFlags(commander) { + commander.usage('outdated [packages ...]'); +} - install(cmds, pkg, spinner) { - var _this3 = this; +function hasWrapper(commander, args) { + return true; +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const ref = pkg._reference; - invariant(ref, 'expected reference'); - const loc = _this3.config.generateHardModulePath(ref); +/***/ }), +/* 401 */ +/***/ (function(module, exports, __webpack_require__) { - try { - for (const _ref3 of cmds) { - var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2); +"use strict"; - const stage = _ref4[0]; - const cmd = _ref4[1]; - var _ref5 = yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).default)(stage, _this3.config, loc, cmd, spinner); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.examples = exports.hasWrapper = exports.setFlags = exports.run = exports.mutate = undefined; - const stdout = _ref5.stdout; +var _asyncToGenerator2; - _this3.reporter.verbose(stdout); - } - } catch (err) { - err.message = `${loc}: ${err.message}`; +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - invariant(ref, 'expected reference'); +let mutate = exports.mutate = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args, config, reporter, buildMessages, mutator) { + if (args.length !== 2 && args.length !== 1) { + return false; + } - if (ref.optional) { - ref.ignore = true; - ref.incompatible = true; - _this3.reporter.warn(_this3.reporter.lang('optionalModuleScriptFail', err.message)); - _this3.reporter.info(_this3.reporter.lang('optionalModuleFail')); + const username = args.shift(); + const name = yield (0, (_tag || _load_tag()).getName)(args, config); + if (!(0, (_validate || _load_validate()).isValidPackageName)(name)) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('invalidPackageName')); + } - // Cleanup node_modules - try { - yield (_fs || _load_fs()).unlink(loc); - } catch (e) { - _this3.reporter.error(_this3.reporter.lang('optionalModuleCleanupFail', e.message)); + const msgs = buildMessages(username, name); + reporter.step(1, 3, reporter.lang('loggingIn')); + const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); + + reporter.step(2, 3, msgs.info); + const user = yield config.registries.npm.request(`-/user/org.couchdb.user:${username}`); + let error = false; + if (user) { + // get package + const pkg = yield config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(name)); + if (pkg) { + pkg.maintainers = pkg.maintainers || []; + error = mutator({ name: user.name, email: user.email }, pkg); + } else { + error = true; + reporter.error(reporter.lang('unknownPackage', name)); + } + + // update package + if (pkg && !error) { + const res = yield config.registries.npm.request(`${(_npmRegistry || _load_npmRegistry()).default.escapeName(name)}/-rev/${pkg._rev}`, { + method: 'PUT', + body: { + _id: pkg._id, + _rev: pkg._rev, + maintainers: pkg.maintainers } + }); + + if (res != null && res.success) { + reporter.success(msgs.success); } else { - throw err; + error = true; + reporter.error(msgs.error); } } - })(); - } - - packageCanBeInstalled(pkg) { - const cmds = this.getInstallCommands(pkg); - if (!cmds.length) { - return false; + } else { + error = true; + reporter.error(reporter.lang('unknownUser', username)); } - const ref = pkg._reference; - invariant(ref, 'Missing package reference'); - if (!ref.fresh && !this.force) { - // this package hasn't been touched - return false; + + reporter.step(3, 3, reporter.lang('revokingToken')); + yield revoke(); + + if (error) { + throw new Error(); + } else { + return true; } + }); - // we haven't actually written this module out - if (ref.ignore) { + return function mutate(_x, _x2, _x3, _x4, _x5) { + return _ref.apply(this, arguments); + }; +})(); + +let list = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (args.length > 1) { return false; } - return true; - } - - runCommand(spinner, pkg) { - var _this4 = this; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const cmds = _this4.getInstallCommands(pkg); - spinner.setPrefix(++_this4.installed, pkg.name); - yield _this4.install(cmds, pkg, spinner); - })(); - } + const name = yield (0, (_tag || _load_tag()).getName)(args, config); - // detect if there is a circularDependency in the dependency tree - detectCircularDependencies(root, seenManifests, pkg) { - const ref = pkg._reference; - invariant(ref, 'expected reference'); + reporter.step(1, 3, reporter.lang('loggingIn')); + const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, name); - const deps = ref.dependencies; - for (const dep of deps) { - const pkgDep = this.resolver.getStrictResolvedPattern(dep); - if (seenManifests.has(pkgDep)) { - // there is a cycle but not with the root - continue; - } - seenManifests.add(pkgDep); - // found a dependency pointing to root - if (pkgDep == root) { - return true; - } - if (this.detectCircularDependencies(root, seenManifests, pkgDep)) { - return true; + reporter.step(2, 3, reporter.lang('ownerGetting', name)); + const pkg = yield config.registries.npm.request(name); + if (pkg) { + const owners = pkg.maintainers; + if (!owners || !owners.length) { + reporter.warn(reporter.lang('ownerNone')); + } else { + for (const owner of owners) { + reporter.info(`${owner.name} <${owner.email}>`); + } } + } else { + reporter.error(reporter.lang('ownerGettingFailed')); } - return false; - } - // find the next package to be installed - findInstallablePackage(workQueue, installed) { - for (const pkg of workQueue) { - const ref = pkg._reference; - invariant(ref, 'expected reference'); - const deps = ref.dependencies; + reporter.step(3, 3, reporter.lang('revokingToken')); + yield revoke(); + + if (pkg) { + return true; + } else { + throw new Error(); + } + }); + + return function list(_x6, _x7, _x8, _x9) { + return _ref2.apply(this, arguments); + }; +})(); + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); +} + +var _buildSubCommands2; + +function _load_buildSubCommands() { + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); +} + +var _validate; - let dependenciesFullfilled = true; - for (const dep of deps) { - const pkgDep = this.resolver.getStrictResolvedPattern(dep); - if (!installed.has(pkgDep)) { - dependenciesFullfilled = false; - break; - } - } +function _load_validate() { + return _validate = __webpack_require__(98); +} - // all depedencies are installed - if (dependenciesFullfilled) { - return pkg; - } +var _tag; - // detect circular dependency, mark this pkg as installable to break the circle - if (this.detectCircularDependencies(pkg, new Set(), pkg)) { - return pkg; - } - } - return null; - } +function _load_tag() { + return _tag = __webpack_require__(258); +} - worker(spinner, workQueue, installed, waitQueue) { - var _this5 = this; +var _login; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - while (true) { - // No more work to be done - if (workQueue.size == 0) { - break; - } +function _load_login() { + return _login = __webpack_require__(93); +} - // find a installable package - const pkg = _this5.findInstallablePackage(workQueue, installed); +var _npmRegistry; - // can't find a package to install, register into waitQueue - if (pkg == null) { - spinner.clear(); - yield new Promise(function (resolve) { - return waitQueue.add(resolve); - }); - continue; - } +function _load_npmRegistry() { + return _npmRegistry = _interopRequireDefault(__webpack_require__(52)); +} - // found a package to install - workQueue.delete(pkg); - if (_this5.packageCanBeInstalled(pkg)) { - yield _this5.runCommand(spinner, pkg); - } - installed.add(pkg); - for (const workerResolve of waitQueue) { - workerResolve(); - } - waitQueue.clear(); - } - })(); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - init(seedPatterns) { - var _this6 = this; +function remove(config, reporter, flags, args) { + return mutate(args, config, reporter, (username, name) => ({ + info: reporter.lang('ownerRemoving', username, name), + success: reporter.lang('ownerRemoved'), + error: reporter.lang('ownerRemoveError') + }), (user, pkg) => { + let found = false; + + pkg.maintainers = pkg.maintainers.filter(o => { + const match = o.name === user.name; + found = found || match; + return !match; + }); - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const workQueue = new Set(); - const installed = new Set(); - const pkgs = _this6.resolver.getTopologicalManifests(seedPatterns); - let installablePkgs = 0; - // A map to keep track of what files exist before installation - const beforeFilesMap = new Map(); - for (const pkg of pkgs) { - if (_this6.packageCanBeInstalled(pkg)) { - const ref = pkg._reference; - invariant(ref, 'expected reference'); - const loc = _this6.config.generateHardModulePath(ref); - beforeFilesMap.set(loc, (yield _this6.walk(loc))); - installablePkgs += 1; + if (!found) { + reporter.error(reporter.lang('userNotAnOwner', user.name)); + } + + return found; + }); +} + +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('owner', { + add(config, reporter, flags, args) { + return mutate(args, config, reporter, (username, name) => ({ + info: reporter.lang('ownerAdding', username, name), + success: reporter.lang('ownerAdded'), + error: reporter.lang('ownerAddingFailed') + }), (user, pkg) => { + for (const owner of pkg.maintainers) { + if (owner.name === user) { + reporter.error(reporter.lang('ownerAlready')); + return true; } - workQueue.add(pkg); } - // waitQueue acts like a semaphore to allow workers to register to be notified - // when there are more work added to the work queue - const waitQueue = new Set(); - const workers = []; + pkg.maintainers.push(user); - const set = _this6.reporter.activitySet(installablePkgs, Math.min(_this6.config.childConcurrency, workQueue.size)); + return false; + }); + }, - for (const spinner of set.spinners) { - workers.push(_this6.worker(spinner, workQueue, installed, waitQueue)); - } + rm(config, reporter, flags, args) { + reporter.warn(`\`yarn owner rm\` is deprecated. Please use \`yarn owner remove\`.`); + return remove(config, reporter, flags, args); + }, - yield Promise.all(workers); + remove(config, reporter, flags, args) { + return remove(config, reporter, flags, args); + }, - // cache all build artifacts - for (const pkg of pkgs) { - if (_this6.packageCanBeInstalled(pkg)) { - const ref = pkg._reference; - invariant(ref, 'expected reference'); - const loc = _this6.config.generateHardModulePath(ref); - const beforeFiles = beforeFilesMap.get(loc); - invariant(beforeFiles, 'files before installation should always be recorded'); - yield _this6.saveBuildArtifacts(loc, pkg, beforeFiles, set.spinners[0]); - } - } + ls(config, reporter, flags, args) { + reporter.warn(`\`yarn owner ls\` is deprecated. Please use \`yarn owner list\`.`); + return list(config, reporter, flags, args); + }, - set.end(); - })(); + list(config, reporter, flags, args) { + return list(config, reporter, flags, args); } -} -exports.default = PackageInstallScripts; +}, ['add <user> [[<@scope>/]<pkg>]', 'remove <user> [[<@scope>/]<pkg>]', 'list [<@scope>/]<pkg>']); + +const run = _buildSubCommands.run, + setFlags = _buildSubCommands.setFlags, + hasWrapper = _buildSubCommands.hasWrapper, + examples = _buildSubCommands.examples; +exports.run = run; +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; +exports.examples = examples; /***/ }), -/* 362 */ +/* 402 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79059,120 +82671,210 @@ exports.default = PackageInstallScripts; Object.defineProperty(exports, "__esModule", { value: true }); +exports.run = undefined; -var _slicedToArray2; +var _asyncToGenerator2; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _misc; +let publish = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, pkg, flags, dir) { + // validate access argument + const access = flags.access; + if (access && access !== 'public' && access !== 'restricted') { + throw new (_errors || _load_errors()).MessageError(config.reporter.lang('invalidAccess')); + } -function _load_misc() { - return _misc = __webpack_require__(10); -} + // get tarball stream + const stat = yield (_fs || _load_fs()).lstat(dir); + let stream; + if (stat.isDirectory()) { + stream = yield (0, (_pack || _load_pack()).pack)(config, dir); + } else if (stat.isFile()) { + stream = fs2.createReadStream(dir); + } else { + throw new Error("Don't know how to handle this file type"); + } + const buffer = yield new Promise(function (resolve, reject) { + const data = []; + invariant(stream, 'expected stream'); + stream.on('data', data.push.bind(data)).on('end', function () { + return resolve(Buffer.concat(data)); + }).on('error', reject); + }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // copy normalized package and remove internal keys as they may be sensitive or yarn specific + pkg = Object.assign({}, pkg); + for (const key in pkg) { + if (key[0] === '_') { + delete pkg[key]; + } + } -class PackageReference { - constructor(request, info, remote) { - this.resolver = request.resolver; - this.lockfile = request.lockfile; - this.requests = []; - this.config = request.config; + const tag = flags.tag || 'latest'; + const tbName = `${pkg.name}-${pkg.version}.tgz`; + const tbURI = `${pkg.name}/-/${tbName}`; - this.registry = remote.registry; - this.version = info.version; - this.name = info.name; - this.uid = info._uid; + // TODO this might modify package.json, do we need to reload it? + yield config.executeLifecycleScript('prepublish'); + yield config.executeLifecycleScript('prepublishOnly'); + yield config.executeLifecycleScript('prepare'); - this.remote = remote; + // create body + const root = { + _id: pkg.name, + access: flags.access, + name: pkg.name, + description: pkg.description, + 'dist-tags': { + [tag]: pkg.version + }, + versions: { + [pkg.version]: pkg + }, + readme: pkg.readme || '', + _attachments: { + [tbName]: { + content_type: 'application/octet-stream', + data: buffer.toString('base64'), + length: buffer.length + } + } + }; - this.dependencies = []; + pkg._id = `${pkg.name}@${pkg.version}`; + pkg.dist = pkg.dist || {}; + pkg.dist.shasum = crypto.createHash('sha1').update(buffer).digest('hex'); - this.permissions = {}; - this.patterns = []; - this.optional = null; - this.root = false; - this.ignore = false; - this.incompatible = false; - this.fresh = false; - this.location = null; - this.addRequest(request); - } + const registry = String(config.getOption('registry')); + pkg.dist.tarball = url.resolve(registry, tbURI).replace(/^https:\/\//, 'http://'); - setFresh(fresh) { - this.fresh = fresh; - } + // publish package + const res = yield config.registries.npm.request((_npmRegistry || _load_npmRegistry()).default.escapeName(pkg.name), { + method: 'PUT', + body: root + }); - setLocation(loc) { - return this.location = loc; - } + if (res) { + yield config.executeLifecycleScript('publish'); + yield config.executeLifecycleScript('postpublish'); + } else { + throw new (_errors || _load_errors()).MessageError(config.reporter.lang('publishFail')); + } + }); - addRequest(request) { - this.requests.push(request); + return function publish(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); - if (!request.parentRequest) { - this.root = true; +let run = exports.run = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + // validate package fields that are required for publishing + const pkg = yield config.readRootManifest(); + if (pkg.private) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('publishPrivate')); + } + if (!pkg.name) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('noName')); } - } - prune() { - for (const selfPattern of this.patterns) { - // remove ourselves from the resolver - this.resolver.removePattern(selfPattern); + // validate arguments + const dir = args[0] || config.cwd; + if (args.length > 1) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('tooManyArguments', 1)); + } + if (!(yield (_fs || _load_fs()).exists(dir))) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownFolderOrTarball')); } - } - addDependencies(deps) { - this.dependencies = this.dependencies.concat(deps); - } + // + reporter.step(1, 4, reporter.lang('bumpingVersion')); + const commitVersion = yield (0, (_version || _load_version()).setVersion)(config, reporter, flags, args, false); - setPermission(key, val) { - this.permissions[key] = val; - } + // + reporter.step(2, 4, reporter.lang('loggingIn')); + const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter, pkg.name); - hasPermission(key) { - if (key in this.permissions) { - return this.permissions[key]; - } else { - return false; - } - } + // + reporter.step(3, 4, reporter.lang('publishing')); + yield publish(config, pkg, flags, dir); + yield commitVersion(); + reporter.success(reporter.lang('published')); - addPattern(pattern, manifest) { - this.resolver.addPattern(pattern, manifest); + // + reporter.step(4, 4, reporter.lang('revokingToken')); + yield revoke(); + }); - this.patterns.push(pattern); + return function run(_x5, _x6, _x7, _x8) { + return _ref2.apply(this, arguments); + }; +})(); - const shrunk = this.lockfile.getLocked(pattern); - if (shrunk && shrunk.permissions) { - for (const _ref of (0, (_misc || _load_misc()).entries)(shrunk.permissions)) { - var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; - const key = _ref2[0]; - const perm = _ref2[1]; +var _npmRegistry; - this.setPermission(key, perm); - } - } - } +function _load_npmRegistry() { + return _npmRegistry = _interopRequireDefault(__webpack_require__(52)); +} - addOptional(optional) { - if (this.optional == null) { - // optional is uninitialised - this.optional = optional; - } else if (!optional) { - // otherwise, ignore all subsequent optional assignments and only accept ones making - // this not optional - this.optional = false; - } - } +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); +} + +var _version; + +function _load_version() { + return _version = __webpack_require__(260); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} + +var _pack; + +function _load_pack() { + return _pack = __webpack_require__(156); +} + +var _login; + +function _load_login() { + return _login = __webpack_require__(93); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const invariant = __webpack_require__(7); +const crypto = __webpack_require__(8); +const url = __webpack_require__(14); +const fs2 = __webpack_require__(5); + +function setFlags(commander) { + (0, (_version || _load_version()).setFlags)(commander); + commander.usage('publish [<tarball>|<folder>] [--tag <tag>] [--access <public|restricted>]'); + commander.option('--access [access]', 'access'); + commander.option('--tag [tag]', 'tag'); +} + +function hasWrapper(commander, args) { + return true; } -exports.default = PackageReference; /***/ }), -/* 363 */ +/* 403 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79181,108 +82883,194 @@ exports.default = PackageReference; Object.defineProperty(exports, "__esModule", { value: true }); -exports.getRcConf = getRcConf; -exports.getRcArgs = getRcArgs; -exports.clearRcCache = clearRcCache; +exports.run = undefined; -var _path; +var _slicedToArray2; -function _load_path() { - return _path = __webpack_require__(1); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } -var _parse; +var _asyncToGenerator2; -function _load_parse() { - return _parse = _interopRequireDefault(__webpack_require__(80)); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _rc; +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + let runCommand = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (args) { + const action = args.shift(); -function _load_rc() { - return _rc = _interopRequireWildcard(__webpack_require__(391)); -} + // build up list of commands + const cmds = []; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + if (pkgScripts && action in pkgScripts) { + const preAction = `pre${action}`; + if (preAction in pkgScripts) { + cmds.push([preAction, pkgScripts[preAction]]); + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + cmds.push([action, scripts[action]]); -// Keys that will get resolved relative to the path of the rc file they belong to -const PATH_KEYS = ['cache-folder', 'global-folder', 'modules-folder']; + const postAction = `post${action}`; + if (postAction in pkgScripts) { + cmds.push([postAction, pkgScripts[postAction]]); + } + } else if (scripts[action]) { + cmds.push([action, scripts[action]]); + } + + if (cmds.length) { + // propagate YARN_SILENT env variable to executed commands + process.env.YARN_SILENT = '1'; + for (const _ref3 of cmds) { + var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2); + + const stage = _ref4[0]; + const cmd = _ref4[1]; + + // only tack on trailing arguments for default script, ignore for pre and post - #1595 + const defaultScriptCmd = cmd + joinArgs(args); + const cmdWithArgs = stage === action ? defaultScriptCmd : cmd; + yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).execCommand)(stage, config, cmdWithArgs, config.cwd); + } + } else if (action === 'env') { + reporter.log(JSON.stringify((yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).makeEnv)('env', config.cwd, config)), null, 2), { force: true }); + } else { + let suggestion; + + for (const commandName in scripts) { + const steps = leven(commandName, action); + if (steps < 2) { + suggestion = commandName; + } + } + + let msg = `Command ${JSON.stringify(action)} not found.`; + if (suggestion) { + msg += ` Did you mean ${JSON.stringify(suggestion)}?`; + } + throw new (_errors || _load_errors()).MessageError(msg); + } + }); + + return function runCommand(_x5) { + return _ref2.apply(this, arguments); + }; + })(); -let rcConfCache; -let rcArgsCache; + // list possible scripts if none specified -const buildRcConf = () => (_rc || _load_rc()).findRc('yarn', (fileText, filePath) => { - const values = (0, (_parse || _load_parse()).default)(fileText, 'yarnrc'); - const keys = Object.keys(values); - for (const key of keys) { - for (const pathKey of PATH_KEYS) { - if (key.replace(/^(--)?([^.]+\.)*/, '') === pathKey) { - values[key] = (0, (_path || _load_path()).resolve)((0, (_path || _load_path()).dirname)(filePath), values[key]); + // build up a list of possible scripts + const pkg = yield config.readManifest(config.cwd); + const scripts = (0, (_map || _load_map()).default)(); + const binCommands = []; + const visitedBinFolders = new Set(); + let pkgCommands = []; + for (const registry of Object.keys((_index || _load_index()).registries)) { + const binFolder = path.join(config.cwd, config.registries[registry].folder, '.bin'); + if (!visitedBinFolders.has(binFolder)) { + if (yield (_fs || _load_fs()).exists(binFolder)) { + for (const name of yield (_fs || _load_fs()).readdir(binFolder)) { + binCommands.push(name); + scripts[name] = `"${path.join(binFolder, name)}"`; + } + } + visitedBinFolders.add(binFolder); } } - } + const pkgScripts = pkg.scripts; + const cmdHints = {}; + if (pkgScripts) { + // inherit `scripts` from manifest + pkgCommands = Object.keys(pkgScripts).sort(); - return values; -}); + // add command hints (what the actual yarn command will do) + for (const cmd of pkgCommands) { + cmdHints[cmd] = pkgScripts[cmd] || ''; + } + + Object.assign(scripts, pkgScripts); + } + + if (args.length === 0) { + reporter.error(reporter.lang('commandNotSpecified')); + reporter.info(`${reporter.lang('binCommands') + binCommands.join(', ')}`); + reporter.info(`${reporter.lang('possibleCommands')}`); + reporter.list('possibleCommands', pkgCommands, cmdHints); + yield reporter.question(reporter.lang('commandQuestion')).then(function (answer) { + return runCommand(answer.split(' ')); + }, function () { + return reporter.error(reporter.lang('commandNotSpecified')); + }); + return Promise.resolve(); + } else { + return runCommand(args); + } + }); + + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); + +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; + +var _executeLifecycleScript; + +function _load_executeLifecycleScript() { + return _executeLifecycleScript = __webpack_require__(97); +} -function getRcConf() { - if (!rcConfCache) { - rcConfCache = buildRcConf(); - } +var _errors; - return rcConfCache; +function _load_errors() { + return _errors = __webpack_require__(3); } -const buildRcArgs = () => Object.keys(getRcConf()).reduce((argLists, key) => { - const miniparse = key.match(/^--(?:([^.]+)\.)?(.*)$/); +var _index; - if (!miniparse) { - return argLists; - } +function _load_index() { + return _index = __webpack_require__(35); +} - const namespace = miniparse[1] || '*'; - const arg = miniparse[2]; - const value = getRcConf()[key]; +var _fs; - if (!argLists[namespace]) { - argLists[namespace] = []; - } +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - if (typeof value === 'string') { - argLists[namespace] = argLists[namespace].concat([`--${arg}`, value]); - } else if (value === true) { - argLists[namespace] = argLists[namespace].concat([`--${arg}`]); - } else if (value === false) { - argLists[namespace] = argLists[namespace].concat([`--no-${arg}`]); - } +var _map; - return argLists; -}, {}); +function _load_map() { + return _map = _interopRequireDefault(__webpack_require__(16)); +} -function getRcArgs(command) { - if (!rcArgsCache) { - rcArgsCache = buildRcArgs(); - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - let result = rcArgsCache['*'] || []; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (command !== '*' && Object.prototype.hasOwnProperty.call(rcArgsCache, command)) { - result = result.concat(rcArgsCache[command] || []); - } +const leven = __webpack_require__(567); - return result; +const path = __webpack_require__(0); + +// Copied from https://github.com/npm/npm/blob/63f153c743f9354376bfb9dad42bd028a320fd1f/lib/run-script.js#L175 +function joinArgs(args) { + return args.reduce((joinedArgs, arg) => joinedArgs + ' "' + arg.replace(/"/g, '\\"') + '"', ''); } -function clearRcCache() { - rcConfCache = null; - rcArgsCache = null; +function setFlags(commander) {} + +function hasWrapper(commander, args) { + return true; } /***/ }), -/* 364 */ +/* 404 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79291,12 +83079,7 @@ function clearRcCache() { Object.defineProperty(exports, "__esModule", { value: true }); - -var _asyncToGenerator2; - -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} +exports.examples = exports.hasWrapper = exports.setFlags = exports.run = undefined; var _extends2; @@ -79304,196 +83087,237 @@ function _load_extends() { return _extends2 = _interopRequireDefault(__webpack_require__(36)); } -var _misc; +var _asyncToGenerator2; -function _load_misc() { - return _misc = __webpack_require__(10); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const objectPath = __webpack_require__(247); - -const path = __webpack_require__(1); - -class BaseRegistry { - constructor(cwd, registries, requestManager, reporter) { - this.reporter = reporter; - this.requestManager = requestManager; - this.registries = registries; - this.config = {}; - this.folder = ''; - this.token = ''; - this.loc = ''; - this.cwd = cwd; - } - - // the filename to use for package metadata - - - // - - // - - - // - - - // - +var _toArray2; - // +function _load_toArray() { + return _toArray2 = _interopRequireDefault(__webpack_require__(99)); +} +let removeTeamUser = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter) { + reporter.step(2, 3, reporter.lang('teamRemovingUser')); + reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user`, { + method: 'DELETE', + body: { + user: parts.user + } + }))); + return true; + }); - // + return function removeTeamUser(_x6, _x7, _x8) { + return _ref2.apply(this, arguments); + }; +})(); +let list = (() => { + var _ref3 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter) { + reporter.step(2, 3, reporter.lang('teamListing')); + const uriParams = '?format=cli'; + if (parts.team) { + reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user${uriParams}`))); + } else { + reporter.inspect((yield config.registries.npm.request(`org/${parts.scope}/team${uriParams}`))); + } + return true; + }); - // absolute folder name to insert modules + return function list(_x9, _x10, _x11) { + return _ref3.apply(this, arguments); + }; +})(); +var _buildSubCommands2; - // relative folder name to put these modules +function _load_buildSubCommands() { + return _buildSubCommands2 = _interopRequireDefault(__webpack_require__(51)); +} +var _login; - setToken(token) { - this.token = token; - } +function _load_login() { + return _login = __webpack_require__(93); +} - getOption(key) { - return this.config[key]; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - getAvailableRegistries() { - const config = this.config; - return Object.keys(config).reduce((registries, option) => { - if (option === 'registry' || option.split(':')[1] === 'registry') { - registries.push(config[option]); - } - return registries; - }, []); - } +function explodeScopeTeam(arg, requireTeam, reporter) { + var _arg$split = arg.split(':'), + _arg$split2 = (0, (_toArray2 || _load_toArray()).default)(_arg$split); - loadConfig() { - return Promise.resolve(); - } + const scope = _arg$split2[0], + team = _arg$split2[1], + parts = _arg$split2.slice(2); - checkOutdated(config, name, range) { - return Promise.reject(new Error('unimplemented')); + if (parts.length) { + return false; } - saveHomeConfig(config) { - return Promise.reject(new Error('unimplemented')); + if (requireTeam && !team) { + return false; } - request(pathname) { - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - return this.requestManager.request((0, (_extends2 || _load_extends()).default)({ - url: pathname - }, opts)); - } + return { + scope: scope || '', + team: team || '', + user: '' + }; +} - init() { - var _this = this; +function warnDeprecation(reporter, deprecationWarning) { + const command = 'yarn team'; + reporter.warn(reporter.lang('deprecatedCommand', `${command} ${deprecationWarning.deprecatedCommand}`, `${command} ${deprecationWarning.currentComand}`)); +} - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - _this.mergeEnv('yarn_'); - yield _this.loadConfig(); - _this.loc = path.join(_this.cwd, _this.folder); - })(); - } +function wrapRequired(callback, requireTeam, deprecationInfo) { + return (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (deprecationInfo) { + warnDeprecation(reporter, deprecationInfo); + } - static normalizeConfig(config) { - for (const key in config) { - config[key] = BaseRegistry.normalizeConfigOption(config[key]); - } - return config; - } + if (!args.length) { + return false; + } - static normalizeConfigOption(val) { - if (val === 'true') { - return true; - } else if (val === 'false') { - return false; - } else { - return val; - } - } + const parts = explodeScopeTeam(args[0], requireTeam, reporter); + if (!parts) { + return false; + } - mergeEnv(prefix) { - // try environment variables - for (const envKey in process.env) { - let key = envKey.toLowerCase(); + reporter.step(1, 3, reporter.lang('loggingIn')); + const revoke = yield (0, (_login || _load_login()).getToken)(config, reporter); - // only accept keys prefixed with the prefix - if (key.indexOf(prefix.toLowerCase()) < 0) { - continue; + const res = yield callback(parts, config, reporter, flags, args); + if (!res) { + return res; } - const val = BaseRegistry.normalizeConfigOption(process.env[envKey]); - - // remove config prefix - key = (0, (_misc || _load_misc()).removePrefix)(key, prefix.toLowerCase()); + reporter.step(3, 3, reporter.lang('revokingToken')); + yield revoke(); + return true; + }); - // replace dunders with dots - key = key.replace(/__/g, '.'); + return function (_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; + })(); +} - // replace underscores with dashes - key = key.replace(/_/g, '-'); +function wrapRequiredTeam(callback) { + let requireTeam = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + let subCommandDeprecated = arguments[2]; - // set it via a path - objectPath.set(this.config, key, val); + return wrapRequired(function (parts, config, reporter, flags, args) { + if (args.length === 1) { + return callback(parts, config, reporter, flags, args); + } else { + return false; } - } + }, requireTeam, subCommandDeprecated); } -exports.default = BaseRegistry; - -/***/ }), -/* 365 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +function wrapRequiredUser(callback, subCommandDeprecated) { + return wrapRequired(function (parts, config, reporter, flags, args) { + if (args.length === 2) { + return callback((0, (_extends2 || _load_extends()).default)({ + user: args[1] + }, parts), config, reporter, flags, args); + } else { + return false; + } + }, true, subCommandDeprecated); +} +var _buildSubCommands = (0, (_buildSubCommands2 || _load_buildSubCommands()).default)('team', { + create: wrapRequiredTeam((() => { + var _ref4 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { + reporter.step(2, 3, reporter.lang('teamCreating')); + reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}`, { + method: 'PUT', + body: { + team: parts.team + } + }))); + return true; + }); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = isRequestToRegistry; + return function (_x12, _x13, _x14, _x15, _x16) { + return _ref4.apply(this, arguments); + }; + })()), -var _url; + destroy: wrapRequiredTeam((() => { + var _ref5 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { + reporter.step(2, 3, reporter.lang('teamRemoving')); + reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}`, { + method: 'DELETE' + }))); + return true; + }); -function _load_url() { - return _url = _interopRequireDefault(__webpack_require__(11)); -} + return function (_x17, _x18, _x19, _x20, _x21) { + return _ref5.apply(this, arguments); + }; + })()), -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + add: wrapRequiredUser((() => { + var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (parts, config, reporter, flags, args) { + reporter.step(2, 3, reporter.lang('teamAddingUser')); + reporter.inspect((yield config.registries.npm.request(`team/${parts.scope}/${parts.team}/user`, { + method: 'PUT', + body: { + user: parts.user + } + }))); + return true; + }); -function isRequestToRegistry(requestUrl, registry, customHostSuffix) { - const requestParsed = (_url || _load_url()).default.parse(requestUrl); - const registryParsed = (_url || _load_url()).default.parse(registry); - const requestHost = requestParsed.hostname || ''; - const registryHost = registryParsed.hostname || ''; - const requestPort = getPortOrDefaultPort(requestParsed.port, requestParsed.protocol); - const registryPort = getPortOrDefaultPort(registryParsed.port, registryParsed.protocol); - const requestPath = requestParsed.path || ''; - const registryPath = registryParsed.path || ''; + return function (_x22, _x23, _x24, _x25, _x26) { + return _ref6.apply(this, arguments); + }; + })()), - return requestHost === registryHost && requestPort === registryPort && (requestPath.startsWith(registryPath) || - // For some registries, the package path does not prefix with the registry path - !!customHostSuffix && customHostSuffix.length > 0 && requestHost.endsWith(customHostSuffix)); -} + rm: wrapRequiredUser(function (parts, config, reporter, flags, args) { + removeTeamUser(parts, config, reporter); + }, { + deprecatedCommand: 'rm', + currentComand: 'remove' + }), + + remove: wrapRequiredUser(function (parts, config, reporter, flags, args) { + removeTeamUser(parts, config, reporter); + }), + + ls: wrapRequiredTeam(function (parts, config, reporter, flags, args) { + list(parts, config, reporter); + }, false, { + deprecatedCommand: 'ls', + currentComand: 'list' + }), + + list: wrapRequiredTeam(function (parts, config, reporter, flags, args) { + list(parts, config, reporter); + }, false) +}, ['create <scope:team>', 'destroy <scope:team>', 'add <scope:team> <user>', 'remove <scope:team> <user>', 'list <scope>|<scope:team>']); -function getPortOrDefaultPort(port, protocol) { - if (protocol === 'https:' && port === '443') { - return null; - } - if (protocol === 'http:' && port === '80') { - return null; - } - return port; -} +const run = _buildSubCommands.run, + setFlags = _buildSubCommands.setFlags, + hasWrapper = _buildSubCommands.hasWrapper, + examples = _buildSubCommands.examples; +exports.run = run; +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; +exports.examples = examples; /***/ }), -/* 366 */ +/* 405 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79502,42 +83326,71 @@ function getPortOrDefaultPort(port, protocol) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULTS = undefined; - -var _slicedToArray2; - -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} +exports.run = undefined; var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _constants; +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (args.length) { + for (const name of args) { + const linkLoc = path.join(config.linkFolder, name); + if (yield (_fs || _load_fs()).exists(linkLoc)) { + yield (_fs || _load_fs()).unlink(path.join((yield (0, (_link || _load_link()).getRegistryFolder)(config, name)), name)); + reporter.success(reporter.lang('linkDisusing', name)); + reporter.info(reporter.lang('linkDisusingMessage', name)); + } else { + throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name)); + } + } + } else { + // remove from registry + const manifest = yield config.readRootManifest(); + const name = manifest.name; + if (!name) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('unknownPackageName')); + } -function _load_constants() { - return _constants = __webpack_require__(8); -} + const linkLoc = path.join(config.linkFolder, name); + if (yield (_fs || _load_fs()).exists(linkLoc)) { + // If there is a `bin` defined in the package.json, + // link each bin to the global bin + if (manifest.bin) { + const globalBinFolder = yield (0, (_global || _load_global()).getBinFolder)(config, flags); + for (const binName in manifest.bin) { + const binDestLoc = path.join(globalBinFolder, binName); + if (yield (_fs || _load_fs()).exists(binDestLoc)) { + yield (_fs || _load_fs()).unlink(binDestLoc); + } + } + } -var _npmRegistry; + yield (_fs || _load_fs()).unlink(linkLoc); -function _load_npmRegistry() { - return _npmRegistry = _interopRequireDefault(__webpack_require__(43)); -} + reporter.success(reporter.lang('linkUnregistered', name)); + reporter.info(reporter.lang('linkUnregisteredMessage', name)); + } else { + throw new (_errors || _load_errors()).MessageError(reporter.lang('linkMissing', name)); + } + } + }); -var _stringify; + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); -function _load_stringify() { - return _stringify = _interopRequireDefault(__webpack_require__(81)); -} +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; -var _parse; +var _errors; -function _load_parse() { - return _parse = _interopRequireDefault(__webpack_require__(80)); +function _load_errors() { + return _errors = __webpack_require__(3); } var _fs; @@ -79546,182 +83399,86 @@ function _load_fs() { return _fs = _interopRequireWildcard(__webpack_require__(4)); } -var _yarnVersion; +var _link; -function _load_yarnVersion() { - return _yarnVersion = __webpack_require__(65); +function _load_link() { + return _link = __webpack_require__(255); +} + +var _global; + +function _load_global() { + return _global = __webpack_require__(92); } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const userHome = __webpack_require__(86).default; - -const path = __webpack_require__(1); +const path = __webpack_require__(0); -const DEFAULTS = exports.DEFAULTS = { - 'version-tag-prefix': 'v', - 'version-git-tag': true, - 'version-git-sign': false, - 'version-git-message': 'v%s', +function setFlags(commander) {} - 'init-version': '1.0.0', - 'init-license': 'MIT', +function hasWrapper(commander, args) { + return true; +} - 'save-prefix': '^', - 'ignore-scripts': false, - 'ignore-optional': false, - registry: (_constants || _load_constants()).YARN_REGISTRY, - 'strict-ssl': true, - 'user-agent': [`yarn/${(_yarnVersion || _load_yarnVersion()).version}`, 'npm/?', `node/${process.version}`, process.platform, process.arch].join(' ') -}; +/***/ }), +/* 406 */ +/***/ (function(module, exports, __webpack_require__) { -const npmMap = { - 'version-git-sign': 'sign-git-tag', - 'version-tag-prefix': 'tag-version-prefix', - 'version-git-tag': 'git-tag-version', - 'version-git-message': 'message' -}; +"use strict"; -class YarnRegistry extends (_npmRegistry || _load_npmRegistry()).default { - constructor(cwd, registries, requestManager, reporter) { - super(cwd, registries, requestManager, reporter); - this.homeConfigLoc = path.join(userHome, '.yarnrc'); - this.homeConfig = {}; - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = undefined; - getOption(key) { - let val = this.config[key]; +var _asyncToGenerator2; - // if this isn't set in a yarn config, then use npm - if (typeof val === 'undefined') { - val = this.registries.npm.getOption(npmMap[key]); - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - if (typeof val === 'undefined') { - val = this.registries.npm.getOption(key); - } +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const versions = { yarn: (_yarnVersion || _load_yarnVersion()).version }; - // if this isn't set in a yarn config or npm config, then use the default (or undefined) - if (typeof val === 'undefined') { - val = DEFAULTS[key]; + const pkg = yield config.maybeReadManifest(config.cwd); + if (pkg && pkg.name && pkg.version) { + versions[pkg.name] = pkg.version; } - return val; - } - - loadConfig() { - var _this = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - for (const _ref of yield _this.getPossibleConfigLocations('.yarnrc', _this.reporter)) { - var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 3); - - const isHome = _ref2[0]; - const loc = _ref2[1]; - const file = _ref2[2]; - - const config = (0, (_parse || _load_parse()).default)(file, loc); - - if (isHome) { - _this.homeConfig = config; - } - - // normalize offline mirror path relative to the current yarnrc - const offlineLoc = config['yarn-offline-mirror']; - - // don't normalize if we already have a mirror path - if (!_this.config['yarn-offline-mirror'] && offlineLoc) { - const mirrorLoc = config['yarn-offline-mirror'] = path.resolve(path.dirname(loc), offlineLoc); - yield (_fs || _load_fs()).mkdirp(mirrorLoc); - } - - // merge with any existing environment variables - const env = config.env; - if (env) { - const existingEnv = _this.config.env; - if (existingEnv) { - _this.config.env = Object.assign({}, env, existingEnv); - } - } - - _this.config = Object.assign({}, config, _this.config); - } - - // default yarn config - _this.config = Object.assign({}, DEFAULTS, _this.config); - })(); - } - - saveHomeConfig(config) { - var _this2 = this; - - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - YarnRegistry.normalizeConfig(config); - - for (const key in config) { - const val = config[key]; - - // if the current config key was taken from home config then update - // the global config - if (_this2.homeConfig[key] === _this2.config[key]) { - _this2.config[key] = val; - } - - // update just the home config - _this2.homeConfig[key] = config[key]; - } - - yield (_fs || _load_fs()).writeFilePreservingEol(_this2.homeConfigLoc, `${(0, (_stringify || _load_stringify()).default)(_this2.homeConfig)}\n`); - })(); - } -} -exports.default = YarnRegistry; -YarnRegistry.filename = 'yarn.json'; - -/***/ }), -/* 367 */ -/***/ (function(module, exports, __webpack_require__) { + Object.assign(versions, process.versions); -"use strict"; + reporter.inspect(versions); + }); + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); -Object.defineProperty(exports, "__esModule", { - value: true -}); +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; -var _jsonReporter; +var _yarnVersion; -function _load_jsonReporter() { - return _jsonReporter = _interopRequireDefault(__webpack_require__(124)); +function _load_yarnVersion() { + return _yarnVersion = __webpack_require__(91); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class BufferReporter extends (_jsonReporter || _load_jsonReporter()).default { - constructor(opts) { - super(opts); - this._buffer = []; - } - - _dump(type, data, error) { - this._buffer.push({ - type, - data, - error: !!error - }); - } +function setFlags(commander) {} - getBuffer() { - return this._buffer; - } +function hasWrapper(commander, args) { + return true; } -exports.default = BufferReporter; /***/ }), -/* 368 */ +/* 407 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -79730,686 +83487,1081 @@ exports.default = BufferReporter; Object.defineProperty(exports, "__esModule", { value: true }); +exports.run = exports.requireLockfile = undefined; -var _asyncToGenerator2; +var _slicedToArray2; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } -var _baseReporter; +var _asyncToGenerator2; -function _load_baseReporter() { - return _baseReporter = _interopRequireDefault(__webpack_require__(51)); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _progressBar; +let cleanQuery = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, query) { + // if a location was passed then turn it into a hash query + if (path.isAbsolute(query) && (yield (_fs || _load_fs()).exists(query))) { + // absolute path + query = path.relative(config.cwd, query); + } -function _load_progressBar() { - return _progressBar = _interopRequireDefault(__webpack_require__(370)); -} + // remove references to node_modules with hashes + query = query.replace(/([\\/]|^)node_modules[\\/]/g, '#'); -var _spinnerProgress; + // remove trailing hashes + query = query.replace(/^#+/g, ''); -function _load_spinnerProgress() { - return _spinnerProgress = _interopRequireDefault(__webpack_require__(371)); -} + // remove trailing paths from each part of the query, skip second part of path for scoped packages + let queryParts = query.split('#'); + queryParts = queryParts.map(function (part) { + let parts = part.split(/[\\/]/g); -var _util; + if (part[0] === '@') { + parts = parts.slice(0, 2); + } else { + parts = parts.slice(0, 1); + } -function _load_util() { - return _util = __webpack_require__(123); -} + return parts.join('/'); + }); + query = queryParts.join('#'); -var _misc; + return query; + }); -function _load_misc() { - return _misc = __webpack_require__(10); -} + return function cleanQuery(_x, _x2) { + return _ref.apply(this, arguments); + }; +})(); -var _treeHelper; +let getPackageSize = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (tuple) { + var _tuple = (0, (_slicedToArray2 || _load_slicedToArray()).default)(tuple, 1); -function _load_treeHelper() { - return _treeHelper = __webpack_require__(369); -} + const loc = _tuple[0]; -var _inquirer; -function _load_inquirer() { - return _inquirer = _interopRequireDefault(__webpack_require__(152)); -} + const files = yield (_fs || _load_fs()).walk(loc, null, new Set([(_constants || _load_constants()).METADATA_FILENAME, (_constants || _load_constants()).TARBALL_FILENAME])); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + const sizes = yield Promise.all(files.map(function (walkFile) { + return (_fs || _load_fs()).getFileSizeOnDisk(walkFile.absolute); + })); -var _require = __webpack_require__(2); + return sum(sizes); + }); -const inspect = _require.inspect; + return function getPackageSize(_x3) { + return _ref2.apply(this, arguments); + }; +})(); -const readline = __webpack_require__(115); -const chalk = __webpack_require__(15); -const read = __webpack_require__(578); -const tty = __webpack_require__(116); +let run = exports.run = (() => { + var _ref6 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + if (!args.length) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('missingWhyDependency')); + } + if (args.length > 1) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('tooManyArguments', 1)); + } -// fixes bold on windows -if (process.platform === 'win32' && process.env.TERM && !/^xterm/i.test(process.env.TERM)) { - chalk.styles.bold.close += '\u001b[m'; -} + const query = yield cleanQuery(config, args[0]); -class ConsoleReporter extends (_baseReporter || _load_baseReporter()).default { - constructor(opts) { - super(opts); + reporter.step(1, 4, reporter.lang('whyStart', args[0]), emoji.get('thinking_face')); - this._lastCategorySize = 0; - this.format = chalk; - this.isSilent = !!opts.isSilent; - } + // init + reporter.step(2, 4, reporter.lang('whyInitGraph'), emoji.get('truck')); + const lockfile = yield (_lockfile || _load_lockfile()).default.fromDirectory(config.lockfileFolder, reporter); + const install = new (_install || _load_install()).Install(flags, config, reporter, lockfile); - _prependEmoji(msg, emoji) { - if (this.emoji && emoji && this.isTTY) { - msg = `${emoji} ${msg}`; - } - return msg; - } + var _ref7 = yield install.fetchRequestFromCwd(); - _logCategory(category, color, msg) { - this._lastCategorySize = category.length; - this._log(`${this.format[color](category)} ${msg}`); - } + const depRequests = _ref7.requests, + patterns = _ref7.patterns, + workspaceLayout = _ref7.workspaceLayout; - _verbose(msg) { - this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`); - } + yield install.resolver.init(depRequests, { + isFlat: install.flags.flat, + isFrozen: install.flags.frozenLockfile, + workspaceLayout + }); + const hoisted = yield install.linker.getFlatHoistedTree(patterns); - _verboseInspect(obj) { - this.inspect(obj); - } + // finding + reporter.step(3, 4, reporter.lang('whyFinding'), emoji.get('mag')); - table(head, body) { - // - head = head.map(field => this.format.underline(field)); + let match; + for (const _ref8 of hoisted) { + var _ref9 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref8, 2); - // - const rows = [head].concat(body); + const loc = _ref9[0]; + const info = _ref9[1]; - // get column widths - const cols = []; - for (let i = 0; i < head.length; i++) { - const widths = rows.map(row => this.format.stripColor(row[i]).length); - cols[i] = Math.max(...widths); + if (info.key === query || info.previousKeys.indexOf(query) >= 0) { + match = [loc, info]; + break; + } } - // - const builtRows = rows.map(row => { - for (let i = 0; i < row.length; i++) { - const field = row[i]; - const padding = cols[i] - this.format.stripColor(field).length; + if (!match) { + reporter.error(reporter.lang('whyUnknownMatch')); + return; + } - row[i] = field + ' '.repeat(padding); + var _match = match, + _match2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_match, 2); + + const matchInfo = _match2[1]; + + const matchRef = matchInfo.pkg._reference; + invariant(matchRef, 'expected reference'); + + const matchPatterns = matchRef.patterns; + const matchRequests = matchRef.requests; + + const reasons = []; + // reason: dependency of these modules + for (const request of matchRequests) { + const parentRequest = request.parentRequest; + if (!parentRequest) { + continue; } - return row.join(' '); - }); - this.log(builtRows.join('\n')); - } + const dependent = install.resolver.getResolvedPattern(parentRequest.pattern); + if (!dependent) { + continue; + } - step(current, total, msg, emoji) { - msg = this._prependEmoji(msg, emoji); + const chain = []; - if (msg.endsWith('?')) { - msg = `${(0, (_misc || _load_misc()).removeSuffix)(msg, '?')}...?`; - } else { - msg += '...'; + let delegator = parentRequest; + do { + chain.push(install.resolver.getStrictResolvedPattern(delegator.pattern).name); + } while (delegator = delegator.parentRequest); + + reasons.push({ + type: 'whyDependedOn', + typeSimple: 'whyDependedOnSimple', + value: chain.reverse().join('#') + }); } - this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`); - } + // reason: exists in manifest + let rootType; + for (const pattern of matchPatterns) { + rootType = install.rootPatternsToOrigin[pattern]; + if (rootType) { + reasons.push({ + type: 'whySpecified', + typeSimple: 'whySpecifiedSimple', + value: rootType + }); + } + } - inspect(value) { - if (typeof value !== 'number' && typeof value !== 'string') { - value = inspect(value, { - breakLength: 0, - colors: true, - depth: null, - maxArrayLength: null - }); + // reason: this is hoisted from these modules + for (const pattern of matchInfo.previousKeys) { + if (pattern !== matchInfo.key) { + reasons.push({ + type: 'whyHoistedFrom', + typeSimple: 'whyHoistedFromSimple', + value: pattern + }); + } } - this.log('' + value); - } + // package sizes + reporter.step(4, 4, reporter.lang('whyCalculating'), emoji.get('aerial_tramway')); - list(key, items, hints) { - const gutterWidth = (this._lastCategorySize || 2) - 1; + let packageSize = 0; + let directSizes = []; + let transitiveSizes = []; + try { + packageSize = yield getPackageSize(match); + } catch (e) {} - if (hints) { - for (const item of items) { - this._log(`${' '.repeat(gutterWidth)}- ${item}`); - this._log(` ${' '.repeat(gutterWidth)} ${hints[item]}`); - } + const dependencies = Array.from(collect(hoisted, new Set(), match)); + const transitiveDependencies = Array.from(collect(hoisted, new Set(), match, { recursive: true })); + + try { + directSizes = yield Promise.all(dependencies.map(getPackageSize)); + transitiveSizes = yield Promise.all(transitiveDependencies.map(getPackageSize)); + } catch (e) {} + + const transitiveKeys = new Set(transitiveDependencies.map(function (_ref10) { + var _ref11 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref10, 2); + + let info = _ref11[1]; + return info.key; + })); + const sharedDependencies = getSharedDependencies(hoisted, transitiveKeys); + + // + // reason: hoisted + if (query === matchInfo.originalKey) { + reporter.info(reporter.lang('whyHoistedTo', matchInfo.key)); + } + + if (reasons.length === 1) { + reporter.info(reporter.lang(reasons[0].typeSimple, reasons[0].value)); + } else if (reasons.length > 1) { + reporter.info(reporter.lang('whyReasons')); + reporter.list('reasons', reasons.map(function (reason) { + return reporter.lang(reason.type, reason.value); + })); } else { - for (const item of items) { - this._log(`${' '.repeat(gutterWidth)}- ${item}`); - } + reporter.error(reporter.lang('whyWhoKnows')); } - } - header(command, pkg) { - this.log(this.format.bold(`${pkg.name} ${command} v${pkg.version}`)); - } + if (packageSize) { + // stats: file size of this dependency without any dependencies + reporter.info(reporter.lang('whyDiskSizeWithout', bytes(packageSize))); - footer(showPeakMemory) { - const totalTime = (this.getTotalTime() / 1000).toFixed(2); - let msg = `Done in ${totalTime}s.`; - if (showPeakMemory) { - const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2); - msg += ` Peak memory usage ${peakMemory}MB.`; - } - this.log(this._prependEmoji(msg, '✨')); - } + // stats: file size of this dependency including dependencies that aren't shared + reporter.info(reporter.lang('whyDiskSizeUnique', bytes(packageSize + sum(directSizes)))); - log(msg) { - this._lastCategorySize = 0; - this._log(msg); - } + // stats: file size of this dependency including dependencies + reporter.info(reporter.lang('whyDiskSizeTransitive', bytes(packageSize + sum(transitiveSizes)))); - _log(msg) { - if (this.isSilent) { - return; + // stats: shared transitive dependencies + reporter.info(reporter.lang('whySharedDependencies', sharedDependencies.size)); } - (0, (_util || _load_util()).clearLine)(this.stdout); - this.stdout.write(`${msg}\n`); - } + }); - success(msg) { - this._logCategory('success', 'green', msg); - } + return function run(_x5, _x6, _x7, _x8) { + return _ref6.apply(this, arguments); + }; +})(); - error(msg) { - (0, (_util || _load_util()).clearLine)(this.stderr); - this.stderr.write(`${this.format.red('error')} ${msg}\n`); - } +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; - info(msg) { - this._logCategory('info', 'blue', msg); - } +var _install; - command(command) { - this.log(this.format.dim(`$ ${command}`)); - } +function _load_install() { + return _install = __webpack_require__(31); +} - warn(msg) { - (0, (_util || _load_util()).clearLine)(this.stderr); - this.stderr.write(`${this.format.yellow('warning')} ${msg}\n`); - } +var _constants; - question(question) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +function _load_constants() { + return _constants = __webpack_require__(6); +} - if (!process.stdout.isTTY) { - return Promise.reject(new Error("Can't answer a question unless a user TTY")); - } +var _fs; - return new Promise((resolve, reject) => { - read({ - prompt: `${this.format.dim('question')} ${question}: `, - silent: !!options.password, - output: this.stdout, - input: this.stdin - }, (err, answer) => { - if (err) { - if (err.message === 'canceled') { - process.exit(1); - } else { - reject(err); - } - } else { - if (!answer && options.required) { - this.error(this.lang('answerRequired')); - resolve(this.question(question, options)); - } else { - resolve(answer); - } - } - }); - }); - } - // handles basic tree output to console - tree(key, trees) { - // - const output = (_ref, titlePrefix, childrenPrefix) => { - let name = _ref.name, - children = _ref.children, - hint = _ref.hint, - color = _ref.color; +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - const formatter = this.format; - const out = (0, (_treeHelper || _load_treeHelper()).getFormattedOutput)({ - prefix: titlePrefix, - hint, - color, - name, - formatter - }); - this.stdout.write(out); +var _lockfile; - if (children && children.length) { - (0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(children), childrenPrefix, output); - } - }; - (0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(trees), '', output); +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} + +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const requireLockfile = exports.requireLockfile = true; + +const invariant = __webpack_require__(7); +const bytes = __webpack_require__(453); +const emoji = __webpack_require__(298); +const path = __webpack_require__(0); + +function sum(array) { + return array.length ? array.reduce((a, b) => a + b, 0) : 0; +} + +function collect(hoistManifests, allDependencies, dependency) { + var _ref3 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { recursive: false }; + + let recursive = _ref3.recursive; + + var _dependency = (0, (_slicedToArray2 || _load_slicedToArray()).default)(dependency, 2); + + const depInfo = _dependency[1]; + + const deps = depInfo.pkg.dependencies; + + if (!deps) { + return allDependencies; } - activitySet(total, workers) { - if (!this.isTTY || this.noProgress) { - return super.activitySet(total, workers); - } + const dependencyKeys = new Set(Object.keys(deps)); + const directDependencies = []; - const spinners = []; + for (const dep of hoistManifests) { + var _dep = (0, (_slicedToArray2 || _load_slicedToArray()).default)(dep, 2); - for (let i = 1; i < workers; i++) { - this.log(''); - } + const info = _dep[1]; - for (let i = 0; i < workers; i++) { - const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr, i); - spinner.start(); - let prefix = null; - let current = 0; - const updatePrefix = () => { - spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `); - }; - const clear = () => { - prefix = null; - current = 0; - updatePrefix(); - spinner.setText('waiting...'); - }; - clear(); + if (!allDependencies.has(dep) && dependencyKeys.has(info.key)) { + allDependencies.add(dep); + directDependencies.push(dep); + } + } - spinners.unshift({ - clear, + if (recursive) { + directDependencies.forEach(dependency => collect(hoistManifests, allDependencies, dependency, { recursive: true })); + } - setPrefix(_current, _prefix) { - current = _current; - prefix = _prefix; - spinner.setText(prefix); - updatePrefix(); - }, + return allDependencies; +} - tick(msg) { - if (prefix) { - msg = `${prefix}: ${msg}`; - } - spinner.setText(msg); - }, +function getSharedDependencies(hoistManifests, transitiveKeys) { + const sharedDependencies = new Set(); + for (const _ref4 of hoistManifests) { + var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref4, 2); - end() { - spinner.stop(); + const info = _ref5[1]; + + if (!transitiveKeys.has(info.key) && info.pkg.dependencies) { + Object.keys(info.pkg.dependencies).forEach(dependency => { + if (transitiveKeys.has(dependency) && !sharedDependencies.has(dependency)) { + sharedDependencies.add(dependency); } }); } - - return { - spinners, - end: () => { - for (const spinner of spinners) { - spinner.end(); - } - readline.moveCursor(this.stdout, 0, -workers + 1); - } - }; } + return sharedDependencies; +} - activity() { - if (!this.isTTY) { - return { - tick() {}, - end() {} - }; - } +function setFlags(commander) {} - const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr); - spinner.start(); +function hasWrapper(commander, args) { + return true; +} - return { - tick(name) { - spinner.setText(name); - }, +/***/ }), +/* 408 */ +/***/ (function(module, exports, __webpack_require__) { - end() { - spinner.stop(); - } - }; - } +"use strict"; - select(header, question, options) { - if (!this.isTTY) { - return Promise.reject(new Error("Can't answer a question unless a user TTY")); - } - const rl = readline.createInterface({ - input: this.stdin, - output: this.stdout, - terminal: true - }); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.run = undefined; - const questions = options.map(opt => opt.name); - const answers = options.map(opt => opt.value); +var _toArray2; - function toIndex(input) { - const index = answers.indexOf(input); +function _load_toArray() { + return _toArray2 = _interopRequireDefault(__webpack_require__(99)); +} - if (index >= 0) { - return index; - } else { - return +input; - } - } +var _asyncToGenerator2; - return new Promise(resolve => { - this.info(header); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - for (let i = 0; i < questions.length; i++) { - this.log(` ${this.format.dim(`${i + 1})`)} ${questions[i]}`); - } +let run = exports.run = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (config, reporter, flags, args) { + const workspaceRootFolder = config.workspaceRootFolder; - const ask = () => { - rl.question(`${question}: `, input => { - let index = toIndex(input); - if (isNaN(index)) { - this.log('Not a number'); - ask(); - return; - } + if (!workspaceRootFolder) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceRootNotFound', config.cwd)); + } - if (index <= 0 || index > options.length) { - this.log('Outside answer range'); - ask(); - return; - } + if (args.length < 1) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceMissingWorkspace')); + } - // get index - index--; - rl.close(); - resolve(answers[index]); - }); - }; + if (args.length < 2) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceMissingCommand')); + } - ask(); - }); - } + const manifest = yield config.findManifest(workspaceRootFolder, false); + invariant(manifest && manifest.workspaces, 'We must find a manifest with a "workspaces" property'); - progress(count) { - if (this.noProgress || count <= 0) { - return function () { - // noop - }; - } + const workspaces = yield config.resolveWorkspaces(workspaceRootFolder, manifest); - if (!this.isTTY) { - return function () { - // TODO what should the behaviour here be? we could buffer progress messages maybe - }; + var _args = (0, (_toArray2 || _load_toArray()).default)(args); + + const workspaceName = _args[0], + rest = _args.slice(1); + + if (!Object.prototype.hasOwnProperty.call(workspaces, workspaceName)) { + throw new (_errors || _load_errors()).MessageError(reporter.lang('workspaceUnknownWorkspace', workspaceName)); } - const bar = new (_progressBar || _load_progressBar()).default(count, this.stderr); + const workspace = workspaces[workspaceName]; - bar.render(); + try { + yield (_child || _load_child()).spawn((_constants || _load_constants()).NODE_BIN_PATH, [(_constants || _load_constants()).YARN_BIN_PATH, ...rest], { + stdio: 'inherit', + cwd: workspace.loc + }); + } catch (err) { + throw err; + } + }); - return function () { - bar.tick(); - }; - } + return function run(_x, _x2, _x3, _x4) { + return _ref.apply(this, arguments); + }; +})(); - prompt(message, choices) { - var _this = this; +exports.setFlags = setFlags; +exports.hasWrapper = hasWrapper; - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - if (!process.stdout.isTTY) { - return Promise.reject(new Error("Can't answer a question unless a user TTY")); - } +var _errors; - let pageSize; - if (process.stdout instanceof tty.WriteStream) { - pageSize = process.stdout.rows - 2; - } +function _load_errors() { + return _errors = __webpack_require__(3); +} - const rl = readline.createInterface({ - input: _this.stdin, - output: _this.stdout, - terminal: true - }); +var _child; - // $FlowFixMe: Need to update the type of Inquirer - const prompt = (_inquirer || _load_inquirer()).default.createPromptModule({ - input: _this.stdin, - output: _this.stdout - }); +function _load_child() { + return _child = _interopRequireWildcard(__webpack_require__(48)); +} - let rejectRef = function () {}; - const killListener = function () { - rejectRef(); - }; +var _constants; - const handleKillFromInquirer = new Promise(function (resolve, reject) { - rejectRef = reject; - }); +function _load_constants() { + return _constants = __webpack_require__(6); +} - rl.addListener('SIGINT', killListener); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - var _options$name = options.name; - const name = _options$name === undefined ? 'prompt' : _options$name; - var _options$type = options.type; - const type = _options$type === undefined ? 'input' : _options$type, - validate = options.validate; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - const answers = yield Promise.race([prompt([{ name, type, message, choices, pageSize, validate }]), handleKillFromInquirer]); +const invariant = __webpack_require__(7); - rl.removeListener('SIGINT', killListener); - rl.close(); +function setFlags(commander) {} - return answers[name]; - })(); - } +function hasWrapper(commander, args) { + return true; } -exports.default = ConsoleReporter; /***/ }), -/* 369 */ +/* 409 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; - +/* WEBPACK VAR INJECTION */(function(module) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.sortTrees = sortTrees; -exports.recurseTree = recurseTree; -exports.getFormattedOutput = getFormattedOutput; +exports.autoRun = undefined; +var _asyncToGenerator2; -// public +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} +let start = (() => { + var _ref2 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const rc = (0, (_rc || _load_rc()).getRcConfigForCwd)(process.cwd()); + const yarnPath = rc['yarn-path']; -// types -function sortTrees(trees) { - return trees.sort(function (tree1, tree2) { - return tree1.name.localeCompare(tree2.name); + if (yarnPath && process.env.YARN_IGNORE_PATH !== '1') { + const argv = process.argv.slice(2); + const opts = { stdio: 'inherit', env: Object.assign({}, process.env, { YARN_IGNORE_PATH: 1 }) }; + + try { + yield (0, (_child || _load_child()).spawnp)(yarnPath, argv, opts); + } catch (firstError) { + try { + yield (0, (_child || _load_child()).forkp)(yarnPath, argv, opts); + } catch (error) { + throw firstError; + } + } + } else { + // ignore all arguments after a -- + const doubleDashIndex = process.argv.findIndex(function (element) { + return element === '--'; + }); + const startArgs = process.argv.slice(0, 2); + const args = process.argv.slice(2, doubleDashIndex === -1 ? process.argv.length : doubleDashIndex); + const endArgs = doubleDashIndex === -1 ? [] : process.argv.slice(doubleDashIndex); + + main({ startArgs, args, endArgs }); + } }); + + return function start() { + return _ref2.apply(this, arguments); + }; +})(); + +// When this module is compiled via Webpack, its child +// count will be 0 since it is a single-file bundle. + + +exports.main = main; + +var _index; + +function _load_index() { + return _index = __webpack_require__(153); } -function recurseTree(tree, prefix, recurseFunc) { - const treeLen = tree.length; - const treeEnd = treeLen - 1; - for (let i = 0; i < treeLen; i++) { - const atEnd = i === treeEnd; - recurseFunc(tree[i], prefix + getLastIndentChar(atEnd), prefix + getNextIndentChar(atEnd)); - } +var _index2; + +function _load_index2() { + return _index2 = __webpack_require__(34); } -function getFormattedOutput(fmt) { - const item = formatColor(fmt.color, fmt.name, fmt.formatter); - const suffix = getSuffix(fmt.hint, fmt.formatter); - return `${fmt.prefix}─ ${item}${suffix}\n`; +var _index3; + +function _load_index3() { + return _index3 = _interopRequireDefault(__webpack_require__(231)); } -function getNextIndentChar(end) { - return end ? ' ' : '│ '; +var _constants; + +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); } -function getLastIndentChar(end) { - return end ? 'â””' : '├'; +var _network; + +function _load_network() { + return _network = _interopRequireWildcard(__webpack_require__(233)); } -function getSuffix(hint, formatter) { - return hint ? ` (${formatter.grey(hint)})` : ''; +var _errors; + +function _load_errors() { + return _errors = __webpack_require__(3); } -function formatColor(color, strToFormat, formatter) { - return color ? formatter[color](strToFormat) : strToFormat; +var _config; + +function _load_config() { + return _config = _interopRequireDefault(__webpack_require__(232)); } -/***/ }), -/* 370 */ -/***/ (function(module, exports, __webpack_require__) { +var _rc; -"use strict"; +function _load_rc() { + return _rc = __webpack_require__(333); +} +var _child; -Object.defineProperty(exports, "__esModule", { - value: true -}); +function _load_child() { + return _child = __webpack_require__(48); +} -var _util; +var _yarnVersion; -function _load_util() { - return _util = __webpack_require__(123); +function _load_yarnVersion() { + return _yarnVersion = __webpack_require__(91); } -class ProgressBar { - constructor(total) { - let stdout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.stderr; +var _signalHandler; - this.stdout = stdout; - this.total = total; - this.chars = ProgressBar.bars[0]; - this.delay = 60; - this.curr = 0; - (0, (_util || _load_util()).clearLine)(stdout); - } +function _load_signalHandler() { + return _signalHandler = _interopRequireDefault(__webpack_require__(334)); +} - tick() { - this.curr++; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - // schedule render - if (!this.id) { - this.id = setTimeout(() => this.render(), this.delay); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - // progress complete - if (this.curr >= this.total) { - clearTimeout(this.id); - (0, (_util || _load_util()).clearLine)(this.stdout); - } +const commander = __webpack_require__(335); + +const fs = __webpack_require__(5); +const invariant = __webpack_require__(7); +const lockfile = __webpack_require__(338); +const loudRejection = __webpack_require__(337); +const http = __webpack_require__(49); +const net = __webpack_require__(59); +const onDeath = __webpack_require__(336); +const path = __webpack_require__(0); + +function findProjectRoot(base) { + let prev = null; + let dir = base; + + do { + if (fs.existsSync(path.join(dir, (_constants || _load_constants()).NODE_PACKAGE_JSON))) { + return dir; + } + + prev = dir; + dir = path.dirname(dir); + } while (dir !== prev); + + return base; +} + +function main(_ref) { + let startArgs = _ref.startArgs, + args = _ref.args, + endArgs = _ref.endArgs; + + loudRejection(); + (0, (_signalHandler || _load_signalHandler()).default)(); + + // set global options + commander.version((_yarnVersion || _load_yarnVersion()).version, '--version'); + commander.usage('[command] [flags]'); + commander.option('-v, --verbose', 'output verbose messages on internal operations'); + commander.option('--offline', 'trigger an error if any required dependencies are not available in local cache'); + commander.option('--prefer-offline', 'use network only if dependencies are not available in local cache'); + commander.option('--strict-semver'); + commander.option('--json', ''); + commander.option('--ignore-scripts', "don't run lifecycle scripts"); + commander.option('--har', 'save HAR output of network traffic'); + commander.option('--ignore-platform', 'ignore platform checks'); + commander.option('--ignore-engines', 'ignore engines check'); + commander.option('--ignore-optional', 'ignore optional dependencies'); + commander.option('--force', 'install and build packages even if they were built before, overwrite lockfile'); + commander.option('--skip-integrity-check', 'run install without checking if node_modules is installed'); + commander.option('--check-files', 'install will verify file tree of packages for consistency'); + commander.option('--no-bin-links', "don't generate bin links when setting up packages"); + commander.option('--flat', 'only allow one version of a package'); + commander.option('--prod, --production [prod]', ''); + commander.option('--no-lockfile', "don't read or generate a lockfile"); + commander.option('--pure-lockfile', "don't generate a lockfile"); + commander.option('--frozen-lockfile', "don't generate a lockfile and fail if an update is needed"); + commander.option('--link-duplicates', 'create hardlinks to the repeated modules in node_modules'); + commander.option('--link-folder <path>', 'specify a custom folder to store global links'); + commander.option('--global-folder <path>', 'specify a custom folder to store global packages'); + commander.option('--modules-folder <path>', 'rather than installing modules into the node_modules folder relative to the cwd, output them here'); + commander.option('--preferred-cache-folder <path>', 'specify a custom folder to store the yarn cache if possible'); + commander.option('--cache-folder <path>', 'specify a custom folder that must be used to store the yarn cache'); + commander.option('--mutex <type>[:specifier]', 'use a mutex to ensure only one yarn instance is executing'); + commander.option('--emoji [bool]', 'enable emoji in output', process.platform === 'darwin'); + commander.option('-s, --silent', 'skip Yarn console logs, other types of logs (script output) will be printed'); + commander.option('--cwd <cwd>', 'working directory to use', process.cwd()); + commander.option('--proxy <host>', ''); + commander.option('--https-proxy <host>', ''); + commander.option('--no-progress', 'disable progress bar'); + commander.option('--network-concurrency <number>', 'maximum number of concurrent network requests', parseInt); + commander.option('--network-timeout <milliseconds>', 'TCP timeout for network requests', parseInt); + commander.option('--non-interactive', 'do not show interactive prompts'); + commander.option('--scripts-prepend-node-path [bool]', 'prepend the node executable dir to the PATH in scripts'); + + // get command name + let commandName = args.shift() || 'install'; + + // if -v is the first command, then always exit after returning the version + if (commandName === '-v') { + console.log((_yarnVersion || _load_yarnVersion()).version.trim()); + process.exitCode = 0; + return; } - render() { - // clear throttle - clearTimeout(this.id); - this.id = null; + if (commandName === '--help' || commandName === '-h') { + commandName = 'help'; + } - let ratio = this.curr / this.total; - ratio = Math.min(Math.max(ratio, 0), 1); + if (args.indexOf('--help') >= 0 || args.indexOf('-h') >= 0) { + args.unshift(commandName); + commandName = 'help'; + } - // progress without bar - let bar = ` ${this.curr}/${this.total}`; + // if no args or command name looks like a flag then set default to `install` + if (commandName[0] === '-') { + args.unshift(commandName); + commandName = 'install'; + } - // calculate size of actual bar - // $FlowFixMe: investigate process.stderr.columns flow error - const availableSpace = Math.max(0, this.stdout.columns - bar.length - 1); - const width = Math.min(this.total, availableSpace); - const completeLength = Math.round(width * ratio); - const complete = this.chars[0].repeat(completeLength); - const incomplete = this.chars[1].repeat(width - completeLength); - bar = `${complete}${incomplete}${bar}`; + let command; + if (Object.prototype.hasOwnProperty.call((_index3 || _load_index3()).default, commandName)) { + command = (_index3 || _load_index3()).default[commandName]; + } - (0, (_util || _load_util()).toStartOfLine)(this.stdout); - this.stdout.write(bar); + // if command is not recognized, then set default to `run` + if (!command) { + args.unshift(commandName); + command = (_index3 || _load_index3()).default.run; } -} -exports.default = ProgressBar; -ProgressBar.bars = [['â–ˆ', 'â–‘']]; -/***/ }), -/* 371 */ -/***/ (function(module, exports, __webpack_require__) { + let warnAboutRunDashDash = false; + // we are using "yarn <script> -abc" or "yarn run <script> -abc", we want -abc to be script options, not yarn options + if (command === (_index3 || _load_index3()).default.run) { + if (endArgs.length === 0) { + endArgs = ['--', ...args.splice(1)]; + } else { + warnAboutRunDashDash = true; + } + } -"use strict"; + command.setFlags(commander); + commander.parse([...startArgs, + // we use this for https://github.com/tj/commander.js/issues/346, otherwise + // it will strip some args that match with any options + 'this-arg-will-get-stripped-later', ...(0, (_rc || _load_rc()).getRcArgs)(commandName, args), ...args]); + commander.args = commander.args.concat(endArgs.slice(1)); + // we strip cmd + console.assert(commander.args.length >= 1); + console.assert(commander.args[0] === 'this-arg-will-get-stripped-later'); + commander.args.shift(); -Object.defineProperty(exports, "__esModule", { - value: true -}); + // + const Reporter = commander.json ? (_index || _load_index()).JSONReporter : (_index || _load_index()).ConsoleReporter; + const reporter = new Reporter({ + emoji: process.stdout.isTTY && commander.emoji, + verbose: commander.verbose, + noProgress: !commander.progress, + isSilent: process.env.YARN_SILENT === '1' || commander.silent + }); -var _util; + const exit = exitCode => { + process.exitCode = exitCode || 0; + reporter.close(); + }; -function _load_util() { - return _util = __webpack_require__(123); -} + reporter.initPeakMemoryCounter(); -class Spinner { - constructor() { - let stdout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.stderr; - let lineNumber = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; + const config = new (_config || _load_config()).default(reporter); + const outputWrapper = !commander.json && command.hasWrapper(commander, commander.args); - this.current = 0; - this.prefix = ''; - this.lineNumber = lineNumber; - this.stdout = stdout; - this.delay = 60; - this.chars = Spinner.spinners[28].split(''); - this.text = ''; - this.id = null; + if (outputWrapper) { + reporter.header(commandName, { name: 'yarn', version: (_yarnVersion || _load_yarnVersion()).version }); } - setPrefix(prefix) { - this.prefix = prefix; + if (command.noArguments && commander.args.length) { + reporter.error(reporter.lang('noArguments')); + reporter.info(command.getDocsInfo); + exit(1); + return; } - setText(text) { - this.text = text; + + // + if (commander.yes) { + reporter.warn(reporter.lang('yesWarning')); } - start() { - this.current = 0; - this.render(); + + // + if (!commander.offline && (_network || _load_network()).isOffline()) { + reporter.warn(reporter.lang('networkWarning')); } - render() { - if (this.id) { - clearTimeout(this.id); - } - // build line ensuring we don't wrap to the next line - let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`; - const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100; - msg = msg.slice(0, columns); - (0, (_util || _load_util()).writeOnNthLine)(this.stdout, this.lineNumber, msg); - this.current = ++this.current % this.chars.length; - this.id = setTimeout(() => this.render(), this.delay); + + // + if (command.requireLockfile && !fs.existsSync(path.join(config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME))) { + reporter.error(reporter.lang('noRequiredLockfile')); + exit(1); + return; } - stop() { - if (this.id) { - clearTimeout(this.id); - this.id = null; + + // + const run = () => { + invariant(command, 'missing command'); + + if (warnAboutRunDashDash) { + reporter.warn(reporter.lang('dashDashDeprecation')); + } + + return command.run(config, reporter, commander, commander.args).then(exitCode => { + if (outputWrapper) { + reporter.footer(false); + } + return exitCode; + }); + }; + + // + const runEventuallyWithFile = (mutexFilename, isFirstTime) => { + return new Promise(resolve => { + const lockFilename = mutexFilename || path.join(config.cwd, (_constants || _load_constants()).SINGLE_INSTANCE_FILENAME); + lockfile.lock(lockFilename, { realpath: false }, (err, release) => { + if (err) { + if (isFirstTime) { + reporter.warn(reporter.lang('waitingInstance')); + } + setTimeout(() => { + resolve(runEventuallyWithFile(mutexFilename, false)); + }, 200); // do not starve the CPU + } else { + onDeath(() => { + process.exitCode = 1; + }); + resolve(run().then(release)); + } + }); + }); + }; + + const runEventuallyWithNetwork = mutexPort => { + return new Promise((resolve, reject) => { + const connectionOptions = { + port: +mutexPort || (_constants || _load_constants()).SINGLE_INSTANCE_PORT + }; + + function startServer() { + const clients = new Set(); + const server = http.createServer(manager); + + // The server must not prevent us from exiting + server.unref(); + + // No socket must timeout, so that they aren't closed before we exit + server.timeout = 0; + + // If we fail to setup the server, we ask the existing one for its name + server.on('error', () => { + reportServerName(); + }); + + // If we succeed, keep track of all the connected sockets to close them later + server.on('connection', socket => { + clients.add(socket); + socket.on('close', () => { + clients.delete(socket); + }); + }); + + server.listen(connectionOptions, () => { + // Don't forget to kill the sockets if we're being killed via signals + onDeath(killSockets); + + // Also kill the sockets if we finish, whether it's a success or a failure + run().then(res => { + killSockets(); + resolve(res); + }, err => { + killSockets(); + reject(err); + }); + }); + + function manager(request, response) { + response.writeHead(200); + response.end(JSON.stringify({ cwd: config.cwd, pid: process.pid })); + } + + function killSockets() { + try { + server.close(); + } catch (err) { + // best effort + } + + for (const socket of clients) { + try { + socket.destroy(); + } catch (err) { + // best effort + } + } + + // If the process hasn't exited in the next 5s, it has stalled and we abort + const timeout = setTimeout(() => { + console.error('Process stalled'); + if (process._getActiveHandles) { + console.error('Active handles:'); + // $FlowFixMe: getActiveHandles is undocumented, but it exists + for (const handle of process._getActiveHandles()) { + console.error(` - ${handle.constructor.name}`); + } + } + // eslint-disable-next-line no-process-exit + process.exit(1); + }, 5000); + + // This timeout must not prevent us from exiting + // $FlowFixMe: Node's setTimeout returns a Timeout, not a Number + timeout.unref(); + } + } + + function reportServerName() { + const request = http.get(connectionOptions, response => { + const buffers = []; + + response.on('data', buffer => { + buffers.push(buffer); + }); + + response.on('end', () => { + var _JSON$parse = JSON.parse(Buffer.concat(buffers).toString()); + + const cwd = _JSON$parse.cwd, + pid = _JSON$parse.pid; + + reporter.warn(reporter.lang('waitingNamedInstance', pid, cwd)); + waitForTheNetwork(); + }); + + response.on('error', () => { + startServer(); + }); + }); + + request.on('error', () => { + startServer(); + }); + } + + function waitForTheNetwork() { + const socket = net.createConnection(connectionOptions); + + socket.on('error', () => { + // catch & ignore, the retry is handled in 'close' + }); + + socket.on('close', () => { + startServer(); + }); + } + + startServer(); + }); + }; + + function onUnexpectedError(err) { + function indent(str) { + return '\n ' + str.trim().split('\n').join('\n '); + } + + const log = []; + log.push(`Arguments: ${indent(process.argv.join(' '))}`); + log.push(`PATH: ${indent(process.env.PATH || 'undefined')}`); + log.push(`Yarn version: ${indent((_yarnVersion || _load_yarnVersion()).version)}`); + log.push(`Node version: ${indent(process.versions.node)}`); + log.push(`Platform: ${indent(process.platform + ' ' + process.arch)}`); + + // add manifests + for (const registryName of (_index2 || _load_index2()).registryNames) { + const possibleLoc = path.join(config.cwd, (_index2 || _load_index2()).registries[registryName].filename); + const manifest = fs.existsSync(possibleLoc) ? fs.readFileSync(possibleLoc, 'utf8') : 'No manifest'; + log.push(`${registryName} manifest: ${indent(manifest)}`); + } + + // lockfile + const lockLoc = path.join(config.cwd, (_constants || _load_constants()).LOCKFILE_FILENAME); + const lockfile = fs.existsSync(lockLoc) ? fs.readFileSync(lockLoc, 'utf8') : 'No lockfile'; + log.push(`Lockfile: ${indent(lockfile)}`); + + log.push(`Trace: ${indent(err.stack)}`); + + const errorReportLoc = writeErrorReport(log); + + reporter.error(reporter.lang('unexpectedError', err.message)); + + if (errorReportLoc) { + reporter.info(reporter.lang('bugReport', errorReportLoc)); } - (0, (_util || _load_util()).clearNthLine)(this.stdout, this.lineNumber); } + + function writeErrorReport(log) { + const errorReportLoc = config.enableMetaFolder ? path.join(config.cwd, (_constants || _load_constants()).META_FOLDER, 'yarn-error.log') : path.join(config.cwd, 'yarn-error.log'); + + try { + fs.writeFileSync(errorReportLoc, log.join('\n\n') + '\n'); + } catch (err) { + reporter.error(reporter.lang('fileWriteError', errorReportLoc, err.message)); + return undefined; + } + + return errorReportLoc; + } + + const cwd = findProjectRoot(commander.cwd); + + config.init({ + cwd, + + binLinks: commander.binLinks, + modulesFolder: commander.modulesFolder, + linkFolder: commander.linkFolder, + globalFolder: commander.globalFolder, + preferredCacheFolder: commander.preferredCacheFolder, + cacheFolder: commander.cacheFolder, + preferOffline: commander.preferOffline, + captureHar: commander.har, + ignorePlatform: commander.ignorePlatform, + ignoreEngines: commander.ignoreEngines, + ignoreScripts: commander.ignoreScripts, + offline: commander.preferOffline || commander.offline, + looseSemver: !commander.strictSemver, + production: commander.production, + httpProxy: commander.proxy, + httpsProxy: commander.httpsProxy, + networkConcurrency: commander.networkConcurrency, + networkTimeout: commander.networkTimeout, + nonInteractive: commander.nonInteractive, + scriptsPrependNodePath: commander.scriptsPrependNodePath, + + commandName: commandName === 'run' ? commander.args[0] : commandName + }).then(() => { + // option "no-progress" stored in yarn config + const noProgressConfig = config.registries.yarn.getOption('no-progress'); + + if (noProgressConfig) { + reporter.disableProgress(); + } + + // verbose logs outputs process.uptime() with this line we can sync uptime to absolute time on the computer + reporter.verbose(`current time: ${new Date().toISOString()}`); + + const mutex = commander.mutex; + if (mutex && typeof mutex === 'string') { + const separatorLoc = mutex.indexOf(':'); + let mutexType; + let mutexSpecifier; + if (separatorLoc === -1) { + mutexType = mutex; + mutexSpecifier = undefined; + } else { + mutexType = mutex.substring(0, separatorLoc); + mutexSpecifier = mutex.substring(separatorLoc + 1); + } + + if (mutexType === 'file') { + return runEventuallyWithFile(mutexSpecifier, true).then(exit); + } else if (mutexType === 'network') { + return runEventuallyWithNetwork(mutexSpecifier).then(exit); + } else { + throw new (_errors || _load_errors()).MessageError(`Unknown single instance type ${mutexType}`); + } + } else { + return run().then(exit); + } + }).catch(err => { + reporter.verbose(err.stack); + + if (err instanceof (_errors || _load_errors()).MessageError) { + reporter.error(err.message); + } else { + onUnexpectedError(err); + } + + if ((_index3 || _load_index3()).default[commandName]) { + reporter.info((_index3 || _load_index3()).default[commandName].getDocsInfo); + } + + return exit(1); + }); } -exports.default = Spinner; -Spinner.spinners = ['|/-\\', 'â ‚-–—–-', 'â—â—“â—‘â—’', '◴◷◶◵', '◰◳◲◱', 'â––â–˜â–â–—', '■□▪▫', '▌▀â–â–„', '▉▊▋▌â–â–Žâ–â–Žâ–▌▋▊▉', 'â–▃▄▅▆▇█▇▆▅▄▃', 'â†â†–↑↗→↘↓↙', '┤┘┴└├┌┬â”', '◢◣◤◥', '.oO°Oo.', '.oO@*', 'ðŸŒðŸŒŽðŸŒ', 'â—¡â—¡ ⊙⊙ â— â— ', '☱☲☴', '⠋⠙⠹⠸⠼⠴⠦⠧⠇â ', '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓', '⠄⠆⠇⠋⠙⠸⠰â ⠰⠸⠙⠋⠇⠆', '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒â â â ’â “â ‹', 'â ⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉â ', '⠈⠉⠋⠓⠒â â ⠒⠖⠦⠤â â ⠤⠦⠖⠒â â ⠒⠓⠋⠉⠈', 'â â ⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤â â ⠤⠦⠖⠒â â ⠒⠓⠋⠉⠈⠈', '⢄⢂â¢â¡â¡ˆâ¡â¡ ', '⢹⢺⢼⣸⣇⡧⡗â¡', '⣾⣽⣻⢿⡿⣟⣯⣷', 'â ⠂⠄⡀⢀â â â ˆ']; + +const autoRun = exports.autoRun = module.children.length === 0; + +if (__webpack_require__.c[__webpack_require__.s] === module) { + start(); +} + +exports.default = start; +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 372 */ +/* 410 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80419,36 +84571,45 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _jsonReporter; +var _asyncToGenerator2; -function _load_jsonReporter() { - return _jsonReporter = _interopRequireDefault(__webpack_require__(124)); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _baseFetcher; -var _require = __webpack_require__(49); +function _load_baseFetcher() { + return _baseFetcher = _interopRequireDefault(__webpack_require__(122)); +} -const EventEmitter = _require.EventEmitter; -class EventReporter extends (_jsonReporter || _load_jsonReporter()).default { +var _fs; - constructor(opts) { - super(opts); +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - // $FlowFixMe: looks like a flow bug - EventEmitter.call(this); - } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - _dump(type, data) { - this.emit(type, data); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +class CopyFetcher extends (_baseFetcher || _load_baseFetcher()).default { + _fetch() { + var _this = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield (_fs || _load_fs()).copy(_this.reference, _this.dest, _this.reporter); + return { + hash: _this.hash || '', + resolved: null + }; + })(); } } - -exports.default = EventReporter; -Object.assign(EventReporter.prototype, EventEmitter.prototype); +exports.default = CopyFetcher; /***/ }), -/* 373 */ +/* 411 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80458,436 +84619,364 @@ Object.defineProperty(exports, "__esModule", { value: true }); -/* eslint max-len: 0 */ +var _slicedToArray2; -const messages = { - upToDate: 'Already up-to-date.', - folderInSync: 'Folder in sync.', - nothingToInstall: 'Nothing to install.', - resolvingPackages: 'Resolving packages', - fetchingPackages: 'Fetching packages', - linkingDependencies: 'Linking dependencies', - rebuildingPackages: 'Rebuilding all packages', - buildingFreshPackages: 'Building fresh packages', - cleaningModules: 'Cleaning modules', - bumpingVersion: 'Bumping version', - savingHar: 'Saving HAR file: $0', - answer: 'Answer?', - usage: 'Usage', - installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.', - waitingInstance: 'Waiting for the other yarn instance to finish', - offlineRetrying: 'There appears to be trouble with your network connection. Retrying...', - clearedCache: 'Cleared cache.', - couldntClearPackageFromCache: "Couldn't clear package $0 from cache", - clearedPackageFromCache: 'Cleared package $0 from cache', - packWroteTarball: 'Wrote tarball to $0.', +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} - manifestPotentialTypo: 'Potential typo $0, did you mean $1?', - manifestBuiltinModule: '$0 is also the name of a node core module', - manifestNameDot: "Name can't start with a dot", - manifestNameIllegalChars: 'Name contains illegal characters', - manifestNameBlacklisted: 'Name is blacklisted', - manifestLicenseInvalid: 'License should be a valid SPDX license expression', - manifestLicenseNone: 'No license field', - manifestStringExpected: '$0 is not a string', - manifestDependencyCollision: '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4', - manifestDirectoryNotFound: 'Unable to read $0 directory of module $1', +var _asyncToGenerator2; - verboseFileCopy: 'Copying $0 to $1.', - verboseFileLink: 'Creating hardlink at $0 to $1.', - verboseFileSymlink: 'Creating symlink at $0 to $1.', - verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).', - verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).', - verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).', - verboseFileRemoveExtraneous: 'Removing extraneous file $0.', - verboseFilePhantomExtraneous: "File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.", - verboseFileFolder: 'Creating directory $0.', +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - verboseRequestStart: 'Performing $0 request to $1.', - verboseRequestFinish: 'Request $0 finished with status code $1.', +var _errors; - configSet: 'Set $0 to $1.', - configDelete: 'Deleted $0.', - configNpm: 'npm config', - configYarn: 'yarn config', +function _load_errors() { + return _errors = __webpack_require__(3); +} - couldntFindPackagejson: "Couldn't find a package.json file in $0", - couldntFindMatch: "Couldn't find match for $0 in $1 for $2.", - couldntFindPackageInCache: "Couldn't find any versions for $0 that matches $1 in our cache. Possible versions: $2", - couldntFindVersionThatMatchesRange: "Couldn't find any versions for $0 that matches $1", - chooseVersionFromList: 'Please choose a version of $0 from this list:', - moduleNotInManifest: "This module isn't specified in a manifest.", - unknownFolderOrTarball: "Passed folder/tarball doesn't exist,", - unknownPackage: "Couldn't find package $0.", - unknownPackageName: "Couldn't find package name.", - unknownUser: "Couldn't find user $0.", - unknownRegistryResolver: 'Unknown registry resolver $0', - userNotAnOwner: "User $0 isn't an owner of this package.", - invalidVersionArgument: 'Use the $0 flag to create a new version.', - invalidVersion: 'Invalid version supplied.', - requiredVersionInRange: 'Required version in range.', - packageNotFoundRegistry: "Couldn't find package $0 on the $1 registry.", - doesntExist: "$0 doesn't exist.", - missingRequiredPackageKey: `Package $0 doesn't have a $1.`, - invalidAccess: 'Invalid argument for access, expected public or restricted.', - invalidCommand: 'Invalid subcommand. Try $0', - invalidGistFragment: 'Invalid gist fragment $0.', - invalidHostedGitFragment: 'Invalid hosted git fragment $0.', - invalidFragment: 'Invalid fragment $0.', - invalidPackageName: 'Invalid package name.', - couldntFindManifestIn: "Couldn't find manifest in $0.", - shrinkwrapWarning: 'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.', - lockfileOutdated: 'Outdated lockfile. Please run `yarn install` and try again.', - ignoredScripts: 'Ignored scripts due to flag.', - missingAddDependencies: 'Missing list of packages to add to your project.', - yesWarning: 'The yes flag has been set. This will automatically answer yes to all questions which may have security implications.', - networkWarning: "You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.", - flatGlobalError: 'The package $0@$1 requires a flat dependency graph. Add `"flat": true` to your package.json and try again.', - noName: `Package doesn't have a name.`, - noVersion: `Package doesn't have a version.`, - answerRequired: 'An answer is required.', - missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed', - bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.', - unexpectedError: 'An unexpected error occurred: $0.', - jsonError: 'Error parsing JSON at $0, $1.', - noFilePermission: "We don't have permissions to touch the file $0.", - allDependenciesUpToDate: 'All of your dependencies are up to date.', - legendColorsForUpgradeInteractive: 'Color legend : \n $0 : Patch Update Backward-compatible bug fixes \n $1 : Minor Update backward-compatibles features', - frozenLockfileError: 'Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile`.', - fileWriteError: 'Could not write file $0: $1', - multiplePackagesCantUnpackInSameDestination: 'Pattern $0 is trying to unpack in the same destination $1 as pattern $2. This could result in a non deterministic behavior, skipping.', - incorrectLockfileEntry: 'Lockfile has incorrect entry for $0. Ignoring it.', +var _baseFetcher; - yarnOutdated: "Your current version of Yarn is out of date. The latest version is $0 while you're on $1.", - yarnOutdatedInstaller: 'To upgrade, download the latest installer at $0.', - yarnOutdatedCommand: 'To upgrade, run the following command:', +function _load_baseFetcher() { + return _baseFetcher = _interopRequireDefault(__webpack_require__(122)); +} - tooManyArguments: 'Too many arguments, maximum of $0.', - tooFewArguments: 'Not enough arguments, expected at least $0.', - noArguments: "This command doesn't require any arguments.", +var _git; - ownerRemoving: 'Removing owner $0 from package $1.', - ownerRemoved: 'Owner removed.', - ownerRemoveError: "Couldn't remove owner.", - ownerGetting: 'Getting owners for package $0', - ownerGettingFailed: "Couldn't get list of owners.", - ownerAlready: 'This user is already an owner of this package.', - ownerAdded: 'Added owner.', - ownerAdding: 'Adding owner $0 to package $1', - ownerAddingFailed: "Couldn't add owner.", - ownerNone: 'No owners.', +function _load_git() { + return _git = _interopRequireDefault(__webpack_require__(165)); +} - teamCreating: 'Creating team', - teamRemoving: 'Removing team', - teamAddingUser: 'Adding user to team', - teamRemovingUser: 'Removing user from team', - teamListing: 'Listing teams', +var _fs; - cleaning: 'Cleaning modules', - cleanCreatingFile: 'Creating $0', +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} - binLinkCollision: "There's already a linked binary called $0 in your global Yarn bin. Could not link this package's $0 bin entry.", - linkCollision: "There's already a module called $0 registered.", - linkMissing: 'No registered module found called $0.', - linkRegistered: 'Registered $0.', - linkRegisteredMessage: 'You can now run `yarn link $0` in the projects where you want to use this module and it will be used instead.', - linkUnregistered: 'Unregistered $0.', - linkUnregisteredMessage: 'You can now run `yarn unlink $0` in the projects where you no longer want to use this module.', - linkUsing: 'Using linked module for $0.', - linkDisusing: 'Removed linked module $0.', - linkDisusingMessage: 'You will need to run `yarn` to re-install the package that was linked.', +var _constants; - createInvalidBin: 'Invalid bin entry found in package $0.', - createMissingPackage: 'Package not found - this is probably an internal error, and should be reported at https://github.com/yarnpkg/yarn/issues.', +function _load_constants() { + return _constants = _interopRequireWildcard(__webpack_require__(6)); +} - workspacesRequirePrivateProjects: 'Workspaces can only be enabled in private projects', - workspaceExperimentalDisabled: 'The workspace feature is currently experimental and needs to be manually enabled - please add "workspaces-experimental true" to your .yarnrc file.', - workspaceRootNotFound: "Cannot find the root of your workspace - are you sure you're currently in a workspace?", - workspaceMissingWorkspace: 'Missing workspace name.', - workspaceMissingCommand: 'Missing command name.', - workspaceUnknownWorkspace: 'Unknown workspace $0.', - workspaceVersionMandatory: 'Missing version in workspace at $0, ignoring.', - workspaceNameMandatory: 'Missing name in workspace at $0, ignoring.', - workspaceNameDuplicate: 'There are more than one workspace with name $0', +var _crypto; - execMissingCommand: 'Missing command name.', +function _load_crypto() { + return _crypto = _interopRequireWildcard(__webpack_require__(123)); +} - commandNotSpecified: 'No command specified.', - binCommands: 'Commands available from binary scripts: ', - possibleCommands: 'Project commands', - commandQuestion: 'Which command would you like to run?', - commandFailed: 'Command failed with exit code $0.', - packageRequiresNodeGyp: 'This package requires node-gyp, which is not currently installed. Yarn will attempt to automatically install it. If this fails, you can run "yarn global add node-gyp" to manually install it.', - nodeGypAutoInstallFailed: 'Failed to auto-install node-gyp. Please run "yarn global add node-gyp" manually. Error: $0', +var _install; - foundIncompatible: 'Found incompatible module', - incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1.', - incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.', - incompatibleOS: 'The platform $0 is incompatible with this module.', - invalidEngine: 'The engine $0 appears to be invalid.', +function _load_install() { + return _install = __webpack_require__(31); +} - optionalCompatibilityExcluded: '$0 is an optional dependency and failed compatibility check. Excluding it from installation.', - optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error', - optionalModuleScriptFail: 'Error running install script for optional dependency: $0', - optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0', +var _lockfile; - unmetPeer: '$0 has unmet peer dependency $1.', - incorrectPeer: '$0 has incorrect peer dependency $1.', +function _load_lockfile() { + return _lockfile = _interopRequireDefault(__webpack_require__(12)); +} - savedNewDependency: 'Saved 1 new dependency.', - savedNewDependencies: 'Saved $0 new dependencies.', +var _config; - foundWarnings: 'Found $0 warnings.', - foundErrors: 'Found $0 errors.', +function _load_config() { + return _config = _interopRequireDefault(__webpack_require__(232)); +} - savedLockfile: 'Saved lockfile.', - noRequiredLockfile: 'No lockfile in this directory. Run `yarn install` to generate one.', - noLockfileFound: 'No lockfile found.', +var _pack; - invalidSemver: 'Invalid semver version', - newVersion: 'New version', - currentVersion: 'Current version', +function _load_pack() { + return _pack = __webpack_require__(156); +} - manualVersionResolution: 'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:', - manualVersionResolutionOption: '$0 which resolved to $1', +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - createdTag: 'Created tag.', - createdTagFail: "Couldn't add tag.", - deletedTag: 'Deleted tag.', - deletedTagFail: "Couldn't delete tag.", - gettingTags: 'Getting tags', - deletingTags: 'Deleting tag', - creatingTag: 'Creating tag $0 = $1', +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - whyStart: 'Why do we have the module $0?', - whyFinding: 'Finding dependency', - whyCalculating: 'Calculating file sizes', - whyUnknownMatch: "We couldn't find a match!", - whyInitGraph: 'Initialising dependency graph', - whyWhoKnows: "We don't know why this module exists", - whyDiskSizeWithout: 'Disk size without dependencies: $0', - whyDiskSizeUnique: 'Disk size with unique dependencies: $0', - whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0', - whySharedDependencies: 'Number of shared dependencies: $0', - whyHoistedTo: `Has been hoisted to $0`, +const tarFs = __webpack_require__(145); +const url = __webpack_require__(14); +const path = __webpack_require__(0); +const fs = __webpack_require__(5); - whyHoistedFromSimple: `This module exists because it's hoisted from $0.`, - whyDependedOnSimple: `This module exists because $0 depends on it.`, - whySpecifiedSimple: `This module exists because it's specified in $0.`, - whyReasons: 'Reasons this module exists', - whyHoistedFrom: 'Hoisted from $0', - whyDependedOn: '$0 depends on it', - whySpecified: `Specified in $0`, +const invariant = __webpack_require__(7); - uninstalledPackages: 'Uninstalled packages.', - uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies', +const PACKED_FLAG = '1'; - cleanRemovedFiles: 'Removed $0 files', - cleanSavedSize: 'Saved $0 MB.', +class GitFetcher extends (_baseFetcher || _load_baseFetcher()).default { + setupMirrorFromCache() { + var _this = this; - configFileFound: 'Found configuration file $0.', - configPossibleFile: 'Checking for configuration file $0.', + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const tarballMirrorPath = _this.getTarballMirrorPath(); + const tarballCachePath = _this.getTarballCachePath(); - npmUsername: 'npm username', - npmPassword: 'npm password', - npmEmail: 'npm email', + if (tarballMirrorPath == null) { + return; + } - loggingIn: 'Logging in', - loggedIn: 'Logged in.', - notRevokingEnvToken: 'Not revoking login token, specified via environment variable.', - notRevokingConfigToken: 'Not revoking login token, specified via config file.', - noTokenToRevoke: 'No login token to revoke.', - revokingToken: 'Revoking token', - revokedToken: 'Revoked login token.', + if (!(yield (_fs || _load_fs()).exists(tarballMirrorPath)) && (yield (_fs || _load_fs()).exists(tarballCachePath))) { + // The tarball doesn't exists in the offline cache but does in the cache; we import it to the mirror + yield (_fs || _load_fs()).mkdirp(path.dirname(tarballMirrorPath)); + yield (_fs || _load_fs()).copy(tarballCachePath, tarballMirrorPath, _this.reporter); + } + })(); + } - loginAsPublic: 'Logging in as public', - incorrectCredentials: 'Incorrect username or password.', - clearedCredentials: 'Cleared login credentials.', + getTarballMirrorPath() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$withCommit = _ref.withCommit; - publishFail: "Couldn't publish package.", - publishPrivate: 'Package marked as private, not publishing.', - published: 'Published.', - publishing: 'Publishing', + let withCommit = _ref$withCommit === undefined ? true : _ref$withCommit; - infoFail: 'Received invalid response from npm.', - malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.', + var _url$parse = url.parse(this.reference); - cantRequestOffline: "Can't make a request in offline mode ($0)", - requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files', - requestError: 'Request $0 returned a $1', - requestFailed: 'Request failed $0', - tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)', - fetchBadHash: "Hashes don't match. Expected $1 but got $2", - fetchBadHashWithPath: "Hashes don't match when extracting file $0. Expected $1 but got $2", - fetchErrorCorrupt: '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\n\n rm -rf $1\n yarn install', - errorDecompressingTarball: '$0. Error decompressing $1, it appears to be corrupt.', - updateInstalling: 'Installing $0...', - hostedGitResolveError: 'Error connecting to repository. Please, check the url.', + const pathname = _url$parse.pathname; - unknownFetcherFor: 'Unknown fetcher for $0', - refusingDownloadGitWithoutCommit: 'Refusing to download the git repo $0 over plain git without a commit hash', - refusingDownloadHTTPWithoutCommit: 'Refusing to download the git repo $0 over HTTP without a commit hash', - refusingDownloadHTTPSWithoutCommit: 'Refusing to download the git repo $0 over HTTPS without a commit hash - possible certificate error?', + if (pathname == null) { + return null; + } - packageInstalledWithBinaries: 'Installed $0 with binaries:', - packageHasBinaries: '$0 has binaries:', - packageHasNoBinaries: '$0 has no binaries', + const hash = this.hash; - couldBeDeduped: '$0 could be deduped from $1 to $2', - lockfileNotContainPattern: 'Lockfile does not contain pattern: $0', - integrityCheckFailed: 'Integrity check failed', - noIntegrityFile: "Couldn't find an integrity file", - integrityFailedExpectedIsNotAJSON: 'Integrity check: integrity file is not a json', - integrityCheckLinkedModulesDontMatch: "Integrity check: Linked modules don't match", - integrityFlagsDontMatch: "Integrity check: Flags don't match", - integrityLockfilesDontMatch: "Integrity check: Lock files don't match", - integrityFailedFilesMissing: 'Integrity check: Files are missing', - packageNotInstalled: '$0 not installed', - optionalDepNotInstalled: 'Optional dependency $0 not installed', - packageWrongVersion: '$0 is wrong version: expected $1, got $2', - packageDontSatisfy: "$0 doesn't satisfy found match of $1", + let packageFilename = withCommit && hash ? `${path.basename(pathname)}-${hash}` : `${path.basename(pathname)}`; - lockfileExists: 'Lockfile already exists, not importing.', - skippingImport: 'Skipping import of $0 for $1', - importFailed: 'Import of $0 for $1 failed, resolving normally.', - importResolveFailed: 'Import of $0 failed starting in $1', - importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3', - packageContainsYarnAsGlobal: 'Installing Yarn via Yarn will result in you having two separate versions of Yarn installed at the same time, which is not recommended. To update Yarn please follow https://yarnpkg.com/en/docs/install .', + if (packageFilename.startsWith(':')) { + packageFilename = packageFilename.substr(1); + } - scopeNotValid: 'The specified scope is not valid.' -}; + return this.config.getOfflineMirrorPath(packageFilename); + } -exports.default = messages; + getTarballCachePath() { + return path.join(this.dest, (_constants || _load_constants()).TARBALL_FILENAME); + } -/***/ }), -/* 374 */ -/***/ (function(module, exports, __webpack_require__) { + *getLocalPaths(override) { + if (override) { + yield path.resolve(this.config.cwd, override); + } + yield this.getTarballMirrorPath(); + yield this.getTarballMirrorPath({ + withCommit: false + }); + yield this.getTarballCachePath(); + } -"use strict"; + fetchFromLocal(override) { + var _this2 = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + var _ref2 = yield (_fs || _load_fs()).readFirstAvailableStream(_this2.getLocalPaths(override)); -Object.defineProperty(exports, "__esModule", { - value: true -}); + const stream = _ref2.stream, + triedPaths = _ref2.triedPaths; -var _asyncToGenerator2; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + return new Promise(function (resolve, reject) { + if (!stream) { + reject(new (_errors || _load_errors()).MessageError(_this2.reporter.lang('tarballNotInNetworkOrCache', _this2.reference, triedPaths))); + return; + } + invariant(stream, 'cachedStream should be available at this point'); + // $FlowFixMe - This is available https://nodejs.org/api/fs.html#fs_readstream_path + const tarballPath = stream.path; -var _format; + const untarStream = _this2._createUntarStream(_this2.dest); -function _load_format() { - return _format = __webpack_require__(202); -} + const hashStream = new (_crypto || _load_crypto()).HashStream(); + stream.pipe(hashStream).pipe(untarStream).on('finish', function () { + const expectHash = _this2.hash; + invariant(expectHash, 'Commit hash required'); -var _index; + const actualHash = hashStream.getHash(); -function _load_index() { - return _index = _interopRequireWildcard(__webpack_require__(203)); -} + // This condition is disabled because "expectHash" actually is the commit hash + // This is a design issue that we'll need to fix (https://github.com/yarnpkg/yarn/pull/3449) + if (true) { + resolve({ + hash: expectHash + }); + } else { + reject(new (_errors || _load_errors()).SecurityError(_this2.config.reporter.lang('fetchBadHashWithPath', _this2.packageName, _this2.remote.reference, expectHash, actualHash))); + } + }).on('error', function (err) { + reject(new (_errors || _load_errors()).MessageError(this.reporter.lang('fetchErrorCorrupt', err.message, tarballPath))); + }); + }); + })(); + } -var _isCi; + hasPrepareScript(git) { + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const manifestFile = yield git.getFile('package.json'); -function _load_isCi() { - return _isCi = _interopRequireDefault(__webpack_require__(153)); -} + if (manifestFile) { + const scripts = JSON.parse(manifestFile).scripts; + const hasPrepareScript = Boolean(scripts && scripts.prepare); + return hasPrepareScript; + } -var _baseReporter; + return false; + })(); + } -function _load_baseReporter() { - return _baseReporter = _interopRequireDefault(__webpack_require__(51)); -} + fetchFromExternal() { + var _this3 = this; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const hash = _this3.hash; + invariant(hash, 'Commit hash required'); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + const gitUrl = (_git || _load_git()).default.npmUrlToGitUrl(_this3.reference); + const git = new (_git || _load_git()).default(_this3.config, gitUrl, hash); + yield git.init(); -class NoopReporter extends (_baseReporter || _load_baseReporter()).default { - lang(key) { - return 'do nothing'; - } - verbose(msg) {} - verboseInspect(val) {} - initPeakMemoryCounter() {} - checkPeakMemory() {} - close() {} - getTotalTime() { - return 0; - } - list(key, items, hints) {} - tree(key, obj) {} - step(current, total, message, emoji) {} - error(message) {} - info(message) {} - warn(message) {} - success(message) {} - log(message) {} - command(command) {} - inspect(value) {} - header(command, pkg) {} - footer(showPeakMemory) {} - table(head, body) {} + if (yield _this3.hasPrepareScript(git)) { + yield _this3.fetchFromInstallAndPack(git); + } else { + yield _this3.fetchFromGitArchive(git); + } - activity() { - return { - tick(name) {}, - end() {} - }; + return { + hash + }; + })(); } - activitySet(total, workers) { - return { - spinners: Array(workers).fill({ - clear() {}, - setPrefix() {}, - tick() {}, - end() {} - }), - end() {} - }; + fetchFromInstallAndPack(git) { + var _this4 = this; + + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const prepareDirectory = _this4.config.getTemp(`${(_crypto || _load_crypto()).hash(git.gitUrl.repository)}.${git.hash}.prepare`); + yield (_fs || _load_fs()).unlink(prepareDirectory); + + yield git.clone(prepareDirectory); + + var _ref3 = yield Promise.all([(_config || _load_config()).default.create({ + binLinks: true, + cwd: prepareDirectory, + disablePrepublish: true + }, _this4.reporter), (_lockfile || _load_lockfile()).default.fromDirectory(prepareDirectory, _this4.reporter)]), + _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2); + + const prepareConfig = _ref4[0], + prepareLockFile = _ref4[1]; + + yield (0, (_install || _load_install()).install)(prepareConfig, _this4.reporter, {}, prepareLockFile); + + const tarballMirrorPath = _this4.getTarballMirrorPath(); + const tarballCachePath = _this4.getTarballCachePath(); + + if (tarballMirrorPath) { + yield _this4._packToTarball(prepareConfig, tarballMirrorPath); + } + if (tarballCachePath) { + yield _this4._packToTarball(prepareConfig, tarballCachePath); + } + + yield _this4._packToDirectory(prepareConfig, _this4.dest); + + yield (_fs || _load_fs()).unlink(prepareDirectory); + })(); } - question(question) { - let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + _packToTarball(config, path) { + var _this5 = this; - return Promise.reject(new Error('Not implemented')); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const tarballStream = yield _this5._createTarballStream(config); + yield new Promise(function (resolve, reject) { + const writeStream = fs.createWriteStream(path); + tarballStream.on('error', reject); + writeStream.on('error', reject); + writeStream.on('end', resolve); + writeStream.on('open', function () { + tarballStream.pipe(writeStream); + }); + writeStream.once('finish', resolve); + }); + })(); } - questionAffirm(question) { - var _this = this; + _packToDirectory(config, dest) { + var _this6 = this; return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - yield _this.question(question); - return false; + const tarballStream = yield _this6._createTarballStream(config); + yield new Promise(function (resolve, reject) { + const untarStream = _this6._createUntarStream(dest); + tarballStream.on('error', reject); + untarStream.on('error', reject); + untarStream.on('end', resolve); + untarStream.once('finish', resolve); + tarballStream.pipe(untarStream); + }); })(); } - select(header, question, options) { - return Promise.reject(new Error('Not implemented')); + _createTarballStream(config) { + let savedPackedHeader = false; + return (0, (_pack || _load_pack()).packTarball)(config, { + mapHeader(header) { + if (!savedPackedHeader) { + savedPackedHeader = true; + header.pax = header.pax || {}; + // add a custom data on the first header + // in order to distinguish a tar from "git archive" and a tar from "pack" command + header.pax.packed = PACKED_FLAG; + } + return header; + } + }); } - progress(total) { - return function () {}; + _createUntarStream(dest) { + const PREFIX = 'package/'; + let isPackedTarball = undefined; + return tarFs.extract(dest, { + dmode: 0o555, // all dirs should be readable + fmode: 0o444, // all files should be readable + chown: false, // don't chown. just leave as it is + map: header => { + if (isPackedTarball === undefined) { + isPackedTarball = header.pax && header.pax.packed === PACKED_FLAG; + } + if (isPackedTarball) { + header.name = header.name.substr(PREFIX.length); + } + } + }); } - disableProgress() { - this.noProgress = true; - } + fetchFromGitArchive(git) { + var _this7 = this; - prompt(message, choices) { - let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield git.clone(_this7.dest); + const tarballMirrorPath = _this7.getTarballMirrorPath(); + const tarballCachePath = _this7.getTarballCachePath(); - return Promise.reject(new Error('Not implemented')); + if (tarballMirrorPath) { + yield git.archive(tarballMirrorPath); + } + + if (tarballCachePath) { + yield git.archive(tarballCachePath); + } + })(); + } + + _fetch() { + return this.fetchFromLocal().catch(err => this.fetchFromExternal()); } } -exports.default = NoopReporter; -/* eslint no-unused-vars: 0 */ +exports.default = GitFetcher; /***/ }), -/* 375 */ +/* 412 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80896,64 +84985,48 @@ exports.default = NoopReporter; Object.defineProperty(exports, "__esModule", { value: true }); +exports.workspace = exports.tarball = exports.git = exports.copy = exports.base = undefined; -var _packageRequest; +var _baseFetcher; -function _load_packageRequest() { - return _packageRequest = _interopRequireDefault(__webpack_require__(28)); +function _load_baseFetcher() { + return _baseFetcher = _interopRequireDefault(__webpack_require__(122)); } -var _baseResolver; +var _copyFetcher; -function _load_baseResolver() { - return _baseResolver = _interopRequireDefault(__webpack_require__(83)); +function _load_copyFetcher() { + return _copyFetcher = _interopRequireDefault(__webpack_require__(410)); } -var _workspaceLayout; +var _gitFetcher; -function _load_workspaceLayout() { - return _workspaceLayout = _interopRequireDefault(__webpack_require__(66)); +function _load_gitFetcher() { + return _gitFetcher = _interopRequireDefault(__webpack_require__(411)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const invariant = __webpack_require__(5); - -class WorkspaceResolver extends (_baseResolver || _load_baseResolver()).default { - static isWorkspace(pattern, workspaceLayout) { - return !!workspaceLayout && !!workspaceLayout.getManifestByPattern(pattern); - } - - constructor(request, fragment, workspaceLayout) { - super(request, fragment); - this.workspaceLayout = workspaceLayout; - } +var _tarballFetcher; - resolve() { - const workspace = this.workspaceLayout.getManifestByPattern(this.request.pattern); - invariant(workspace, 'expected workspace'); - const manifest = workspace.manifest, - loc = workspace.loc; +function _load_tarballFetcher() { + return _tarballFetcher = _interopRequireDefault(__webpack_require__(261)); +} - const registry = manifest._registry; - invariant(registry, 'expected reference'); +var _workspaceFetcher; - manifest._remote = { - type: 'workspace', - registry, - hash: '', - reference: loc - }; +function _load_workspaceFetcher() { + return _workspaceFetcher = _interopRequireDefault(__webpack_require__(413)); +} - manifest._uid = manifest.version; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return Promise.resolve(manifest); - } -} -exports.default = WorkspaceResolver; +exports.base = (_baseFetcher || _load_baseFetcher()).default; +exports.copy = (_copyFetcher || _load_copyFetcher()).default; +exports.git = (_gitFetcher || _load_gitFetcher()).default; +exports.tarball = (_tarballFetcher || _load_tarballFetcher()).default; +exports.workspace = (_workspaceFetcher || _load_workspaceFetcher()).default; /***/ }), -/* 376 */ +/* 413 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -80963,42 +85036,54 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _hostedGitResolver; +var _extends2; -function _load_hostedGitResolver() { - return _hostedGitResolver = _interopRequireDefault(__webpack_require__(52)); +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _asyncToGenerator2; -class BitbucketResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default { +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - static getTarballUrl(parts, hash) { - return `https://${this.hostname}/${parts.user}/${parts.repo}/get/${hash}.tar.gz`; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - static getGitHTTPBaseUrl(parts) { - return `https://${this.hostname}/${parts.user}/${parts.repo}`; +class WorkspaceFetcher { + constructor(dest, remote, config) { + this.config = config; + this.dest = dest; + this.registry = remote.registry; + this.workspaceDir = remote.reference; } - static getGitHTTPUrl(parts) { - return `${BitbucketResolver.getGitHTTPBaseUrl(parts)}.git`; + setupMirrorFromCache() { + return Promise.resolve(); } - static getGitSSHUrl(parts) { - return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; - } + fetch() { + var _this = this; - static getHTTPFileUrl(parts, filename, commit) { - return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const pkg = yield _this.config.readManifest(_this.workspaceDir, _this.registry); + + return { + resolved: null, + hash: '', + cached: false, + dest: _this.dest, + package: (0, (_extends2 || _load_extends()).default)({}, pkg, { + _uid: pkg.version + }) + }; + })(); } } -exports.default = BitbucketResolver; -BitbucketResolver.hostname = 'bitbucket.org'; -BitbucketResolver.protocol = 'bitbucket'; +exports.default = WorkspaceFetcher; /***/ }), -/* 377 */ +/* 414 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81007,57 +85092,31 @@ BitbucketResolver.protocol = 'bitbucket'; Object.defineProperty(exports, "__esModule", { value: true }); +const semver = __webpack_require__(22); -var _hostedGitResolver; - -function _load_hostedGitResolver() { - return _hostedGitResolver = _interopRequireDefault(__webpack_require__(52)); -} - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -class GitHubResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default { - - static isVersion(pattern) { - // github proto - if (pattern.startsWith('github:')) { - return true; - } - - // github shorthand - if (/^[^:@%/\s.-][^:@%/\s]*[/][^:@\s/%]+(?:#.*)?$/.test(pattern)) { - return true; - } - - return false; - } - - static getTarballUrl(parts, hash) { - return `https://codeload.${this.hostname}/${parts.user}/${parts.repo}/tar.gz/${hash}`; - } - - static getGitSSHUrl(parts) { - return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; - } - - static getGitHTTPBaseUrl(parts) { - return `https://${this.hostname}/${parts.user}/${parts.repo}`; - } +// This isn't really a "proper" constraint resolver. We just return the highest semver +// version in the versions passed that satisfies the input range. This vastly reduces +// the complexity and is very efficient for package resolution. - static getGitHTTPUrl(parts) { - return `${GitHubResolver.getGitHTTPBaseUrl(parts)}.git`; +class PackageConstraintResolver { + constructor(config, reporter) { + this.reporter = reporter; + this.config = config; } - static getHTTPFileUrl(parts, filename, commit) { - return `https://raw.githubusercontent.com/${parts.user}/${parts.repo}/${commit}/${filename}`; + reduce(versions, range) { + if (range === 'latest') { + // Usually versions are already ordered and the last one is the latest + return Promise.resolve(versions[versions.length - 1]); + } else { + return Promise.resolve(semver.maxSatisfying(versions, range, this.config.looseSemver)); + } } } -exports.default = GitHubResolver; -GitHubResolver.protocol = 'github'; -GitHubResolver.hostname = 'github.com'; +exports.default = PackageConstraintResolver; /***/ }), -/* 378 */ +/* 415 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81066,472 +85125,666 @@ GitHubResolver.hostname = 'github.com'; Object.defineProperty(exports, "__esModule", { value: true }); +exports.HoistManifest = undefined; -var _hostedGitResolver; +var _slicedToArray2; -function _load_hostedGitResolver() { - return _hostedGitResolver = _interopRequireDefault(__webpack_require__(52)); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} + +var _misc; + +function _load_misc() { + return _misc = __webpack_require__(10); } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -class GitLabResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default { +const invariant = __webpack_require__(7); +const path = __webpack_require__(0); - static getTarballUrl(parts, hash) { - return `https://${this.hostname}/${parts.user}/${parts.repo}/repository/archive.tar.gz?ref=${hash}`; +let historyCounter = 0; + +class HoistManifest { + constructor(key, parts, pkg, loc, isDirectRequire, isRequired, isIncompatible) { + this.isDirectRequire = isDirectRequire; + this.isRequired = isRequired; + this.isIncompatible = isIncompatible; + + this.loc = loc; + this.pkg = pkg; + this.key = key; + this.parts = parts; + this.originalKey = key; + this.previousKeys = []; + + this.history = []; + this.addHistory(`Start position = ${key}`); } - static getGitHTTPBaseUrl(parts) { - return `https://${this.hostname}/${parts.user}/${parts.repo}`; + addHistory(msg) { + this.history.push(`${++historyCounter}: ${msg}`); } +} - static getGitHTTPUrl(parts) { - return `${GitLabResolver.getGitHTTPBaseUrl(parts)}.git`; +exports.HoistManifest = HoistManifest; +class PackageHoister { + constructor(config, resolver) { + var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + let ignoreOptional = _ref.ignoreOptional; + + this.resolver = resolver; + this.config = config; + + this.ignoreOptional = ignoreOptional; + + this.taintedKeys = new Map(); + this.levelQueue = []; + this.tree = new Map(); } - static getGitSSHUrl(parts) { - return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; + /** + * Taint this key and prevent any modules from being hoisted to it. + */ + + taintKey(key, info) { + const existingTaint = this.taintedKeys.get(key); + if (existingTaint && existingTaint.loc !== info.loc) { + return false; + } else { + this.taintedKeys.set(key, info); + return true; + } } - static getHTTPFileUrl(parts, filename, commit) { - return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`; + /** + * Implode an array of ancestry parts into a key. + */ + + implodeKey(parts) { + return parts.join('#'); } -} -exports.default = GitLabResolver; -GitLabResolver.hostname = 'gitlab.com'; -GitLabResolver.protocol = 'gitlab'; -/***/ }), -/* 379 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Seed the hoister with patterns taken from the included resolver. + */ -"use strict"; + seed(patterns) { + this.prepass(patterns); + for (const pattern of this.resolver.dedupePatterns(patterns)) { + this._seed(pattern, { isDirectRequire: true }); + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + while (true) { + let queue = this.levelQueue; + if (!queue.length) { + this._propagateRequired(); + return; + } -var _asyncToGenerator2; + this.levelQueue = []; -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + // sort queue to get determinism between runs + queue = queue.sort((_ref2, _ref3) => { + var _ref5 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 1); -var _exoticResolver; + let aPattern = _ref5[0]; -function _load_exoticResolver() { - return _exoticResolver = _interopRequireDefault(__webpack_require__(44)); -} + var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 1); -var _misc; + let bPattern = _ref4[0]; -function _load_misc() { - return _misc = _interopRequireWildcard(__webpack_require__(10)); -} + return (0, (_misc || _load_misc()).sortAlpha)(aPattern, bPattern); + }); -var _fs; + // sort the queue again to hoist packages without peer dependencies first + let sortedQueue = []; + const availableSet = new Set(); -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + let hasChanged = true; + while (queue.length > 0 && hasChanged) { + hasChanged = false; -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + for (let t = 0; t < queue.length; ++t) { + const pattern = queue[t][0]; + const pkg = this.resolver.getStrictResolvedPattern(pattern); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + const peerDependencies = Object.keys(pkg.peerDependencies || {}); + const areDependenciesFulfilled = peerDependencies.every(peerDependency => availableSet.has(peerDependency)); -const path = __webpack_require__(1); + if (areDependenciesFulfilled) { + // Move the package inside our sorted queue + sortedQueue.push(queue[t]); + queue.splice(t--, 1); -class LinkResolver extends (_exoticResolver || _load_exoticResolver()).default { - constructor(request, fragment) { - super(request, fragment); - this.loc = (_misc || _load_misc()).removePrefix(fragment, 'link:'); - } + // Add it to our set, so that we know it is available + availableSet.add(pattern); - resolve() { - var _this = this; + // Schedule a next pass, in case other packages had peer dependencies on this one + hasChanged = true; + } + } + } - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - let loc = _this.loc; - if (!path.isAbsolute(loc)) { - loc = path.join(_this.config.cwd, loc); + // We might end up with some packages left in the queue, that have not been sorted. We reach this codepath if two + // packages have a cyclic dependency, or if the peer dependency is provided by a parent package. In these case, + // nothing we can do, so we just add all of these packages to the end of the sorted queue. + sortedQueue = sortedQueue.concat(queue); + + for (const _ref6 of sortedQueue) { + var _ref7 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref6, 2); + + const pattern = _ref7[0]; + const parent = _ref7[1]; + + const info = this._seed(pattern, { isDirectRequire: false, parent }); + if (info) { + this.hoist(info); + } } + } + } - const name = path.basename(loc); - const registry = 'npm'; + /** + * Seed the hoister with a specific pattern. + */ - const manifest = !(yield (_fs || _load_fs()).exists(loc)) ? { _uid: '', name, version: '0.0.0', _registry: registry } : yield _this.config.readManifest(loc, _this.registry); + _seed(pattern, _ref8) { + let isDirectRequire = _ref8.isDirectRequire, + parent = _ref8.parent; - manifest._remote = { - type: 'link', - registry, - hash: null, - reference: loc - }; + // + const pkg = this.resolver.getStrictResolvedPattern(pattern); + const ref = pkg._reference; + invariant(ref, 'expected reference'); - manifest._uid = manifest.version; + // + let parentParts = []; - return manifest; - })(); - } -} -exports.default = LinkResolver; -LinkResolver.protocol = 'link'; + const isIncompatible = ref.incompatible; + const isMarkedAsOptional = ref.optional && this.ignoreOptional; -/***/ }), -/* 380 */ -/***/ (function(module, exports, __webpack_require__) { + let isRequired = isDirectRequire && !ref.ignore && !isIncompatible && !isMarkedAsOptional; -"use strict"; + if (parent) { + if (!this.tree.get(parent.key)) { + return null; + } + // non ignored dependencies inherit parent's ignored status + // parent may transition from ignored to non ignored when hoisted if it is used in another non ignored branch + if (!isDirectRequire && !isIncompatible && parent.isRequired && !isMarkedAsOptional) { + isRequired = true; + } + parentParts = parent.parts; + } + // + const loc = this.config.generateHardModulePath(ref); + const parts = parentParts.concat(pkg.name); + const key = this.implodeKey(parts); + const info = new HoistManifest(key, parts, pkg, loc, isDirectRequire, isRequired, isIncompatible); + // + this.tree.set(key, info); + this.taintKey(key, info); -Object.defineProperty(exports, "__esModule", { - value: true -}); + // + for (const depPattern of ref.dependencies) { + this.levelQueue.push([depPattern, info]); + } -var _errors; + return info; + } -function _load_errors() { - return _errors = __webpack_require__(3); -} + /** + * Propagate inherited ignore statuses from non-ignored to ignored packages + */ -var _exoticResolver; + _propagateRequired() { + // + const toVisit = []; -function _load_exoticResolver() { - return _exoticResolver = _interopRequireDefault(__webpack_require__(44)); -} + // enumerate all non-ignored packages + for (const entry of this.tree.entries()) { + if (entry[1].isRequired) { + toVisit.push(entry[1]); + } + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + // visit them + while (toVisit.length) { + const info = toVisit.shift(); + const ref = info.pkg._reference; + invariant(ref, 'expected reference'); -class RegistryResolver extends (_exoticResolver || _load_exoticResolver()).default { - constructor(request, fragment) { - super(request, fragment); + for (const depPattern of ref.dependencies) { + const depinfo = this._lookupDependency(info, depPattern); - const match = fragment.match(/^(\S+):(.*?)(@(.*?)|)$/); - if (match) { - this.range = match[4] || 'latest'; - this.name = match[2]; - } else { - throw new (_errors || _load_errors()).MessageError(this.reporter.lang('invalidFragment', fragment)); + if (!depinfo) { + continue; + } + + const isMarkedAsOptional = !depinfo.pkg._reference || this.ignoreOptional; + if (!depinfo.isRequired && !depinfo.isIncompatible && !isMarkedAsOptional) { + depinfo.isRequired = true; + depinfo.addHistory(`Mark as non-ignored because of usage by ${info.key}`); + toVisit.push(depinfo); + } + } } + } - // $FlowFixMe - this.registry = this.constructor.protocol; + /** + * Looks up the package a dependency resolves to + */ + + _lookupDependency(info, depPattern) { + // + const pkg = this.resolver.getStrictResolvedPattern(depPattern); + const ref = pkg._reference; + invariant(ref, 'expected reference'); + + // + for (let i = info.parts.length; i >= 0; i--) { + const checkParts = info.parts.slice(0, i).concat(pkg.name); + const checkKey = this.implodeKey(checkParts); + const existing = this.tree.get(checkKey); + if (existing) { + return existing; + } + } + + return null; } - resolve() { - return this.fork(this.constructor.factory, false, this.name, this.range); - } -} -exports.default = RegistryResolver; + /** + * Find the highest position we can hoist this module to. + */ + + getNewParts(key, info, parts) { + let stepUp = false; + + const fullKey = this.implodeKey(parts); + const stack = []; // stack of removed parts + const name = parts.pop(); + + for (let i = parts.length - 1; i >= 0; i--) { + const checkParts = parts.slice(0, i).concat(name); + const checkKey = this.implodeKey(checkParts); + info.addHistory(`Looked at ${checkKey} for a match`); + + const existing = this.tree.get(checkKey); + + if (existing) { + if (existing.loc === info.loc) { + // switch to non ignored if earlier deduped version was ignored (must be compatible) + if (!existing.isRequired && info.isRequired) { + existing.addHistory(`Deduped ${fullKey} to this item, marking as required`); + existing.isRequired = true; + } else { + existing.addHistory(`Deduped ${fullKey} to this item`); + } + + return { parts: checkParts, duplicate: true }; + } else { + // everything above will be shadowed and this is a conflict + info.addHistory(`Found a collision at ${checkKey}`); + break; + } + } -/***/ }), -/* 381 */ -/***/ (function(module, exports, __webpack_require__) { + const existingTaint = this.taintedKeys.get(checkKey); + if (existingTaint && existingTaint.loc !== info.loc) { + info.addHistory(`Broken by ${checkKey}`); + break; + } + } -"use strict"; + const peerDependencies = Object.keys(info.pkg.peerDependencies || {}); + // remove redundant parts that wont collide + hoistLoop: while (parts.length) { + // we must not hoist a package higher than its peer dependencies + for (const peerDependency of peerDependencies) { + const checkParts = parts.concat(peerDependency); + const checkKey = this.implodeKey(checkParts); + info.addHistory(`Looked at ${checkKey} for a peer dependency match`); -Object.defineProperty(exports, "__esModule", { - value: true -}); + const existing = this.tree.get(checkKey); -var _asyncToGenerator2; + if (existing) { + info.addHistory(`Found a peer dependency requirement at ${checkKey}`); + break hoistLoop; + } + } -function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} + const checkParts = parts.concat(name); + const checkKey = this.implodeKey(checkParts); -var _tarballFetcher; + // + const existing = this.tree.get(checkKey); + if (existing) { + stepUp = true; + break; + } -function _load_tarballFetcher() { - return _tarballFetcher = _interopRequireDefault(__webpack_require__(198)); -} + // check if we're trying to hoist ourselves to a previously unflattened module key, + // this will result in a conflict and we'll need to move ourselves up + if (key !== checkKey && this.taintedKeys.has(checkKey)) { + stepUp = true; + break; + } -var _exoticResolver; + // + stack.push(parts.pop()); + } -function _load_exoticResolver() { - return _exoticResolver = _interopRequireDefault(__webpack_require__(44)); -} + // + parts.push(name); -var _gitResolver; + // + const isValidPosition = parts => { + const key = this.implodeKey(parts); + const existing = this.tree.get(key); + if (existing && existing.loc === info.loc) { + return true; + } -function _load_gitResolver() { - return _gitResolver = _interopRequireDefault(__webpack_require__(61)); -} + // ensure there's no taint or the taint is us + const existingTaint = this.taintedKeys.get(key); + if (existingTaint && existingTaint.loc !== info.loc) { + return false; + } -var _misc; + return true; + }; -function _load_misc() { - return _misc = __webpack_require__(10); -} + // we need to special case when we attempt to hoist to the top level as the `existing` logic + // wont be hit in the above `while` loop and we could conflict + if (!isValidPosition(parts)) { + stepUp = true; + } -var _guessName; + // sometimes we need to step up to a parent module to install ourselves + while (stepUp && stack.length) { + info.addHistory(`Stepping up from ${this.implodeKey(parts)}`); -function _load_guessName() { - return _guessName = _interopRequireDefault(__webpack_require__(128)); -} + parts.pop(); // remove `name` + parts.push(stack.pop(), name); -var _version; + if (isValidPosition(parts)) { + info.addHistory(`Found valid position ${this.implodeKey(parts)}`); + stepUp = false; + } + } -function _load_version() { - return _version = _interopRequireWildcard(__webpack_require__(131)); -} + return { parts, duplicate: false }; + } -var _crypto; + /** + * Hoist all seeded patterns to their highest positions. + */ -function _load_crypto() { - return _crypto = _interopRequireWildcard(__webpack_require__(85)); -} + hoist(info) { + const oldKey = info.key, + rawParts = info.parts; -var _fs; + // remove this item from the `tree` map so we can ignore it -function _load_fs() { - return _fs = _interopRequireWildcard(__webpack_require__(4)); -} + this.tree.delete(oldKey); -function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + var _getNewParts = this.getNewParts(oldKey, info, rawParts.slice()); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + const parts = _getNewParts.parts, + duplicate = _getNewParts.duplicate; -const invariant = __webpack_require__(5); + const newKey = this.implodeKey(parts); + if (duplicate) { + info.addHistory(`Satisfied from above by ${newKey}`); + this.declareRename(info, rawParts, parts); + return; + } -class TarballResolver extends (_exoticResolver || _load_exoticResolver()).default { - constructor(request, fragment) { - super(request, fragment); + // update to the new key + if (oldKey === newKey) { + info.addHistory("Didn't hoist - conflicts above"); + this.setKey(info, oldKey, rawParts); + return; + } - var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment); + // + this.declareRename(info, rawParts, parts); + this.setKey(info, newKey, parts); + } - const hash = _versionUtil$explodeH.hash, - url = _versionUtil$explodeH.url; + /** + * Declare that a module has been hoisted and update our internal references. + */ - this.hash = hash; - this.url = url; + declareRename(info, oldParts, newParts) { + // go down the tree from our new position reserving our name + this.taintParents(info, oldParts.slice(0, -1), newParts.length - 1); } - static isVersion(pattern) { - // we can sometimes match git urls which we don't want - if ((_gitResolver || _load_gitResolver()).default.isVersion(pattern)) { - return false; - } + /** + * Crawl upwards through a list of ancestry parts and taint a package name. + */ - // full http url - if (pattern.startsWith('http://') || pattern.startsWith('https://')) { - return true; - } + taintParents(info, processParts, start) { + for (let i = start; i < processParts.length; i++) { + const parts = processParts.slice(0, i).concat(info.pkg.name); + const key = this.implodeKey(parts); - // local file reference - ignore patterns with names - if (pattern.indexOf('@') < 0) { - if (pattern.endsWith('.tgz') || pattern.endsWith('.tar.gz')) { - return true; + if (this.taintKey(key, info)) { + info.addHistory(`Tainted ${key} to prevent collisions`); } } - - return false; } - resolve() { - var _this = this; + /** + * Update the key of a module and update our references. + */ - return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { - const shrunk = _this.request.getLocked('tarball'); - if (shrunk) { - return shrunk; - } + setKey(info, newKey, parts) { + const oldKey = info.key; - const url = (0, (_misc || _load_misc()).removePrefix)(_this.url, 'file:'); - let hash = _this.hash, - registry = _this.registry; + info.key = newKey; + info.parts = parts; + this.tree.set(newKey, info); - let pkgJson; + if (oldKey === newKey) { + return; + } - // generate temp directory - const dest = _this.config.getTemp((_crypto || _load_crypto()).hash(url)); + info.previousKeys.push(newKey); + info.addHistory(`New position = ${newKey}`); + } - if (yield _this.config.isValidModuleDest(dest)) { - var _ref = yield _this.config.readPackageMetadata(dest); - // load from local cache + /** + * Perform a prepass and if there's multiple versions of the same package, hoist the one with + * the most dependents to the top. + */ + prepass(patterns) { + patterns = this.resolver.dedupePatterns(patterns).sort(); - pkgJson = _ref.package; - hash = _ref.hash; - registry = _ref.registry; - } else { - // delete if invalid - yield (_fs || _load_fs()).unlink(dest); + const visited = new Map(); - const fetcher = new (_tarballFetcher || _load_tarballFetcher()).default(dest, { - type: 'tarball', - reference: url, - registry, - hash - }, _this.config); + const occurences = {}; - // fetch file and get it's hash - const fetched = yield fetcher.fetch({ - name: (0, (_guessName || _load_guessName()).default)(url), - version: '0.0.0', - _registry: 'npm' - }); - pkgJson = fetched.package; - hash = fetched.hash; + // visitor to be used inside add() to mark occurences of packages + const visitAdd = (pkg, ancestry, pattern) => { + const versions = occurences[pkg.name] = occurences[pkg.name] || {}; + const version = versions[pkg.version] = versions[pkg.version] || { + occurences: new Set(), + pattern + }; - registry = pkgJson._registry; - invariant(registry, 'expected registry'); + if (ancestry.length) { + version.occurences.add(ancestry[ancestry.length - 1]); } + }; - // use the commit/tarball hash as the uid as we can't rely on the version as it's not - // in the registry - pkgJson._uid = hash; + // add an occuring package to the above data structure + const add = (pattern, ancestry, ancestryPatterns) => { + const pkg = this.resolver.getStrictResolvedPattern(pattern); + if (ancestry.indexOf(pkg) >= 0) { + // prevent recursive dependencies + return; + } - // set remote so it can be "fetched" - pkgJson._remote = { - type: 'copy', - resolved: `${url}#${hash}`, - hash, - registry, - reference: dest - }; + let visitedPattern = visited.get(pattern); - return pkgJson; - })(); - } -} -exports.default = TarballResolver; + if (visitedPattern) { + // if a package has been visited before, simply increment occurrences of packages + // like last time this package was visited + visitedPattern.forEach(visitPkg => { + visitAdd(visitPkg.pkg, visitPkg.ancestry, visitPkg.pattern); + }); -/***/ }), -/* 382 */ -/***/ (function(module, exports, __webpack_require__) { + visitAdd(pkg, ancestry, pattern); -"use strict"; + return; + } + const ref = pkg._reference; + invariant(ref, 'expected reference'); -Object.defineProperty(exports, "__esModule", { - value: true -}); + visitAdd(pkg, ancestry, pattern); -var _baseResolver; + for (const depPattern of ref.dependencies) { + const depAncestry = ancestry.concat(pkg); + const depAncestryPatterns = ancestryPatterns.concat(depPattern); + add(depPattern, depAncestry, depAncestryPatterns); + } -function _load_baseResolver() { - return _baseResolver = _interopRequireDefault(__webpack_require__(83)); -} + visitedPattern = visited.get(pattern) || []; + visited.set(pattern, visitedPattern); + visitedPattern.push({ pkg, ancestry, pattern }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + ancestryPatterns.forEach(ancestryPattern => { + const visitedAncestryPattern = visited.get(ancestryPattern); + if (visitedAncestryPattern) { + visitedAncestryPattern.push({ pkg, ancestry, pattern }); + } + }); + }; -class RegistryResolver extends (_baseResolver || _load_baseResolver()).default { - constructor(request, name, range) { - super(request, `${name}@${range}`); - this.name = name; - this.range = range; + // get a list of root package names since we can't hoist other dependencies to these spots! + const rootPackageNames = new Set(); + for (const pattern of patterns) { + const pkg = this.resolver.getStrictResolvedPattern(pattern); + rootPackageNames.add(pkg.name); + add(pattern, [], []); + } - this.registryConfig = request.config.registries[this.constructor.registry].config; - } + for (const packageName of Object.keys(occurences).sort()) { + const versionOccurences = occurences[packageName]; + const versions = Object.keys(versionOccurences); -} -exports.default = RegistryResolver; + if (versions.length === 1) { + // only one package type so we'll hoist this to the top anyway + continue; + } -/***/ }), -/* 383 */ -/***/ (function(module, exports, __webpack_require__) { + if (this.tree.get(packageName)) { + // a transitive dependency of a previously hoisted dependency exists + continue; + } -"use strict"; + if (rootPackageNames.has(packageName)) { + // can't replace top level packages + continue; + } + let mostOccurenceCount; + let mostOccurencePattern; + for (const version of Object.keys(versionOccurences).sort()) { + var _versionOccurences$ve = versionOccurences[version]; + const occurences = _versionOccurences$ve.occurences, + pattern = _versionOccurences$ve.pattern; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = envReplace; -const ENV_EXPR = /(\\*)\$\{([^}]+)\}/g; + const occurenceCount = occurences.size; -function envReplace(value) { - let env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.env; + if (!mostOccurenceCount || occurenceCount > mostOccurenceCount) { + mostOccurenceCount = occurenceCount; + mostOccurencePattern = pattern; + } + } + invariant(mostOccurencePattern, 'expected most occuring pattern'); + invariant(mostOccurenceCount, 'expected most occuring count'); - if (typeof value !== 'string' || !value) { - return value; + // only hoist this module if it occured more than once + if (mostOccurenceCount > 1) { + this._seed(mostOccurencePattern, { isDirectRequire: false }); + } + } } - return value.replace(ENV_EXPR, (match, esc, envVarName) => { - if (esc.length && esc.length % 2) { - return match; - } - if (undefined === env[envVarName]) { - throw new Error('Failed to replace env in config: ' + match); - } - return env[envVarName] || ''; - }); -} + /** + * Produce a flattened list of module locations and manifests. + */ -/***/ }), -/* 384 */ -/***/ (function(module, exports, __webpack_require__) { + init() { + const flatTree = []; -"use strict"; + // + for (const _ref9 of this.tree.entries()) { + var _ref10 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref9, 2); + const key = _ref10[0]; + const info = _ref10[1]; -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.fixCmdWinSlashes = fixCmdWinSlashes; -function fixCmdWinSlashes(cmd) { - function findQuotes(quoteSymbol) { - const quotes = []; - const addQuote = (_, index) => { - quotes.push({ from: index, to: index + _.length }); - return _; - }; - const regEx = new RegExp(quoteSymbol + '.*' + quoteSymbol); - cmd.replace(regEx, addQuote); - return quotes; - } - const quotes = findQuotes('"').concat(findQuotes("'")); + // decompress the location and push it to the flat tree. this path could be made + const parts = []; + const keyParts = key.split('#'); + for (let i = 0; i < keyParts.length; i++) { + const key = keyParts.slice(0, i + 1).join('#'); + const hoisted = this.tree.get(key); + invariant(hoisted, 'expected hoisted manifest'); + parts.push(this.config.getFolder(hoisted.pkg)); + parts.push(keyParts[i]); + } - function isInsideQuotes(index) { - return quotes.reduce((result, quote) => { - return result || quote.from <= index && index <= quote.to; - }, false); - } + if (this.config.modulesFolder) { + // remove the first part which will be the folder name and replace it with a + // hardcoded modules folder + parts.splice(0, 1, this.config.modulesFolder); + } else { + // first part will be the registry-specific module folder + parts.splice(0, 0, this.config.lockfileFolder); + } - const cmdPrePattern = '((?:^|&&|&|\\|\\||\\|)\\s*)'; - const cmdPattern = '(".*?"|\'.*?\'|\\S*)'; - const regExp = new RegExp(`${cmdPrePattern}${cmdPattern}`, 'g'); - return cmd.replace(regExp, (whole, pre, cmd, index) => { - if ((pre[0] === '&' || pre[0] === '|') && isInsideQuotes(index)) { - return whole; + const loc = path.join(...parts); + flatTree.push([loc, info]); } - return pre + cmd.replace(/\//g, '\\'); - }); -} - -/***/ }), -/* 385 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; + // remove ignored modules from the tree + const visibleFlatTree = []; + for (const _ref11 of flatTree) { + var _ref12 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref11, 2); -Object.defineProperty(exports, "__esModule", { - value: true -}); -const lockPromises = new Map(); + const loc = _ref12[0]; + const info = _ref12[1]; -/** - * Acquires a mutex lock over the given key. If the lock can't be acquired, it waits until it's available. - * @param key Key to get the lock for. - * @return {Promise.<Function>} A Promise that resolves when the lock is acquired, with the function that - * must be called to release the lock. - */ + const ref = info.pkg._reference; + invariant(ref, 'expected reference'); + if (!info.isRequired) { + info.addHistory('Deleted as this module was ignored'); + } else { + visibleFlatTree.push([loc, info]); + } + } + return visibleFlatTree; + } +} -exports.default = key => { - let unlockNext; - const willLock = new Promise(resolve => unlockNext = resolve); - const lockPromise = lockPromises.get(key) || Promise.resolve(); - const willUnlock = lockPromise.then(() => unlockNext); - lockPromises.set(key, lockPromise.then(() => willLock)); - return willUnlock; -}; +exports.default = PackageHoister; /***/ }), -/* 386 */ +/* 416 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81541,34 +85794,22 @@ Object.defineProperty(exports, "__esModule", { value: true }); -var _toArray2; +var _slicedToArray2; -function _load_toArray() { - return _toArray2 = _interopRequireDefault(__webpack_require__(67)); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } var _asyncToGenerator2; function _load_asyncToGenerator() { - return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(0)); -} - -var _util; - -function _load_util() { - return _util = __webpack_require__(130); -} - -var _index; - -function _load_index() { - return _index = __webpack_require__(53); + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -var _inferLicense; +var _executeLifecycleScript; -function _load_inferLicense() { - return _inferLicense = _interopRequireDefault(__webpack_require__(387)); +function _load_executeLifecycleScript() { + return _executeLifecycleScript = _interopRequireDefault(__webpack_require__(97)); } var _fs; @@ -81581,307 +85822,314 @@ function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const semver = __webpack_require__(27); -const path = __webpack_require__(1); -const url = __webpack_require__(11); +const invariant = __webpack_require__(7); -const LICENSE_RENAMES = { - 'MIT/X11': 'MIT', - X11: 'MIT' -}; +const INSTALL_STAGES = ['preinstall', 'install', 'postinstall']; -exports.default = (() => { - var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, reporter, warn, looseSemver) { - const files = yield (_fs || _load_fs()).readdir(moduleLoc); +class PackageInstallScripts { + constructor(config, resolver, force) { + this.installed = 0; + this.resolver = resolver; + this.reporter = config.reporter; + this.config = config; + this.force = force; + this.artifacts = {}; + } - // clean info.version - if (typeof info.version === 'string') { - info.version = semver.clean(info.version, looseSemver) || info.version; - } + setForce(force) { + this.force = force; + } - // if name or version aren't set then set them to empty strings - info.name = info.name || ''; - info.version = info.version || ''; + setArtifacts(artifacts) { + this.artifacts = artifacts; + } - // if the man field is a string then coerce it to an array - if (typeof info.man === 'string') { - info.man = [info.man]; + getArtifacts() { + return this.artifacts; + } + + getInstallCommands(pkg) { + const scripts = pkg.scripts; + if (scripts) { + const cmds = []; + for (const stage of INSTALL_STAGES) { + const cmd = scripts[stage]; + if (cmd) { + cmds.push([stage, cmd]); + } + } + return cmds; + } else { + return []; } + } - // if the keywords field is a string then split it on any whitespace - if (typeof info.keywords === 'string') { - info.keywords = info.keywords.split(/\s+/g); - } + walk(loc) { + var _this = this; - // if there's no contributors field but an authors field then expand it - if (!info.contributors && files.indexOf('AUTHORS') >= 0) { - const authorsFilepath = path.join(moduleLoc, 'AUTHORS'); - const authorsFilestats = yield (_fs || _load_fs()).stat(authorsFilepath); - if (authorsFilestats.isFile()) { - let authors = yield (_fs || _load_fs()).readFile(authorsFilepath); - authors = authors.split(/\r?\n/g) // split on lines - .map(function (line) { - return line.replace(/^\s*#.*$/, '').trim(); - }) // remove comments - .filter(function (line) { - return !!line; - }); // remove empty lines - info.contributors = authors; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const files = yield (_fs || _load_fs()).walk(loc, null, new Set(_this.config.registryFolders)); + const mtimes = new Map(); + for (const file of files) { + mtimes.set(file.relative, file.mtime); } - } + return mtimes; + })(); + } - // expand people fields to objects - if (typeof info.author === 'string' || typeof info.author === 'object') { - info.author = (0, (_util || _load_util()).normalizePerson)(info.author); - } - if (Array.isArray(info.contributors)) { - info.contributors = info.contributors.map((_util || _load_util()).normalizePerson); - } - if (Array.isArray(info.maintainers)) { - info.maintainers = info.maintainers.map((_util || _load_util()).normalizePerson); - } + saveBuildArtifacts(loc, pkg, beforeFiles, spinner) { + var _this2 = this; - // if there's no readme field then load the README file from the cwd - if (!info.readme) { - const readmeCandidates = files.filter(function (filename) { - const lower = filename.toLowerCase(); - return lower === 'readme' || lower.indexOf('readme.') === 0; - }).sort(function (filename1, filename2) { - // favor files with extensions - return filename2.indexOf('.') - filename1.indexOf('.'); - }); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const afterFiles = yield _this2.walk(loc); - for (const readmeFilename of readmeCandidates) { - const readmeFilepath = path.join(moduleLoc, readmeFilename); - const readmeFileStats = yield (_fs || _load_fs()).stat(readmeFilepath); - if (readmeFileStats.isFile()) { - info.readmeFilename = readmeFilename; - info.readme = yield (_fs || _load_fs()).readFile(readmeFilepath); - break; + // work out what files have been created/modified + const buildArtifacts = []; + for (const _ref of afterFiles) { + var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); + + const file = _ref2[0]; + const mtime = _ref2[1]; + + if (!beforeFiles.has(file) || beforeFiles.get(file) !== mtime) { + buildArtifacts.push(file); } } - } - // if there's no description then take the first paragraph from the readme - if (!info.description && info.readme) { - const desc = (0, (_util || _load_util()).extractDescription)(info.readme); - if (desc) { - info.description = desc; + if (!buildArtifacts.length) { + // nothing else to do here since we have no build artifacts + return; } - } - // support array of engine keys - if (Array.isArray(info.engines)) { - const engines = {}; - for (const str of info.engines) { - if (typeof str === 'string') { - var _str$trim$split = str.trim().split(/ +/g), - _str$trim$split2 = (0, (_toArray2 || _load_toArray()).default)(_str$trim$split); + // set build artifacts + const ref = pkg._reference; + invariant(ref, 'expected reference'); + _this2.artifacts[`${pkg.name}@${pkg.version}`] = buildArtifacts; + })(); + } - const name = _str$trim$split2[0], - patternParts = _str$trim$split2.slice(1); + install(cmds, pkg, spinner) { + var _this3 = this; - engines[name] = patternParts.join(' '); - } - } - info.engines = engines; - } + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const ref = pkg._reference; + invariant(ref, 'expected reference'); + const loc = _this3.config.generateHardModulePath(ref); - // if the repository field is a string then assume it's a git repo and expand it - if (typeof info.repository === 'string') { - info.repository = { - type: 'git', - url: info.repository - }; - } + try { + for (const _ref3 of cmds) { + var _ref4 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref3, 2); - const repo = info.repository; + const stage = _ref4[0]; + const cmd = _ref4[1]; - // explode info.repository.url if it's a hosted git shorthand - if (repo && typeof repo === 'object' && typeof repo.url === 'string') { - repo.url = (0, (_index || _load_index()).hostedGitFragmentToGitUrl)(repo.url, reporter); - } + var _ref5 = yield (0, (_executeLifecycleScript || _load_executeLifecycleScript()).default)(stage, _this3.config, loc, cmd, spinner); - // allow bugs to be specified as a string, expand it to an object with a single url prop - if (typeof info.bugs === 'string') { - info.bugs = { url: info.bugs }; - } + const stdout = _ref5.stdout; - // normalize homepage url to http - if (typeof info.homepage === 'string') { - const parts = url.parse(info.homepage); - parts.protocol = parts.protocol || 'http:'; - if (parts.pathname && !parts.hostname) { - parts.hostname = parts.pathname; - parts.pathname = ''; - } - info.homepage = url.format(parts); - } + _this3.reporter.verbose(stdout); + } + } catch (err) { + err.message = `${loc}: ${err.message}`; - // if the `bin` field is as string then expand it to an object with a single property - // based on the original `bin` field and `name field` - // { name: "foo", bin: "cli.js" } -> { name: "foo", bin: { foo: "cli.js" } } - if (typeof info.name === 'string' && typeof info.bin === 'string') { - // Remove scoped package name for consistency with NPM's bin field fixing behaviour - const name = info.name.replace(/^@[^\/]+\//, ''); - info.bin = { [name]: info.bin }; - } + invariant(ref, 'expected reference'); - // bundleDependencies is an alias for bundledDependencies - if (info.bundledDependencies) { - info.bundleDependencies = info.bundledDependencies; - delete info.bundledDependencies; - } + if (ref.optional) { + ref.ignore = true; + ref.incompatible = true; + _this3.reporter.warn(_this3.reporter.lang('optionalModuleScriptFail', err.message)); + _this3.reporter.info(_this3.reporter.lang('optionalModuleFail')); - let scripts; + // Cleanup node_modules + try { + yield (_fs || _load_fs()).unlink(loc); + } catch (e) { + _this3.reporter.error(_this3.reporter.lang('optionalModuleCleanupFail', e.message)); + } + } else { + throw err; + } + } + })(); + } - // dummy script object to shove file inferred scripts onto - if (info.scripts && typeof info.scripts === 'object') { - scripts = info.scripts; - } else { - scripts = {}; + packageCanBeInstalled(pkg) { + const cmds = this.getInstallCommands(pkg); + if (!cmds.length) { + return false; } - - // if there's a server.js file and no start script then set it to `node server.js` - if (!scripts.start && files.indexOf('server.js') >= 0) { - scripts.start = 'node server.js'; + const ref = pkg._reference; + invariant(ref, 'Missing package reference'); + if (!ref.fresh && !this.force) { + // this package hasn't been touched + return false; } - // if there's a binding.gyp file and no install script then set it to `node-gyp rebuild` - if (!scripts.install && files.indexOf('binding.gyp') >= 0) { - scripts.install = 'node-gyp rebuild'; + // Don't run lifecycle scripts for hoisted packages + if (!ref.location) { + return false; } - // set scripts if we've polluted the empty object - if (Object.keys(scripts).length) { - info.scripts = scripts; + // we haven't actually written this module out + if (ref.ignore) { + return false; } + return true; + } - const dirs = info.directories; + runCommand(spinner, pkg) { + var _this4 = this; - if (dirs && typeof dirs === 'object') { - const binDir = dirs.bin; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const cmds = _this4.getInstallCommands(pkg); + spinner.setPrefix(++_this4.installed, pkg.name); + yield _this4.install(cmds, pkg, spinner); + })(); + } - if (!info.bin && binDir && typeof binDir === 'string') { - const bin = info.bin = {}; - const fullBinDir = path.join(moduleLoc, binDir); + // detect if there is a circularDependency in the dependency tree + detectCircularDependencies(root, seenManifests, pkg) { + const ref = pkg._reference; + invariant(ref, 'expected reference'); - if (yield (_fs || _load_fs()).exists(fullBinDir)) { - for (const scriptName of yield (_fs || _load_fs()).readdir(fullBinDir)) { - if (scriptName[0] === '.') { - continue; - } - bin[scriptName] = path.join('.', binDir, scriptName); - } - } else { - warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name)); - } + const deps = ref.dependencies; + for (const dep of deps) { + const pkgDep = this.resolver.getStrictResolvedPattern(dep); + if (seenManifests.has(pkgDep)) { + // there is a cycle but not with the root + continue; } + seenManifests.add(pkgDep); + // found a dependency pointing to root + if (pkgDep == root) { + return true; + } + if (this.detectCircularDependencies(root, seenManifests, pkgDep)) { + return true; + } + } + return false; + } - const manDir = dirs.man; - - if (!info.man && typeof manDir === 'string') { - const man = info.man = []; - const fullManDir = path.join(moduleLoc, manDir); + // find the next package to be installed + findInstallablePackage(workQueue, installed) { + for (const pkg of workQueue) { + const ref = pkg._reference; + invariant(ref, 'expected reference'); + const deps = ref.dependencies; - if (yield (_fs || _load_fs()).exists(fullManDir)) { - for (const filename of yield (_fs || _load_fs()).readdir(fullManDir)) { - if (/^(.*?)\.[0-9]$/.test(filename)) { - man.push(path.join('.', manDir, filename)); - } - } - } else { - warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name)); + let dependenciesFullfilled = true; + for (const dep of deps) { + const pkgDep = this.resolver.getStrictResolvedPattern(dep); + if (!installed.has(pkgDep)) { + dependenciesFullfilled = false; + break; } } + + // all depedencies are installed + if (dependenciesFullfilled) { + return pkg; + } + + // detect circular dependency, mark this pkg as installable to break the circle + if (this.detectCircularDependencies(pkg, new Set(), pkg)) { + return pkg; + } } + return null; + } - delete info.directories; + worker(spinner, workQueue, installed, waitQueue) { + var _this5 = this; - // normalize licenses field - const licenses = info.licenses; - if (Array.isArray(licenses) && !info.license) { - let licenseTypes = []; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + while (true) { + // No more work to be done + if (workQueue.size == 0) { + break; + } - for (let license of licenses) { - if (license && typeof license === 'object') { - license = license.type; + // find a installable package + const pkg = _this5.findInstallablePackage(workQueue, installed); + + // can't find a package to install, register into waitQueue + if (pkg == null) { + spinner.clear(); + yield new Promise(function (resolve) { + return waitQueue.add(resolve); + }); + continue; } - if (typeof license === 'string') { - licenseTypes.push(license); + + // found a package to install + workQueue.delete(pkg); + if (_this5.packageCanBeInstalled(pkg)) { + yield _this5.runCommand(spinner, pkg); + } + installed.add(pkg); + for (const workerResolve of waitQueue) { + workerResolve(); } + waitQueue.clear(); } + })(); + } - licenseTypes = licenseTypes.filter((_util || _load_util()).isValidLicense); + init(seedPatterns) { + var _this6 = this; - if (licenseTypes.length === 1) { - info.license = licenseTypes[0]; - } else if (licenseTypes.length) { - info.license = `(${licenseTypes.join(' OR ')})`; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const workQueue = new Set(); + const installed = new Set(); + const pkgs = _this6.resolver.getTopologicalManifests(seedPatterns); + let installablePkgs = 0; + // A map to keep track of what files exist before installation + const beforeFilesMap = new Map(); + for (const pkg of pkgs) { + if (_this6.packageCanBeInstalled(pkg)) { + const ref = pkg._reference; + invariant(ref, 'expected reference'); + const loc = _this6.config.generateHardModulePath(ref); + beforeFilesMap.set(loc, (yield _this6.walk(loc))); + installablePkgs += 1; + } + workQueue.add(pkg); } - } - const license = info.license; + // waitQueue acts like a semaphore to allow workers to register to be notified + // when there are more work added to the work queue + const waitQueue = new Set(); + const workers = []; - // normalize license - if (license && typeof license === 'object') { - info.license = license.type; - } + const set = _this6.reporter.activitySet(installablePkgs, Math.min(_this6.config.childConcurrency, workQueue.size)); - // get license file - const licenseFile = files.find(function (filename) { - const lower = filename.toLowerCase(); - return lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.'); - }); - if (licenseFile) { - const licenseFilepath = path.join(moduleLoc, licenseFile); - const licenseFileStats = yield (_fs || _load_fs()).stat(licenseFilepath); - if (licenseFileStats.isFile()) { - const licenseContent = yield (_fs || _load_fs()).readFile(licenseFilepath); - const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(licenseContent); - info.licenseText = licenseContent; + for (const spinner of set.spinners) { + workers.push(_this6.worker(spinner, workQueue, installed, waitQueue)); + } - const license = info.license; + yield Promise.all(workers); - if (typeof license === 'string') { - if (inferredLicense && (0, (_util || _load_util()).isValidLicense)(inferredLicense) && !(0, (_util || _load_util()).isValidLicense)(license)) { - // some packages don't specify their license version but we can infer it based on their license file - const basicLicense = license.toLowerCase().replace(/(-like|\*)$/g, ''); - const expandedLicense = inferredLicense.toLowerCase(); - if (expandedLicense.startsWith(basicLicense)) { - // TODO consider doing something to notify the user - info.license = inferredLicense; - } - } - } else if (inferredLicense) { - // if there's no license then infer it based on the license file - info.license = inferredLicense; - } else { - // valid expression to refer to a license in a file - info.license = `SEE LICENSE IN ${licenseFile}`; + // cache all build artifacts + for (const pkg of pkgs) { + if (_this6.packageCanBeInstalled(pkg)) { + const ref = pkg._reference; + invariant(ref, 'expected reference'); + const loc = _this6.config.generateHardModulePath(ref); + const beforeFiles = beforeFilesMap.get(loc); + invariant(beforeFiles, 'files before installation should always be recorded'); + yield _this6.saveBuildArtifacts(loc, pkg, beforeFiles, set.spinners[0]); } } - } - - if (typeof info.license === 'string') { - // sometimes licenses are known by different names, reduce them - info.license = LICENSE_RENAMES[info.license] || info.license; - } else if (typeof info.readme === 'string') { - // the license might be at the bottom of the README - const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(info.readme); - if (inferredLicense) { - info.license = inferredLicense; - } - } - }); - return function (_x, _x2, _x3, _x4, _x5) { - return _ref.apply(this, arguments); - }; -})(); + set.end(); + })(); + } +} +exports.default = PackageInstallScripts; /***/ }), -/* 387 */ +/* 417 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81890,53 +86138,120 @@ exports.default = (() => { Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = inferLicense; -var _licenses; +var _slicedToArray2; -function _load_licenses() { - return _licenses = _interopRequireDefault(__webpack_require__(388)); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var _misc; -function clean(str) { - return str.replace(/[^A-Za-z\s]/g, ' ').replace(/[\s]+/g, ' ').trim().toLowerCase(); +function _load_misc() { + return _misc = __webpack_require__(10); } -const REGEXES = { - Apache: [/Apache License\b/], - BSD: [/BSD\b/], - ISC: [/The ISC License/, /ISC\b/], - MIT: [/MIT\b/], - Unlicense: [/http:\/\/unlicense.org\//], - WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\b/] -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function inferLicense(license) { - // check if we have any explicit licenses - const cleanLicense = clean(license); - for (const licenseName in (_licenses || _load_licenses()).default) { - const testLicense = (_licenses || _load_licenses()).default[licenseName]; - if (cleanLicense.search(testLicense) >= 0) { - return licenseName; +class PackageReference { + constructor(request, info, remote) { + this.resolver = request.resolver; + this.lockfile = request.lockfile; + this.requests = []; + this.config = request.config; + + this.registry = remote.registry; + this.version = info.version; + this.name = info.name; + this.uid = info._uid; + + this.remote = remote; + + this.dependencies = []; + + this.permissions = {}; + this.patterns = []; + this.optional = null; + this.root = false; + this.ignore = false; + this.incompatible = false; + this.fresh = false; + this.location = null; + this.addRequest(request); + } + + setFresh(fresh) { + this.fresh = fresh; + } + + setLocation(loc) { + return this.location = loc; + } + + addRequest(request) { + this.requests.push(request); + + if (!request.parentRequest) { + this.root = true; + } + } + + prune() { + for (const selfPattern of this.patterns) { + // remove ourselves from the resolver + this.resolver.removePattern(selfPattern); + } + } + + addDependencies(deps) { + this.dependencies = this.dependencies.concat(deps); + } + + setPermission(key, val) { + this.permissions[key] = val; + } + + hasPermission(key) { + if (key in this.permissions) { + return this.permissions[key]; + } else { + return false; } } - // infer based on some keywords - for (const licenseName in REGEXES) { - for (const regex of REGEXES[licenseName]) { - if (license.search(regex) >= 0) { - return `${licenseName}*`; + addPattern(pattern, manifest) { + this.resolver.addPattern(pattern, manifest); + + this.patterns.push(pattern); + + const shrunk = this.lockfile.getLocked(pattern); + if (shrunk && shrunk.permissions) { + for (const _ref of (0, (_misc || _load_misc()).entries)(shrunk.permissions)) { + var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 2); + + const key = _ref2[0]; + const perm = _ref2[1]; + + this.setPermission(key, perm); } } } - return null; + addOptional(optional) { + if (this.optional == null) { + // optional is uninitialised + this.optional = optional; + } else if (!optional) { + // otherwise, ignore all subsequent optional assignments and only accept ones making + // this not optional + this.optional = false; + } + } } +exports.default = PackageReference; /***/ }), -/* 388 */ +/* 418 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -81946,196 +86261,163 @@ Object.defineProperty(exports, "__esModule", { value: true }); +var _asyncToGenerator2; -/* eslint-disable max-len */ - -/** - * DO NOT EDIT THIS FILE MANUALLY. - * THIS FILE WAS GENERATED BY "generate-licenses-js.js". - */ +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} -exports.default = { - 'Apache-2.0': new RegExp('(licensed under the apache license version the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license$|apache license version january http www apache org licenses terms and conditions for use reproduction and distribution definitions license shall mean the terms and conditions for use reproduction and distribution as defined by sections through of this document licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the license legal entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity for the purposes of this definition control means i the power direct or indirect to cause the direction or management of such entity whether by contract or otherwise or ii ownership of fifty percent or more of the outstanding shares or iii beneficial ownership of such entity you or your shall mean an individual or legal entity exercising permissions granted by this license source form shall mean the preferred form for making modifications including but not limited to software source code documentation source and configuration files object form shall mean any form resulting from mechanical transformation or translation of a source form including but not limited to compiled object code generated documentation and conversions to other media types work shall mean the work of authorship whether in source or object form made available under the license as indicated by a copyright notice that is included in or attached to the work an example is provided in the appendix below derivative works shall mean any work whether in source or object form that is based on or derived from the work and for which the editorial revisions annotations elaborations or other modifications represent as a whole an original work of authorship for the purposes of this license derivative works shall not include works that remain separable from or merely link or bind by name to the interfaces of the work and derivative works thereof contribution shall mean any work of authorship including the original version of the work and any modifications or additions to that work or derivative works thereof that is intentionally submitted to licensor for inclusion in the work by the copyright owner or by an individual or legal entity authorized to submit on behalf of the copyright owner for the purposes of this definition submitted means any form of electronic verbal or written communication sent to the licensor or its representatives including but not limited to communication on electronic mailing lists source code control systems and issue tracking systems that are managed by or on behalf of the licensor for the purpose of discussing and improving the work but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as not a contribution contributor shall mean licensor and any individual or legal entity on behalf of whom a contribution has been received by licensor and subsequently incorporated within the work grant of copyright license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable copyright license to reproduce prepare derivative works of publicly display publicly perform sublicense and distribute the work and such derivative works in source or object form grant of patent license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable except as stated in this section patent license to make have made use offer to sell sell import and otherwise transfer the work where such license applies only to those patent claims licensable by such contributor that are necessarily infringed by their contribution s alone or by combination of their contribution s with the work to which such contribution s was submitted if you institute patent litigation against any entity including a cross claim or counterclaim in a lawsuit alleging that the work or a contribution incorporated within the work constitutes direct or contributory patent infringement then any patent licenses granted to you under this license for that work shall terminate as of the date such litigation is filed redistribution you may reproduce and distribute copies of the work or derivative works thereof in any medium with or without modifications and in source or object form provided that you meet the following conditions a you must give any other recipients of the work or derivative works a copy of this license and b you must cause any modified files to carry prominent notices stating that you changed the files and c you must retain in the source form of any derivative works that you distribute all copyright patent trademark and attribution notices from the source form of the work excluding those notices that do not pertain to any part of the derivative works and d if the work includes a notice text file as part of its distribution then any derivative works that you distribute must include a readable copy of the attribution notices contained within such notice file excluding those notices that do not pertain to any part of the derivative works in at least one of the following places within a notice text file distributed as part of the derivative works within the source form or documentation if provided along with the derivative works or within a display generated by the derivative works if and wherever such third party notices normally appear the contents of the notice file are for informational purposes only and do not modify the license you may add your own attribution notices within derivative works that you distribute alongside or as an addendum to the notice text from the work provided that such additional attribution notices cannot be construed as modifying the license you may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use reproduction or distribution of your modifications or for any such derivative works as a whole provided your use reproduction and distribution of the work otherwise complies with the conditions stated in this license submission of contributions unless you explicitly state otherwise any contribution intentionally submitted for inclusion in the work by you to the licensor shall be under the terms and conditions of this license without any additional terms or conditions notwithstanding the above nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with licensor regarding such contributions trademarks this license does not grant permission to use the trade names trademarks service marks or product names of the licensor except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the notice file disclaimer of warranty unless required by applicable law or agreed to in writing licensor provides the work and each contributor provides its contributions on an as is basis without warranties or conditions of any kind either express or implied including without limitation any warranties or conditions of title non infringement merchantability or fitness for a particular purpose you are solely responsible for determining the appropriateness of using or redistributing the work and assume any risks associated with your exercise of permissions under this license limitation of liability in no event and under no legal theory whether in tort including negligence contract or otherwise unless required by applicable law such as deliberate and grossly negligent acts or agreed to in writing shall any contributor be liable to you for damages including any direct indirect special incidental or consequential damages of any character arising as a result of this license or out of the use or inability to use the work including but not limited to damages for loss of goodwill work stoppage computer failure or malfunction or any and all other commercial damages or losses even if such contributor has been advised of the possibility of such damages accepting warranty or additional liability while redistributing the work or derivative works thereof you may choose to offer and charge a fee for acceptance of support warranty indemnity or other liability obligations and or rights consistent with this license however in accepting such obligations you may act only on your own behalf and on your sole responsibility not on behalf of any other contributor and only if you agree to indemnify defend and hold each contributor harmless for any liability incurred by or claims asserted against such contributor by reason of your accepting any such warranty or additional liability end of terms and conditions$)', 'g'), - 'BSD-2-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this(.*?| )is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this(.*?| )even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$)', 'g'), - 'BSD-3-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name of(.*?| )nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution the names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall the copyright holders and contributors be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name(.*?| )nor the names of(.*?| )contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by(.*?| )as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$))', 'g'), - MIT: new RegExp('permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software$', 'g'), - Unlicense: new RegExp('this is free and unencumbered software released into the public domain anyone is free to copy modify publish use compile sell or distribute this software either in source code form or as a compiled binary for any purpose commercial or non commercial and by any means in jurisdictions that recognize copyright laws the author or authors of this software dedicate any and all copyright interest in the software to the public domain we make this dedication for the benefit of the public at large and to the detriment of our heirs and successors we intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software for more information please refer to wildcard$', 'g') -}; +var _extends2; -/***/ }), -/* 389 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_extends() { + return _extends2 = _interopRequireDefault(__webpack_require__(36)); +} -"use strict"; +var _misc; +function _load_misc() { + return _misc = __webpack_require__(10); +} -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = { - autohr: 'author', - autor: 'author', - contributers: 'contributors', - depdenencies: 'dependencies', - dependancies: 'dependencies', - dependecies: 'dependencies', - depends: 'dependencies', - 'dev-dependencies': 'devDependencies', - devDependences: 'devDependencies', - devDepenencies: 'devDependencies', - devEependencies: 'devDependencies', - devdependencies: 'devDependencies', - hampage: 'homepage', - hompage: 'homepage', - prefereGlobal: 'preferGlobal', - publicationConfig: 'publishConfig', - repo: 'repository', - repostitory: 'repository', - script: 'scripts' -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 390 */ -/***/ (function(module, exports, __webpack_require__) { +const objectPath = __webpack_require__(300); -"use strict"; +const path = __webpack_require__(0); +class BaseRegistry { + constructor(cwd, registries, requestManager, reporter) { + this.reporter = reporter; + this.requestManager = requestManager; + this.registries = registries; + this.config = {}; + this.folder = ''; + this.token = ''; + this.loc = ''; + this.cwd = cwd; + } -Object.defineProperty(exports, "__esModule", { - value: true -}); + // the filename to use for package metadata -var _slicedToArray2; -function _load_slicedToArray() { - return _slicedToArray2 = _interopRequireDefault(__webpack_require__(12)); -} + // -exports.default = parsePackageName; + // -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -const PKG_INPUT = /(^\S?[^\s@]+)(?:@(\S+))?$/; + // -function parsePackageName(input) { - var _PKG_INPUT$exec = PKG_INPUT.exec(input), - _PKG_INPUT$exec2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_PKG_INPUT$exec, 3); - const name = _PKG_INPUT$exec2[1], - version = _PKG_INPUT$exec2[2]; + // - return { name, version }; -} -/***/ }), -/* 391 */ -/***/ (function(module, exports, __webpack_require__) { + // -"use strict"; + // -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.findRc = findRc; -var _fs; + // absolute folder name to insert modules -function _load_fs() { - return _fs = __webpack_require__(6); -} -var _path; + // relative folder name to put these modules -function _load_path() { - return _path = __webpack_require__(1); -} -const etc = '/etc'; -const isWin = process.platform === 'win32'; -const home = isWin ? process.env.USERPROFILE : process.env.HOME; + setToken(token) { + this.token = token; + } -function findRc(name, parser) { - let configPaths = []; + getOption(key) { + return this.config[key]; + } - function addConfigPath() { - configPaths.push((0, (_path || _load_path()).join)(...arguments)); + getAvailableRegistries() { + const config = this.config; + return Object.keys(config).reduce((registries, option) => { + if (option === 'registry' || option.split(':')[1] === 'registry') { + registries.push(config[option]); + } + return registries; + }, []); } - function addRecursiveConfigPath() { - const queue = []; + loadConfig() { + return Promise.resolve(); + } - let oldPath; - let path = (0, (_path || _load_path()).join)(...arguments); + checkOutdated(config, name, range) { + return Promise.reject(new Error('unimplemented')); + } - do { - queue.unshift(path); + saveHomeConfig(config) { + return Promise.reject(new Error('unimplemented')); + } - oldPath = path; - path = (0, (_path || _load_path()).join)((0, (_path || _load_path()).dirname)((0, (_path || _load_path()).dirname)(path)), (0, (_path || _load_path()).basename)(path)); - } while (path !== oldPath); + request(pathname) { + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - configPaths = configPaths.concat(queue); + return this.requestManager.request((0, (_extends2 || _load_extends()).default)({ + url: pathname + }, opts)); } - function fetchConfigs() { - return Object.assign({}, ...configPaths.map(path => { - try { - return parser((0, (_fs || _load_fs()).readFileSync)(path).toString(), path); - } catch (error) { - return {}; - } - })); - } + init() { + var _this = this; - if (!isWin) { - addConfigPath(etc, name, 'config'); - addConfigPath(etc, `${name}rc`); + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + _this.mergeEnv('yarn_'); + yield _this.loadConfig(); + _this.loc = path.join(_this.cwd, _this.folder); + })(); } - if (home) { - addConfigPath(home, '.config', name, 'config'); - addConfigPath(home, '.config', name); - addConfigPath(home, `.${name}`, 'config'); - addConfigPath(home, `.${name}rc`); + static normalizeConfig(config) { + for (const key in config) { + config[key] = BaseRegistry.normalizeConfigOption(config[key]); + } + return config; } - addRecursiveConfigPath(process.cwd(), `.${name}rc`); + static normalizeConfigOption(val) { + if (val === 'true') { + return true; + } else if (val === 'false') { + return false; + } else { + return val; + } + } - const envVariable = `${name}_config`.toUpperCase(); + mergeEnv(prefix) { + // try environment variables + for (const envKey in process.env) { + let key = envKey.toLowerCase(); - if (process.env[envVariable]) { - addConfigPath(process.env[envVariable]); - } + // only accept keys prefixed with the prefix + if (key.indexOf(prefix.toLowerCase()) < 0) { + continue; + } - return fetchConfigs(); -} + const val = BaseRegistry.normalizeConfigOption(process.env[envKey]); -/***/ }), -/* 392 */ -/***/ (function(module, exports, __webpack_require__) { + // remove config prefix + key = (0, (_misc || _load_misc()).removePrefix)(key, prefix.toLowerCase()); -"use strict"; + // replace dunders with dots + key = key.replace(/__/g, '.'); + // replace underscores with dashes + key = key.replace(/_/g, '-'); -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isRootUser = isRootUser; -function getUid() { - if (process.platform !== 'win32' && process.getuid) { - return process.getuid(); + // set it via a path + objectPath.set(this.config, key, val); + } } - return null; -} - -exports.default = isRootUser(getUid()); -function isRootUser(uid) { - return uid === 0; } +exports.default = BaseRegistry; /***/ }), -/* 393 */ +/* 419 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -82144,3390 +86426,2809 @@ function isRootUser(uid) { Object.defineProperty(exports, "__esModule", { value: true }); -exports.satisfiesWithPreleases = satisfiesWithPreleases; -const semver = __webpack_require__(27); - -/** - * Returns whether the given semver version satisfies the given range. Notably this supports - * prerelease versions so that "2.0.0-rc.0" satisfies the range ">=1.0.0", for example. - */ - -function satisfiesWithPreleases(version, range) { - let loose = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; +exports.DEFAULTS = undefined; - let semverRange; - try { - // $FlowFixMe: Add a definition for the Range class - semverRange = new semver.Range(range, loose); - } catch (err) { - return false; - } +var _slicedToArray2; - if (!version) { - return false; - } - const semverVersion = new semver.SemVer(version, semverRange.loose); +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} - // A range has multiple sets of comparators. A version must satisfy all comparators in a set - // and at least one set to satisfy the range. - return semverRange.set.some(comparatorSet => { - // node-semver converts ~ and ^ ranges into pairs of >= and < ranges but the upper bounds don't - // properly exclude prerelease versions. For example, "^1.0.0" is converted to ">=1.0.0 <2.0.0", - // which includes "2.0.0-pre" since prerelease versions are lower than their non-prerelease - // counterparts. As a practical workaround we make upper-bound ranges exclude prereleases and - // convert "<2.0.0" to "<2.0.0-0", for example. - comparatorSet = comparatorSet.map(comparator => { - if (comparator.operator !== '<' || !comparator.value || comparator.semver.prerelease.length) { - return comparator; - } +var _asyncToGenerator2; - // "0" is the lowest prerelease version - comparator.semver.inc('pre', 0); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - const comparatorString = comparator.operator + comparator.semver.version; - // $FlowFixMe: Add a definition for the Comparator class - return new semver.Comparator(comparatorString, comparator.loose); - }); +var _constants; - return !comparatorSet.some(comparator => !comparator.test(semverVersion)); - }); +function _load_constants() { + return _constants = __webpack_require__(6); } -/***/ }), -/* 394 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = { "default": __webpack_require__(413), __esModule: true }; +var _npmRegistry; -/***/ }), -/* 395 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_npmRegistry() { + return _npmRegistry = _interopRequireDefault(__webpack_require__(52)); +} -module.exports = { "default": __webpack_require__(414), __esModule: true }; +var _lockfile; -/***/ }), -/* 396 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_lockfile() { + return _lockfile = __webpack_require__(12); +} -module.exports = { "default": __webpack_require__(415), __esModule: true }; +var _fs; -/***/ }), -/* 397 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} -module.exports = { "default": __webpack_require__(416), __esModule: true }; +var _yarnVersion; -/***/ }), -/* 398 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_yarnVersion() { + return _yarnVersion = __webpack_require__(91); +} -module.exports = { "default": __webpack_require__(417), __esModule: true }; +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } -/***/ }), -/* 399 */ -/***/ (function(module, exports) { +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); +const userHome = __webpack_require__(62).default; +const path = __webpack_require__(0); - var r = range(a, b, str); +const DEFAULTS = exports.DEFAULTS = { + 'version-tag-prefix': 'v', + 'version-git-tag': true, + 'version-git-sign': false, + 'version-git-message': 'v%s', - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} + 'init-version': '1.0.0', + 'init-license': 'MIT', -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} + 'save-prefix': '^', + 'ignore-scripts': false, + 'ignore-optional': false, + registry: (_constants || _load_constants()).YARN_REGISTRY, + 'strict-ssl': true, + 'user-agent': [`yarn/${(_yarnVersion || _load_yarnVersion()).version}`, 'npm/?', `node/${process.version}`, process.platform, process.arch].join(' ') +}; -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; +const npmMap = { + 'version-git-sign': 'sign-git-tag', + 'version-tag-prefix': 'tag-version-prefix', + 'version-git-tag': 'git-tag-version', + 'version-git-message': 'message' +}; - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; +class YarnRegistry extends (_npmRegistry || _load_npmRegistry()).default { + constructor(cwd, registries, requestManager, reporter) { + super(cwd, registries, requestManager, reporter); - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } + this.homeConfigLoc = path.join(userHome, '.yarnrc'); + this.homeConfig = {}; + } - bi = str.indexOf(b, i + 1); - } + getOption(key) { + let val = this.config[key]; - i = ai < bi && ai >= 0 ? ai : bi; + // if this isn't set in a yarn config, then use npm + if (typeof val === 'undefined') { + val = this.registries.npm.getOption(npmMap[key]); } - if (begs.length) { - result = [ left, right ]; + if (typeof val === 'undefined') { + val = this.registries.npm.getOption(key); } - } - - return result; -} - - -/***/ }), -/* 400 */ -/***/ (function(module, exports, __webpack_require__) { - -var DuplexStream = __webpack_require__(579) - , util = __webpack_require__(2) - -function BufferList (callback) { - if (!(this instanceof BufferList)) - return new BufferList(callback) + // if this isn't set in a yarn config or npm config, then use the default (or undefined) + if (typeof val === 'undefined') { + val = DEFAULTS[key]; + } - this._bufs = [] - this.length = 0 + return val; + } - if (typeof callback == 'function') { - this._callback = callback + loadConfig() { + var _this = this; - var piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + for (const _ref of yield _this.getPossibleConfigLocations('yarnrc', _this.reporter)) { + var _ref2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref, 3); - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) - } else { - this.append(callback) - } + const isHome = _ref2[0]; + const loc = _ref2[1]; + const file = _ref2[2]; - DuplexStream.call(this) -} + var _parse = (0, (_lockfile || _load_lockfile()).parse)(file, loc); + const config = _parse.object; -util.inherits(BufferList, DuplexStream) + if (isHome) { + _this.homeConfig = config; + } -BufferList.prototype._offset = function _offset (offset) { - var tot = 0, i = 0, _t - if (offset === 0) return [ 0, 0 ] - for (; i < this._bufs.length; i++) { - _t = tot + this._bufs[i].length - if (offset < _t || i == this._bufs.length - 1) - return [ i, offset - tot ] - tot = _t - } -} + // normalize offline mirror path relative to the current yarnrc + const offlineLoc = config['yarn-offline-mirror']; + // don't normalize if we already have a mirror path + if (!_this.config['yarn-offline-mirror'] && offlineLoc) { + const mirrorLoc = config['yarn-offline-mirror'] = path.resolve(path.dirname(loc), offlineLoc); + yield (_fs || _load_fs()).mkdirp(mirrorLoc); + } -BufferList.prototype.append = function append (buf) { - var i = 0 + // merge with any existing environment variables + const env = config.env; + if (env) { + const existingEnv = _this.config.env; + if (existingEnv) { + _this.config.env = Object.assign({}, env, existingEnv); + } + } - if (Buffer.isBuffer(buf)) { - this._appendBuffer(buf); - } else if (Array.isArray(buf)) { - for (; i < buf.length; i++) - this.append(buf[i]) - } else if (buf instanceof BufferList) { - // unwrap argument into individual BufferLists - for (; i < buf._bufs.length; i++) - this.append(buf._bufs[i]) - } else if (buf != null) { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf == 'number') - buf = buf.toString() + _this.config = Object.assign({}, config, _this.config); + } - this._appendBuffer(new Buffer(buf)); + // default yarn config + _this.config = Object.assign({}, DEFAULTS, _this.config); + })(); } - return this -} + saveHomeConfig(config) { + var _this2 = this; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + YarnRegistry.normalizeConfig(config); -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} + for (const key in config) { + const val = config[key]; + // if the current config key was taken from home config then update + // the global config + if (_this2.homeConfig[key] === _this2.config[key]) { + _this2.config[key] = val; + } -BufferList.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) + // update just the home config + _this2.homeConfig[key] = config[key]; + } - if (typeof callback == 'function') - callback() + yield (_fs || _load_fs()).writeFilePreservingEol(_this2.homeConfigLoc, `${(0, (_lockfile || _load_lockfile()).stringify)(_this2.homeConfig)}\n`); + })(); + } } +exports.default = YarnRegistry; +YarnRegistry.filename = 'yarn.json'; +/***/ }), +/* 420 */ +/***/ (function(module, exports, __webpack_require__) { -BufferList.prototype._read = function _read (size) { - if (!this.length) - return this.push(null) +"use strict"; - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} +Object.defineProperty(exports, "__esModule", { + value: true +}); -BufferList.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) +var _jsonReporter; - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } +function _load_jsonReporter() { + return _jsonReporter = _interopRequireDefault(__webpack_require__(161)); } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -BufferList.prototype.get = function get (index) { - return this.slice(index, index + 1)[0] -} +class BufferReporter extends (_jsonReporter || _load_jsonReporter()).default { + constructor(opts) { + super(opts); + this._buffer = []; + } + _dump(type, data, error) { + this._buffer.push({ + type, + data, + error: !!error + }); + } -BufferList.prototype.slice = function slice (start, end) { - if (typeof start == 'number' && start < 0) - start += this.length - if (typeof end == 'number' && end < 0) - end += this.length - return this.copy(null, 0, start, end) + getBuffer() { + return this._buffer; + } } +exports.default = BufferReporter; +/***/ }), +/* 421 */ +/***/ (function(module, exports, __webpack_require__) { -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart != 'number' || srcStart < 0) - srcStart = 0 - if (typeof srcEnd != 'number' || srcEnd > this.length) - srcEnd = this.length - if (srcStart >= this.length) - return dst || new Buffer(0) - if (srcEnd <= 0) - return dst || new Buffer(0) - - var copy = !!dst - , off = this._offset(srcStart) - , len = srcEnd - srcStart - , bytes = len - , bufoff = (copy && dstStart) || 0 - , start = off[1] - , l - , i +"use strict"; - // copy/slice everything - if (srcStart === 0 && srcEnd == this.length) { - if (!copy) { // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) - } - // copy, need to copy individual buffers - for (i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length - } +Object.defineProperty(exports, "__esModule", { + value: true +}); - return dst - } +var _asyncToGenerator2; - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - if (!copy) // a slice, we need something to copy in to - dst = new Buffer(len) +var _baseReporter; - for (i = off[0]; i < this._bufs.length; i++) { - l = this._bufs[i].length - start +function _load_baseReporter() { + return _baseReporter = _interopRequireDefault(__webpack_require__(77)); +} - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - break - } +var _progressBar; - bufoff += l - bytes -= l +function _load_progressBar() { + return _progressBar = _interopRequireDefault(__webpack_require__(423)); +} - if (start) - start = 0 - } +var _spinnerProgress; - return dst +function _load_spinnerProgress() { + return _spinnerProgress = _interopRequireDefault(__webpack_require__(424)); } -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = end || this.length +var _util; - if (start < 0) - start += this.length - if (end < 0) - end += this.length +function _load_util() { + return _util = __webpack_require__(160); +} - var startOffset = this._offset(start) - , endOffset = this._offset(end) - , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) +var _misc; - if (endOffset[1] == 0) - buffers.pop() - else - buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) +function _load_misc() { + return _misc = __webpack_require__(10); +} - if (startOffset[1] != 0) - buffers[0] = buffers[0].slice(startOffset[1]) +var _treeHelper; - return new BufferList(buffers) +function _load_treeHelper() { + return _treeHelper = __webpack_require__(422); } -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} +var _inquirer; -BufferList.prototype.consume = function consume (bytes) { - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break - } - } - return this +function _load_inquirer() { + return _inquirer = _interopRequireDefault(__webpack_require__(212)); } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -BufferList.prototype.duplicate = function duplicate () { - var i = 0 - , copy = new BufferList() - - for (; i < this._bufs.length; i++) - copy.append(this._bufs[i]) +var _require = __webpack_require__(2); - return copy -} +const inspect = _require.inspect; +const readline = __webpack_require__(151); +const chalk = __webpack_require__(20); +const read = __webpack_require__(593); +const tty = __webpack_require__(90); -BufferList.prototype.destroy = function destroy () { - this._bufs.length = 0 - this.length = 0 - this.push(null) +// fixes bold on windows +if (process.platform === 'win32' && process.env.TERM && !/^xterm/i.test(process.env.TERM)) { + chalk.styles.bold.close += '\u001b[m'; } +class ConsoleReporter extends (_baseReporter || _load_baseReporter()).default { + constructor(opts) { + super(opts); -;(function () { - var methods = { - 'readDoubleBE' : 8 - , 'readDoubleLE' : 8 - , 'readFloatBE' : 4 - , 'readFloatLE' : 4 - , 'readInt32BE' : 4 - , 'readInt32LE' : 4 - , 'readUInt32BE' : 4 - , 'readUInt32LE' : 4 - , 'readInt16BE' : 2 - , 'readInt16LE' : 2 - , 'readUInt16BE' : 2 - , 'readUInt16LE' : 2 - , 'readInt8' : 1 - , 'readUInt8' : 1 + this._lastCategorySize = 0; + this._spinners = new Set(); + this.format = chalk; + this.isSilent = !!opts.isSilent; } - for (var m in methods) { - (function (m) { - BufferList.prototype[m] = function (offset) { - return this.slice(offset, offset + methods[m])[m](0) - } - }(m)) + _prependEmoji(msg, emoji) { + if (this.emoji && emoji && this.isTTY) { + msg = `${emoji} ${msg}`; + } + return msg; } -}()) + _logCategory(category, color, msg) { + this._lastCategorySize = category.length; + this._log(`${this.format[color](category)} ${msg}`); + } -module.exports = BufferList - + _verbose(msg) { + this._logCategory('verbose', 'grey', `${process.uptime()} ${msg}`); + } -/***/ }), -/* 401 */ -/***/ (function(module, exports, __webpack_require__) { + _verboseInspect(obj) { + this.inspect(obj); + } -var concatMap = __webpack_require__(412); -var balanced = __webpack_require__(399); + close() { + for (const spinner of this._spinners) { + spinner.stop(); + } + this._spinners.clear(); + this.stopProgress(); + super.close(); + } -module.exports = expandTop; + table(head, body) { + // + head = head.map(field => this.format.underline(field)); -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; + // + const rows = [head].concat(body); -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} + // get column widths + const cols = []; + for (let i = 0; i < head.length; i++) { + const widths = rows.map(row => this.format.stripColor(row[i]).length); + cols[i] = Math.max(...widths); + } -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} + // + const builtRows = rows.map(row => { + for (let i = 0; i < row.length; i++) { + const field = row[i]; + const padding = cols[i] - this.format.stripColor(field).length; -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} + row[i] = field + ' '.repeat(padding); + } + return row.join(' '); + }); + this.log(builtRows.join('\n')); + } -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; + step(current, total, msg, emoji) { + msg = this._prependEmoji(msg, emoji); - var parts = []; - var m = balanced('{', '}', str); + if (msg.endsWith('?')) { + msg = `${(0, (_misc || _load_misc()).removeSuffix)(msg, '?')}...?`; + } else { + msg += '...'; + } - if (!m) - return str.split(','); + this.log(`${this.format.dim(`[${current}/${total}]`)} ${msg}`); + } - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); + inspect(value) { + if (typeof value !== 'number' && typeof value !== 'string') { + value = inspect(value, { + breakLength: 0, + colors: true, + depth: null, + maxArrayLength: null + }); + } - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); + this.log('' + value); } - parts.push.apply(parts, p); - - return parts; -} + list(key, items, hints) { + const gutterWidth = (this._lastCategorySize || 2) - 1; -function expandTop(str) { - if (!str) - return []; + if (hints) { + for (const item of items) { + this._log(`${' '.repeat(gutterWidth)}- ${item}`); + this._log(` ${' '.repeat(gutterWidth)} ${hints[item]}`); + } + } else { + for (const item of items) { + this._log(`${' '.repeat(gutterWidth)}- ${item}`); + } + } + } - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); + header(command, pkg) { + this.log(this.format.bold(`${pkg.name} ${command} v${pkg.version}`)); } - return expand(escapeBraces(str), true).map(unescapeBraces); -} + footer(showPeakMemory) { + this.stopProgress(); -function identity(e) { - return e; -} + const totalTime = (this.getTotalTime() / 1000).toFixed(2); + let msg = `Done in ${totalTime}s.`; + if (showPeakMemory) { + const peakMemory = (this.peakMemory / 1024 / 1024).toFixed(2); + msg += ` Peak memory usage ${peakMemory}MB.`; + } + this.log(this._prependEmoji(msg, '✨')); + } -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} + log(msg) { + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$force = _ref.force; -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} + let force = _ref$force === undefined ? false : _ref$force; -function expand(str, isTop) { - var expansions = []; + this._lastCategorySize = 0; + this._log(msg, { force }); + } - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + _log(msg) { + var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref2$force = _ref2.force; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); + let force = _ref2$force === undefined ? false : _ref2$force; + + if (this.isSilent && !force) { + return; } - return [str]; + (0, (_util || _load_util()).clearLine)(this.stdout); + this.stdout.write(`${msg}\n`); } - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } + success(msg) { + this._logCategory('success', 'green', msg); } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. + error(msg) { + (0, (_util || _load_util()).clearLine)(this.stderr); + this.stderr.write(`${this.format.red('error')} ${msg}\n`); + } - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + info(msg) { + this._logCategory('info', 'blue', msg); + } - var N; + command(command) { + this.log(this.format.dim(`$ ${command}`)); + } - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); + warn(msg) { + (0, (_util || _load_util()).clearLine)(this.stderr); + this.stderr.write(`${this.format.yellow('warning')} ${msg}\n`); + } - N = []; + question(question) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; + if (!process.stdout.isTTY) { + return Promise.reject(new Error("Can't answer a question unless a user TTY")); + } + + return new Promise((resolve, reject) => { + read({ + prompt: `${this.format.dim('question')} ${question}: `, + silent: !!options.password, + output: this.stdout, + input: this.stdin + }, (err, answer) => { + if (err) { + if (err.message === 'canceled') { + process.exitCode = 1; + } + reject(err); + } else { + if (!answer && options.required) { + this.error(this.lang('answerRequired')); + resolve(this.question(question, options)); + } else { + resolve(answer); } } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); + }); + }); } + // handles basic tree output to console + tree(key, trees) { + // + const output = (_ref3, titlePrefix, childrenPrefix) => { + let name = _ref3.name, + children = _ref3.children, + hint = _ref3.hint, + color = _ref3.color; - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } - } + const formatter = this.format; + const out = (0, (_treeHelper || _load_treeHelper()).getFormattedOutput)({ + prefix: titlePrefix, + hint, + color, + name, + formatter + }); + this.stdout.write(out); - return expansions; -} + if (children && children.length) { + (0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(children), childrenPrefix, output); + } + }; + (0, (_treeHelper || _load_treeHelper()).recurseTree)((0, (_treeHelper || _load_treeHelper()).sortTrees)(trees), '', output); + } + activitySet(total, workers) { + if (!this.isTTY || this.noProgress) { + return super.activitySet(total, workers); + } + const spinners = []; + const reporterSpinners = this._spinners; -/***/ }), -/* 402 */ -/***/ (function(module, exports, __webpack_require__) { + for (let i = 1; i < workers; i++) { + this.log(''); + } -"use strict"; -/*! - * braces <https://github.com/jonschlinkert/braces> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT license. - */ + for (let i = 0; i < workers; i++) { + const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr, i); + reporterSpinners.add(spinner); + spinner.start(); + let prefix = null; + let current = 0; + const updatePrefix = () => { + spinner.setPrefix(`${this.format.dim(`[${current === 0 ? '-' : current}/${total}]`)} `); + }; + const clear = () => { + prefix = null; + current = 0; + updatePrefix(); + spinner.setText('waiting...'); + }; + clear(); + spinners.unshift({ + clear, -/** - * Module dependencies - */ + setPrefix(_current, _prefix) { + current = _current; + prefix = _prefix; + spinner.setText(prefix); + updatePrefix(); + }, -var expand = __webpack_require__(461); -var repeat = __webpack_require__(257); -var tokens = __webpack_require__(571); + tick(msg) { + if (prefix) { + msg = `${prefix}: ${msg}`; + } + spinner.setText(msg); + }, -/** - * Expose `braces` - */ + end() { + spinner.stop(); + reporterSpinners.delete(spinner); + } + }); + } -module.exports = function(str, options) { - if (typeof str !== 'string') { - throw new Error('braces expects a string'); + return { + spinners, + end: () => { + for (const spinner of spinners) { + spinner.end(); + } + readline.moveCursor(this.stdout, 0, -workers + 1); + } + }; } - return braces(str, options); -}; -/** - * Expand `{foo,bar}` or `{1..5}` braces in the - * given `string`. - * - * @param {String} `str` - * @param {Array} `arr` - * @param {Object} `options` - * @return {Array} - */ + activity() { + if (!this.isTTY) { + return { + tick() {}, + end() {} + }; + } + const reporterSpinners = this._spinners; -function braces(str, arr, options) { - if (str === '') { - return []; - } + const spinner = new (_spinnerProgress || _load_spinnerProgress()).default(this.stderr); + spinner.start(); - if (!Array.isArray(arr)) { - options = arr; - arr = []; - } + reporterSpinners.add(spinner); - var opts = options || {}; - arr = arr || []; + return { + tick(name) { + spinner.setText(name); + }, - if (typeof opts.nodupes === 'undefined') { - opts.nodupes = true; + end() { + spinner.stop(); + reporterSpinners.delete(spinner); + } + }; } - var fn = opts.fn; - var es6; + select(header, question, options) { + if (!this.isTTY) { + return Promise.reject(new Error("Can't answer a question unless a user TTY")); + } - if (typeof opts === 'function') { - fn = opts; - opts = {}; - } + const rl = readline.createInterface({ + input: this.stdin, + output: this.stdout, + terminal: true + }); - if (!(patternRe instanceof RegExp)) { - patternRe = patternRegex(); - } + const questions = options.map(opt => opt.name); + const answers = options.map(opt => opt.value); - var matches = str.match(patternRe) || []; - var m = matches[0]; + function toIndex(input) { + const index = answers.indexOf(input); - switch(m) { - case '\\,': - return escapeCommas(str, arr, opts); - case '\\.': - return escapeDots(str, arr, opts); - case '\/.': - return escapePaths(str, arr, opts); - case ' ': - return splitWhitespace(str); - case '{,}': - return exponential(str, opts, braces); - case '{}': - return emptyBraces(str, arr, opts); - case '\\{': - case '\\}': - return escapeBraces(str, arr, opts); - case '${': - if (!/\{[^{]+\{/.test(str)) { - return arr.concat(str); + if (index >= 0) { + return index; } else { - es6 = true; - str = tokens.before(str, es6Regex()); + return +input; } - } - - if (!(braceRe instanceof RegExp)) { - braceRe = braceRegex(); - } + } - var match = braceRe.exec(str); - if (match == null) { - return [str]; - } + return new Promise(resolve => { + this.info(header); - var outter = match[1]; - var inner = match[2]; - if (inner === '') { return [str]; } + for (let i = 0; i < questions.length; i++) { + this.log(` ${this.format.dim(`${i + 1})`)} ${questions[i]}`); + } - var segs, segsLength; + const ask = () => { + rl.question(`${question}: `, input => { + let index = toIndex(input); - if (inner.indexOf('..') !== -1) { - segs = expand(inner, opts, fn) || inner.split(','); - segsLength = segs.length; + if (isNaN(index)) { + this.log('Not a number'); + ask(); + return; + } - } else if (inner[0] === '"' || inner[0] === '\'') { - return arr.concat(str.split(/['"]/).join('')); + if (index <= 0 || index > options.length) { + this.log('Outside answer range'); + ask(); + return; + } - } else { - segs = inner.split(','); - if (opts.makeRe) { - return braces(str.replace(outter, wrap(segs, '|')), opts); - } + // get index + index--; + rl.close(); + resolve(answers[index]); + }); + }; - segsLength = segs.length; - if (segsLength === 1 && opts.bash) { - segs[0] = wrap(segs[0], '\\'); - } + ask(); + }); } - var len = segs.length; - var i = 0, val; - - while (len--) { - var path = segs[i++]; - - if (/(\.[^.\/])/.test(path)) { - if (segsLength > 1) { - return segs; - } else { - return [str]; - } + progress(count) { + if (this.noProgress || count <= 0) { + return function () { + // noop + }; } - val = splice(str, outter, path); - - if (/\{[^{}]+?\}/.test(val)) { - arr = braces(val, arr, opts); - } else if (val !== '') { - if (opts.nodupes && arr.indexOf(val) !== -1) { continue; } - arr.push(es6 ? tokens.after(val) : val); + if (!this.isTTY) { + return function () { + // TODO what should the behaviour here be? we could buffer progress messages maybe + }; } - } - - if (opts.strict) { return filter(arr, filterEmpty); } - return arr; -} -/** - * Expand exponential ranges - * - * `a{,}{,}` => ['a', 'a', 'a', 'a'] - */ + // Clear any potentiall old progress bars + this.stopProgress(); -function exponential(str, options, fn) { - if (typeof options === 'function') { - fn = options; - options = null; - } + const bar = this._progressBar = new (_progressBar || _load_progressBar()).default(count, this.stderr, progress => { + if (progress === this._progressBar) { + this._progressBar = null; + } + }); - var opts = options || {}; - var esc = '__ESC_EXP__'; - var exp = 0; - var res; + bar.render(); - var parts = str.split('{,}'); - if (opts.nodupes) { - return fn(parts.join(''), opts); + return function () { + bar.tick(); + }; } - exp = parts.length - 1; - res = fn(parts.join(esc), opts); - var len = res.length; - var arr = []; - var i = 0; - - while (len--) { - var ele = res[i++]; - var idx = ele.indexOf(esc); + stopProgress() { + if (this._progressBar) { + this._progressBar.stop(); + } + } - if (idx === -1) { - arr.push(ele); + prompt(message, choices) { + var _this = this; - } else { - ele = ele.split('__ESC_EXP__').join(''); - if (!!ele && opts.nodupes !== false) { - arr.push(ele); + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + if (!process.stdout.isTTY) { + return Promise.reject(new Error("Can't answer a question unless a user TTY")); + } - } else { - var num = Math.pow(2, exp); - arr.push.apply(arr, repeat(ele, num)); + let pageSize; + if (process.stdout instanceof tty.WriteStream) { + pageSize = process.stdout.rows - 2; } - } - } - return arr; -} -/** - * Wrap a value with parens, brackets or braces, - * based on the given character/separator. - * - * @param {String|Array} `val` - * @param {String} `ch` - * @return {String} - */ + const rl = readline.createInterface({ + input: _this.stdin, + output: _this.stdout, + terminal: true + }); -function wrap(val, ch) { - if (ch === '|') { - return '(' + val.join(ch) + ')'; - } - if (ch === ',') { - return '{' + val.join(ch) + '}'; - } - if (ch === '-') { - return '[' + val.join(ch) + ']'; - } - if (ch === '\\') { - return '\\{' + val + '\\}'; - } -} + // $FlowFixMe: Need to update the type of Inquirer + const prompt = (_inquirer || _load_inquirer()).default.createPromptModule({ + input: _this.stdin, + output: _this.stdout + }); -/** - * Handle empty braces: `{}` - */ + let rejectRef = function () {}; + const killListener = function () { + rejectRef(); + }; -function emptyBraces(str, arr, opts) { - return braces(str.split('{}').join('\\{\\}'), arr, opts); -} + const handleKillFromInquirer = new Promise(function (resolve, reject) { + rejectRef = reject; + }); -/** - * Filter out empty-ish values - */ + rl.addListener('SIGINT', killListener); -function filterEmpty(ele) { - return !!ele && ele !== '\\'; -} + var _options$name = options.name; + const name = _options$name === undefined ? 'prompt' : _options$name; + var _options$type = options.type; + const type = _options$type === undefined ? 'input' : _options$type, + validate = options.validate; -/** - * Handle patterns with whitespace - */ + const answers = yield Promise.race([prompt([{ name, type, message, choices, pageSize, validate }]), handleKillFromInquirer]); -function splitWhitespace(str) { - var segs = str.split(' '); - var len = segs.length; - var res = []; - var i = 0; + rl.removeListener('SIGINT', killListener); + rl.close(); - while (len--) { - res.push.apply(res, braces(segs[i++])); + return answers[name]; + })(); } - return res; } +exports.default = ConsoleReporter; -/** - * Handle escaped braces: `\\{foo,bar}` - */ +/***/ }), +/* 422 */ +/***/ (function(module, exports, __webpack_require__) { -function escapeBraces(str, arr, opts) { - if (!/\{[^{]+\{/.test(str)) { - return arr.concat(str.split('\\').join('')); - } else { - str = str.split('\\{').join('__LT_BRACE__'); - str = str.split('\\}').join('__RT_BRACE__'); - return map(braces(str, arr, opts), function(ele) { - ele = ele.split('__LT_BRACE__').join('{'); - return ele.split('__RT_BRACE__').join('}'); - }); - } -} +"use strict"; -/** - * Handle escaped dots: `{1\\.2}` - */ -function escapeDots(str, arr, opts) { - if (!/[^\\]\..+\\\./.test(str)) { - return arr.concat(str.split('\\').join('')); - } else { - str = str.split('\\.').join('__ESC_DOT__'); - return map(braces(str, arr, opts), function(ele) { - return ele.split('__ESC_DOT__').join('.'); - }); - } -} +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sortTrees = sortTrees; +exports.recurseTree = recurseTree; +exports.getFormattedOutput = getFormattedOutput; -/** - * Handle escaped dots: `{1\\.2}` - */ -function escapePaths(str, arr, opts) { - str = str.split('\/.').join('__ESC_PATH__'); - return map(braces(str, arr, opts), function(ele) { - return ele.split('__ESC_PATH__').join('\/.'); +// public + + +// types +function sortTrees(trees) { + return trees.sort(function (tree1, tree2) { + return tree1.name.localeCompare(tree2.name); }); } -/** - * Handle escaped commas: `{a\\,b}` - */ - -function escapeCommas(str, arr, opts) { - if (!/\w,/.test(str)) { - return arr.concat(str.split('\\').join('')); - } else { - str = str.split('\\,').join('__ESC_COMMA__'); - return map(braces(str, arr, opts), function(ele) { - return ele.split('__ESC_COMMA__').join(','); - }); +function recurseTree(tree, prefix, recurseFunc) { + const treeLen = tree.length; + const treeEnd = treeLen - 1; + for (let i = 0; i < treeLen; i++) { + const atEnd = i === treeEnd; + recurseFunc(tree[i], prefix + getLastIndentChar(atEnd), prefix + getNextIndentChar(atEnd)); } } -/** - * Regex for common patterns - */ - -function patternRegex() { - return /\${|( (?=[{,}])|(?=[{,}]) )|{}|{,}|\\,(?=.*[{}])|\/\.(?=.*[{}])|\\\.(?={)|\\{|\\}/; +function getFormattedOutput(fmt) { + const item = formatColor(fmt.color, fmt.name, fmt.formatter); + const suffix = getSuffix(fmt.hint, fmt.formatter); + return `${fmt.prefix}─ ${item}${suffix}\n`; } -/** - * Braces regex. - */ +function getNextIndentChar(end) { + return end ? ' ' : '│ '; +} -function braceRegex() { - return /.*(\\?\{([^}]+)\})/; +function getLastIndentChar(end) { + return end ? 'â””' : '├'; } -/** - * es6 delimiter regex. - */ +function getSuffix(hint, formatter) { + return hint ? ` (${formatter.grey(hint)})` : ''; +} -function es6Regex() { - return /\$\{([^}]+)\}/; +function formatColor(color, strToFormat, formatter) { + return color ? formatter[color](strToFormat) : strToFormat; } -var braceRe; -var patternRe; +/***/ }), +/* 423 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Faster alternative to `String.replace()` when the - * index of the token to be replaces can't be supplied - */ +"use strict"; -function splice(str, token, replacement) { - var i = str.indexOf(token); - return str.substr(0, i) + replacement - + str.substr(i + token.length); + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _util; + +function _load_util() { + return _util = __webpack_require__(160); } -/** - * Fast array map - */ +class ProgressBar { + constructor(total) { + let stdout = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.stderr; + let callback = arguments[2]; -function map(arr, fn) { - if (arr == null) { - return []; + this.stdout = stdout; + this.total = total; + this.chars = ProgressBar.bars[0]; + this.delay = 60; + this.curr = 0; + this._callback = callback; + (0, (_util || _load_util()).clearLine)(stdout); } - var len = arr.length; - var res = new Array(len); - var i = -1; + tick() { + if (this.curr >= this.total) { + return; + } - while (++i < len) { - res[i] = fn(arr[i], i, arr); + this.curr++; + + // schedule render + if (!this.id) { + this.id = setTimeout(() => this.render(), this.delay); + } } - return res; -} + cancelTick() { + if (this.id) { + clearTimeout(this.id); + this.id = null; + } + } -/** - * Fast array filter - */ + stop() { + // "stop" by setting current to end so `tick` becomes noop + this.curr = this.total; -function filter(arr, cb) { - if (arr == null) return []; - if (typeof cb !== 'function') { - throw new TypeError('braces: filter expects a callback function.'); + this.cancelTick(); + (0, (_util || _load_util()).clearLine)(this.stdout); + if (this._callback) { + this._callback(this); + } } - var len = arr.length; - var res = arr.slice(); - var i = 0; + render() { + // clear throttle + this.cancelTick(); - while (len--) { - if (!cb(arr[len], i++)) { - res.splice(len, 1); - } + let ratio = this.curr / this.total; + ratio = Math.min(Math.max(ratio, 0), 1); + + // progress without bar + let bar = ` ${this.curr}/${this.total}`; + + // calculate size of actual bar + // $FlowFixMe: investigate process.stderr.columns flow error + const availableSpace = Math.max(0, this.stdout.columns - bar.length - 1); + const width = Math.min(this.total, availableSpace); + const completeLength = Math.round(width * ratio); + const complete = this.chars[0].repeat(completeLength); + const incomplete = this.chars[1].repeat(width - completeLength); + bar = `${complete}${incomplete}${bar}`; + + (0, (_util || _load_util()).toStartOfLine)(this.stdout); + this.stdout.write(bar); } - return res; } - +exports.default = ProgressBar; +ProgressBar.bars = [['â–ˆ', 'â–‘']]; /***/ }), -/* 403 */ +/* 424 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var blacklist = [ - 'freelist', - 'sys' -]; +Object.defineProperty(exports, "__esModule", { + value: true +}); -module.exports = Object.keys(process.binding('natives')).filter(function (el) { - return !/^_|^internal|\//.test(el) && blacklist.indexOf(el) === -1; -}).sort(); +var _util; +function _load_util() { + return _util = __webpack_require__(160); +} -/***/ }), -/* 404 */ -/***/ (function(module, exports, __webpack_require__) { +class Spinner { + constructor() { + let stdout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : process.stderr; + let lineNumber = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; -"use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ + this.current = 0; + this.prefix = ''; + this.lineNumber = lineNumber; + this.stdout = stdout; + this.delay = 60; + this.chars = Spinner.spinners[28].split(''); + this.text = ''; + this.id = null; + } + setPrefix(prefix) { + this.prefix = prefix; + } + setText(text) { + this.text = text; + } + start() { + this.current = 0; + this.render(); + } + render() { + if (this.id) { + clearTimeout(this.id); + } + // build line ensuring we don't wrap to the next line + let msg = `${this.prefix}${this.chars[this.current]} ${this.text}`; + const columns = typeof this.stdout.columns === 'number' ? this.stdout.columns : 100; + msg = msg.slice(0, columns); + (0, (_util || _load_util()).writeOnNthLine)(this.stdout, this.lineNumber, msg); + this.current = ++this.current % this.chars.length; + this.id = setTimeout(() => this.render(), this.delay); + } + stop() { + if (this.id) { + clearTimeout(this.id); + this.id = null; + } + (0, (_util || _load_util()).clearNthLine)(this.stdout, this.lineNumber); + } +} +exports.default = Spinner; +Spinner.spinners = ['|/-\\', 'â ‚-–—–-', 'â—â—“â—‘â—’', '◴◷◶◵', '◰◳◲◱', 'â––â–˜â–â–—', '■□▪▫', '▌▀â–â–„', '▉▊▋▌â–â–Žâ–â–Žâ–▌▋▊▉', 'â–▃▄▅▆▇█▇▆▅▄▃', 'â†â†–↑↗→↘↓↙', '┤┘┴└├┌┬â”', '◢◣◤◥', '.oO°Oo.', '.oO@*', 'ðŸŒðŸŒŽðŸŒ', 'â—¡â—¡ ⊙⊙ â— â— ', '☱☲☴', '⠋⠙⠹⠸⠼⠴⠦⠧⠇â ', '⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓', '⠄⠆⠇⠋⠙⠸⠰â ⠰⠸⠙⠋⠇⠆', '⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒â â â ’â “â ‹', 'â ⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉â ', '⠈⠉⠋⠓⠒â â ⠒⠖⠦⠤â â ⠤⠦⠖⠒â â ⠒⠓⠋⠉⠈', 'â â ⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤â â ⠤⠦⠖⠒â â ⠒⠓⠋⠉⠈⠈', '⢄⢂â¢â¡â¡ˆâ¡â¡ ', '⢹⢺⢼⣸⣇⡧⡗â¡', '⣾⣽⣻⢿⡿⣟⣯⣷', 'â ⠂⠄⡀⢀â â â ˆ']; +/***/ }), +/* 425 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Module exports. - * @public - */ +"use strict"; -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; -/** - * Module variables. - * @private - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; +var _jsonReporter; -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; +function _load_jsonReporter() { + return _jsonReporter = _interopRequireDefault(__webpack_require__(161)); +} -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: ((1 << 30) * 1024) -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -// TODO: use is-finite module? -var numberIsFinite = Number.isFinite || function (v) { return typeof v === 'number' && isFinite(v); }; +var _require = __webpack_require__(46); -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i; +const EventEmitter = _require.EventEmitter; +class EventReporter extends (_jsonReporter || _load_jsonReporter()).default { -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ + constructor(opts) { + super(opts); -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); + // $FlowFixMe: looks like a flow bug + EventEmitter.call(this); } - if (typeof value === 'number') { - return format(value, options); + _dump(type, data) { + this.emit(type, data); } - - return null; } -/** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public - */ +exports.default = EventReporter; +Object.assign(EventReporter.prototype, EventEmitter.prototype); -function format(value, options) { - if (!numberIsFinite(value)) { - return null; - } +/***/ }), +/* 426 */ +/***/ (function(module, exports, __webpack_require__) { - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; +"use strict"; - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'kB'; - } else { - unit = 'B'; - } - } - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); +Object.defineProperty(exports, "__esModule", { + value: true +}); - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); - } +/* eslint max-len: 0 */ - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); - } +const messages = { + upToDate: 'Already up-to-date.', + folderInSync: 'Folder in sync.', + nothingToInstall: 'Nothing to install.', + resolvingPackages: 'Resolving packages', + checkingManifest: 'Validating package.json', + fetchingPackages: 'Fetching packages', + linkingDependencies: 'Linking dependencies', + rebuildingPackages: 'Rebuilding all packages', + buildingFreshPackages: 'Building fresh packages', + cleaningModules: 'Cleaning modules', + bumpingVersion: 'Bumping version', + savingHar: 'Saving HAR file: $0', + answer: 'Answer?', + usage: 'Usage', + installCommandRenamed: '`install` has been replaced with `add` to add new dependencies. Run $0 instead.', + globalFlagRemoved: '`--global` has been deprecated. Please run $0 instead.', + waitingInstance: 'Waiting for the other yarn instance to finish (pid $0, inside $1)', + waitingNamedInstance: 'Waiting for the other yarn instance to finish ($0)', + offlineRetrying: 'There appears to be trouble with your network connection. Retrying...', + clearedCache: 'Cleared cache.', + couldntClearPackageFromCache: "Couldn't clear package $0 from cache", + clearedPackageFromCache: 'Cleared package $0 from cache', + packWroteTarball: 'Wrote tarball to $0.', - return str + unitSeparator + unit; -} + helpExamples: ' Examples:\n$0\n', + helpCommands: ' Commands:\n$0\n', + helpCommandsMore: ' Run `$0` for more information on specific commands.', + helpLearnMore: ' Visit $0 to learn more about Yarn.\n', -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ + manifestPotentialTypo: 'Potential typo $0, did you mean $1?', + manifestBuiltinModule: '$0 is also the name of a node core module', + manifestNameDot: "Name can't start with a dot", + manifestNameIllegalChars: 'Name contains illegal characters', + manifestNameBlacklisted: 'Name is blacklisted', + manifestLicenseInvalid: 'License should be a valid SPDX license expression', + manifestLicenseNone: 'No license field', + manifestStringExpected: '$0 is not a string', + manifestDependencyCollision: '$0 has dependency $1 with range $2 that collides with a dependency in $3 of the same name with version $4', + manifestDirectoryNotFound: 'Unable to read $0 directory of module $1', -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; - } + verboseFileCopy: 'Copying $0 to $1.', + verboseFileLink: 'Creating hardlink at $0 to $1.', + verboseFileSymlink: 'Creating symlink at $0 to $1.', + verboseFileSkip: 'Skipping copying of file $0 as the file at $1 is the same size ($2) and mtime ($3).', + verboseFileSkipSymlink: 'Skipping copying of $0 as the file at $1 is the same symlink ($2).', + verboseFileSkipHardlink: 'Skipping copying of $0 as the file at $1 is the same hardlink ($2).', + verboseFileRemoveExtraneous: 'Removing extraneous file $0.', + verboseFilePhantomExtraneous: "File $0 would be marked as extraneous but has been removed as it's listed as a phantom file.", + verboseFileFolder: 'Creating directory $0.', - if (typeof val !== 'string') { - return null; - } + verboseRequestStart: 'Performing $0 request to $1.', + verboseRequestFinish: 'Request $0 finished with status code $1.', - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; + configSet: 'Set $0 to $1.', + configDelete: 'Deleted $0.', + configNpm: 'npm config', + configYarn: 'yarn config', - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); - } + couldntFindPackagejson: "Couldn't find a package.json file in $0", + couldntFindMatch: "Couldn't find match for $0 in $1 for $2.", + couldntFindPackageInCache: "Couldn't find any versions for $0 that matches $1 in our cache (possible versions are $2). This is usually caused by a missing entry in the lockfile, running Yarn without the --offline flag may help fix this issue.", + couldntFindVersionThatMatchesRange: "Couldn't find any versions for $0 that matches $1", + chooseVersionFromList: 'Please choose a version of $0 from this list:', + moduleNotInManifest: "This module isn't specified in a manifest.", + unknownFolderOrTarball: "Passed folder/tarball doesn't exist,", + unknownPackage: "Couldn't find package $0.", + unknownPackageName: "Couldn't find package name.", + unknownUser: "Couldn't find user $0.", + unknownRegistryResolver: 'Unknown registry resolver $0', + userNotAnOwner: "User $0 isn't an owner of this package.", + invalidVersionArgument: 'Use the $0 flag to create a new version.', + invalidVersion: 'Invalid version supplied.', + requiredVersionInRange: 'Required version in range.', + packageNotFoundRegistry: "Couldn't find package $0 on the $1 registry.", + doesntExist: "$0 doesn't exist.", + missingRequiredPackageKey: `Package $0 doesn't have a $1.`, + invalidAccess: 'Invalid argument for access, expected public or restricted.', + invalidCommand: 'Invalid subcommand. Try $0', + invalidGistFragment: 'Invalid gist fragment $0.', + invalidHostedGitFragment: 'Invalid hosted git fragment $0.', + invalidFragment: 'Invalid fragment $0.', + invalidPackageName: 'Invalid package name.', + couldntFindManifestIn: "Couldn't find manifest in $0.", + shrinkwrapWarning: 'npm-shrinkwrap.json found. This will not be updated or respected. See https://yarnpkg.com/en/docs/migrating-from-npm for more information.', + lockfileOutdated: 'Outdated lockfile. Please run `yarn install` and try again.', + lockfileMerged: 'Merge conflict detected in yarn.lock and successfully merged.', + lockfileConflict: 'A merge conflict was found in yarn.lock but it could not be successfully merged, regenerating yarn.lock from scratch.', + ignoredScripts: 'Ignored scripts due to flag.', + missingAddDependencies: 'Missing list of packages to add to your project.', + yesWarning: 'The yes flag has been set. This will automatically answer yes to all questions which may have security implications.', + networkWarning: "You don't appear to have an internet connection. Try the --offline flag to use the cache for registry queries.", + flatGlobalError: 'The package $0@$1 requires a flat dependency graph. Add `"flat": true` to your package.json and try again.', + noName: `Package doesn't have a name.`, + noVersion: `Package doesn't have a version.`, + answerRequired: 'An answer is required.', + missingWhyDependency: 'Missing package name, folder or path to file to identify why a package has been installed', + bugReport: 'If you think this is a bug, please open a bug report with the information provided in $0.', + unexpectedError: 'An unexpected error occurred: $0.', + jsonError: 'Error parsing JSON at $0, $1.', + noPermission: 'Cannot create $0 due to insufficient permissions.', + noGlobalFolder: 'Cannot find a suitable global folder. Tried these: $0', + allDependenciesUpToDate: 'All of your dependencies are up to date.', + legendColorsForUpgradeInteractive: 'Color legend : \n $0 : Major Update backward-incompatible updates \n $1 : Minor Update backward-compatible features \n $2 : Patch Update backward-compatible bug fixes', + frozenLockfileError: 'Your lockfile needs to be updated, but yarn was run with `--frozen-lockfile`.', + fileWriteError: 'Could not write file $0: $1', + multiplePackagesCantUnpackInSameDestination: 'Pattern $0 is trying to unpack in the same destination $1 as pattern $2. This could result in a non deterministic behavior, skipping.', + incorrectLockfileEntry: 'Lockfile has incorrect entry for $0. Ignoring it.', - return Math.floor(map[unit] * floatValue); -} + invalidResolutionName: 'Resolution field $0 does not end with a valid package name and will be ignored', + invalidResolutionVersion: 'Resolution field $0 has an invalid version entry and may be ignored', + incompatibleResolutionVersion: 'Resolution field $0 is incompatible with requested version $1', + yarnOutdated: "Your current version of Yarn is out of date. The latest version is $0 while you're on $1.", + yarnOutdatedInstaller: 'To upgrade, download the latest installer at $0.', + yarnOutdatedCommand: 'To upgrade, run the following command:', -/***/ }), -/* 405 */ -/***/ (function(module, exports, __webpack_require__) { + tooManyArguments: 'Too many arguments, maximum of $0.', + tooFewArguments: 'Not enough arguments, expected at least $0.', + noArguments: "This command doesn't require any arguments.", -"use strict"; + ownerRemoving: 'Removing owner $0 from package $1.', + ownerRemoved: 'Owner removed.', + ownerRemoveError: "Couldn't remove owner.", + ownerGetting: 'Getting owners for package $0', + ownerGettingFailed: "Couldn't get list of owners.", + ownerAlready: 'This user is already an owner of this package.', + ownerAdded: 'Added owner.', + ownerAdding: 'Adding owner $0 to package $1', + ownerAddingFailed: "Couldn't add owner.", + ownerNone: 'No owners.', + teamCreating: 'Creating team', + teamRemoving: 'Removing team', + teamAddingUser: 'Adding user to team', + teamRemovingUser: 'Removing user from team', + teamListing: 'Listing teams', -function preserveCamelCase(str) { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; + cleaning: 'Cleaning modules', + cleanCreatingFile: 'Creating $0', + cleanCreatedFile: 'Created $0. Please review the contents of this file then run "yarn autoclean --force" to perform a clean.', + cleanAlreadyExists: '$0 already exists. To revert to the default file, delete $0 then rerun this command.', + cleanRequiresForce: 'This command required the "--force" flag to perform the clean. This is a destructive operation. Files specified in $0 will be deleted.', + cleanDoesNotExist: '$0 does not exist. Autoclean will delete files specified by $0. Run "autoclean --init" to create $0 with the default entries.', - for (let i = 0; i < str.length; i++) { - const c = str[i]; + binLinkCollision: "There's already a linked binary called $0 in your global Yarn bin. Could not link this package's $0 bin entry.", + linkCollision: "There's already a module called $0 registered.", + linkMissing: 'No registered module found called $0.', + linkRegistered: 'Registered $0.', + linkRegisteredMessage: 'You can now run `yarn link $0` in the projects where you want to use this module and it will be used instead.', + linkUnregistered: 'Unregistered $0.', + linkUnregisteredMessage: 'You can now run `yarn unlink $0` in the projects where you no longer want to use this module.', + linkUsing: 'Using linked module for $0.', + linkDisusing: 'Removed linked module $0.', + linkDisusingMessage: 'You will need to run `yarn` to re-install the package that was linked.', - if (isLastCharLower && /[a-zA-Z]/.test(c) && c.toUpperCase() === c) { - str = str.substr(0, i) + '-' + str.substr(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(c) && c.toLowerCase() === c) { - str = str.substr(0, i - 1) + '-' + str.substr(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = c.toLowerCase() === c; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = c.toUpperCase() === c; - } - } + createInvalidBin: 'Invalid bin entry found in package $0.', + createMissingPackage: 'Package not found - this is probably an internal error, and should be reported at https://github.com/yarnpkg/yarn/issues.', - return str; -} + workspacesPreferDevDependencies: "You're trying to add a regular dependency to a workspace root, which is probably a mistake (do you want to run this command inside a workspace?). If this dependency really should be in your workspace root, use the --dev flag to add it to your devDependencies.", + workspacesRequirePrivateProjects: 'Workspaces can only be enabled in private projects', + workspacesDisabled: 'Your project root defines workspaces but the feature is disabled in your Yarn config. Please check "workspaces-experimental" in your .yarnrc file.', + workspaceRootNotFound: "Cannot find the root of your workspace - are you sure you're currently in a workspace?", + workspaceMissingWorkspace: 'Missing workspace name.', + workspaceMissingCommand: 'Missing command name.', + workspaceUnknownWorkspace: 'Unknown workspace $0.', + workspaceVersionMandatory: 'Missing version in workspace at $0, ignoring.', + workspaceNameMandatory: 'Missing name in workspace at $0, ignoring.', + workspaceNameDuplicate: 'There are more than one workspace with name $0', -module.exports = function (str) { - if (arguments.length > 1) { - str = Array.from(arguments) - .map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - str = str.trim(); - } + cacheFolderSkipped: 'Skipping preferred cache folder $0 because it is not writable.', + cacheFolderMissing: "Yarn hasn't been able to find a cache folder it can use. Please use the explicit --cache-folder option to tell it what location to use, or make one of the preferred locations writable.", + cacheFolderSelected: 'Selected the next writable cache folder in the list, will be $0.', + + execMissingCommand: 'Missing command name.', + + dashDashDeprecation: `From Yarn 1.0 onwards, scripts don't require "--" for options to be forwarded. In a future version, any explicit "--" will be forwarded as-is to the scripts.`, + commandNotSpecified: 'No command specified.', + binCommands: 'Commands available from binary scripts: ', + possibleCommands: 'Project commands', + commandQuestion: 'Which command would you like to run?', + commandFailedWithCode: 'Command failed with exit code $0.', + commandFailedWithSignal: 'Command failed with signal $0.', + packageRequiresNodeGyp: 'This package requires node-gyp, which is not currently installed. Yarn will attempt to automatically install it. If this fails, you can run "yarn global add node-gyp" to manually install it.', + nodeGypAutoInstallFailed: 'Failed to auto-install node-gyp. Please run "yarn global add node-gyp" manually. Error: $0', - if (str.length === 0) { - return ''; - } + foundIncompatible: 'Found incompatible module', + incompatibleEngine: 'The engine $0 is incompatible with this module. Expected version $1.', + incompatibleCPU: 'The CPU architecture $0 is incompatible with this module.', + incompatibleOS: 'The platform $0 is incompatible with this module.', + invalidEngine: 'The engine $0 appears to be invalid.', - if (str.length === 1) { - return str.toLowerCase(); - } + optionalCompatibilityExcluded: '$0 is an optional dependency and failed compatibility check. Excluding it from installation.', + optionalModuleFail: 'This module is OPTIONAL, you can safely ignore this error', + optionalModuleScriptFail: 'Error running install script for optional dependency: $0', + optionalModuleCleanupFail: 'Could not cleanup build artifacts from failed install: $0', - if (/^[a-z0-9]+$/.test(str)) { - return str; - } + unmetPeer: '$0 has unmet peer dependency $1.', + incorrectPeer: '$0 has incorrect peer dependency $1.', + missingBundledDependency: '$0 is missing a bundled dependency $1. This should be reported to the package maintainer.', - const hasUpperCase = str !== str.toLowerCase(); + savedNewDependency: 'Saved 1 new dependency.', + savedNewDependencies: 'Saved $0 new dependencies.', - if (hasUpperCase) { - str = preserveCamelCase(str); - } + foundWarnings: 'Found $0 warnings.', + foundErrors: 'Found $0 errors.', - return str - .replace(/^[_.\- ]+/, '') - .toLowerCase() - .replace(/[_.\- ]+(\w|$)/g, (m, p1) => p1.toUpperCase()); -}; + notSavedLockfileNoDependencies: 'Lockfile not saved, no dependencies.', + savedLockfile: 'Saved lockfile.', + noRequiredLockfile: 'No lockfile in this directory. Run `yarn install` to generate one.', + noLockfileFound: 'No lockfile found.', -/***/ }), -/* 406 */ -/***/ (function(module, exports, __webpack_require__) { + invalidSemver: 'Invalid semver version', + newVersion: 'New version', + currentVersion: 'Current version', -"use strict"; + manualVersionResolution: 'Unable to find a suitable version for $0, please choose one by typing one of the numbers below:', + manualVersionResolutionOption: '$0 which resolved to $1', -var argv = process.argv; + createdTag: 'Created tag.', + createdTagFail: "Couldn't add tag.", + deletedTag: 'Deleted tag.', + deletedTagFail: "Couldn't delete tag.", + gettingTags: 'Getting tags', + deletingTags: 'Deleting tag', + creatingTag: 'Creating tag $0 = $1', -var terminator = argv.indexOf('--'); -var hasFlag = function (flag) { - flag = '--' + flag; - var pos = argv.indexOf(flag); - return pos !== -1 && (terminator !== -1 ? pos < terminator : true); -}; + whyStart: 'Why do we have the module $0?', + whyFinding: 'Finding dependency', + whyCalculating: 'Calculating file sizes', + whyUnknownMatch: "We couldn't find a match!", + whyInitGraph: 'Initialising dependency graph', + whyWhoKnows: "We don't know why this module exists", + whyDiskSizeWithout: 'Disk size without dependencies: $0', + whyDiskSizeUnique: 'Disk size with unique dependencies: $0', + whyDiskSizeTransitive: 'Disk size with transitive dependencies: $0', + whySharedDependencies: 'Number of shared dependencies: $0', + whyHoistedTo: `Has been hoisted to $0`, -module.exports = (function () { - if ('FORCE_COLOR' in process.env) { - return true; - } + whyHoistedFromSimple: `This module exists because it's hoisted from $0.`, + whyDependedOnSimple: `This module exists because $0 depends on it.`, + whySpecifiedSimple: `This module exists because it's specified in $0.`, + whyReasons: 'Reasons this module exists', + whyHoistedFrom: 'Hoisted from $0', + whyDependedOn: '$0 depends on it', + whySpecified: `Specified in $0`, - if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false')) { - return false; - } + uninstalledPackages: 'Uninstalled packages.', + uninstallRegenerate: 'Regenerating lockfile and installing missing dependencies', - if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - return true; - } + cleanRemovedFiles: 'Removed $0 files', + cleanSavedSize: 'Saved $0 MB.', - if (process.stdout && !process.stdout.isTTY) { - return false; - } + configFileFound: 'Found configuration file $0.', + configPossibleFile: 'Checking for configuration file $0.', - if (process.platform === 'win32') { - return true; - } + npmUsername: 'npm username', + npmPassword: 'npm password', + npmEmail: 'npm email', - if ('COLORTERM' in process.env) { - return true; - } + loggingIn: 'Logging in', + loggedIn: 'Logged in.', + notRevokingEnvToken: 'Not revoking login token, specified via environment variable.', + notRevokingConfigToken: 'Not revoking login token, specified via config file.', + noTokenToRevoke: 'No login token to revoke.', + revokingToken: 'Revoking token', + revokedToken: 'Revoked login token.', - if (process.env.TERM === 'dumb') { - return false; - } + loginAsPublic: 'Logging in as public', + incorrectCredentials: 'Incorrect username or password.', + clearedCredentials: 'Cleared login credentials.', - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } + publishFail: "Couldn't publish package.", + publishPrivate: 'Package marked as private, not publishing.', + published: 'Published.', + publishing: 'Publishing', - return false; -})(); + infoFail: 'Received invalid response from npm.', + malformedRegistryResponse: 'Received malformed response from registry for $0. The registry may be down.', + cantRequestOffline: "Can't make a request in offline mode ($0)", + requestManagerNotSetupHAR: 'RequestManager was not setup to capture HAR files', + requestError: 'Request $0 returned a $1', + requestFailed: 'Request failed $0', + tarballNotInNetworkOrCache: '$0: Tarball is not in network and can not be located in cache ($1)', + fetchBadHashWithPath: 'Fetch succeeded for $0. However, extracting $1 resulted in hash $2, which did not match the requested hash $3.', + fetchErrorCorrupt: '$0. Mirror tarball appears to be corrupt. You can resolve this by running:\n\n rm -rf $1\n yarn install', + errorDecompressingTarball: '$0. Error decompressing $1, it appears to be corrupt.', + updateInstalling: 'Installing $0...', + hostedGitResolveError: 'Error connecting to repository. Please, check the url.', + retryOnInternalServerError: 'There appears to be trouble with our server. Retrying...', -/***/ }), -/* 407 */ -/***/ (function(module, exports, __webpack_require__) { + unknownFetcherFor: 'Unknown fetcher for $0', -module.exports = chownr -chownr.sync = chownrSync + refusingDownloadGitWithoutCommit: 'Refusing to download the git repo $0 over plain git without a commit hash', + refusingDownloadHTTPWithoutCommit: 'Refusing to download the git repo $0 over HTTP without a commit hash', + refusingDownloadHTTPSWithoutCommit: 'Refusing to download the git repo $0 over HTTPS without a commit hash - possible certificate error?', -var fs = __webpack_require__(6) -, path = __webpack_require__(1) + packageInstalledWithBinaries: 'Installed $0 with binaries:', + packageHasBinaries: '$0 has binaries:', + packageHasNoBinaries: '$0 has no binaries', -function chownr (p, uid, gid, cb) { - fs.readdir(p, function (er, children) { - // any error other than ENOTDIR means it's not readable, or - // doesn't exist. give up. - if (er && er.code !== "ENOTDIR") return cb(er) - if (er || !children.length) return fs.chown(p, uid, gid, cb) + couldBeDeduped: '$0 could be deduped from $1 to $2', + lockfileNotContainPattern: 'Lockfile does not contain pattern: $0', + integrityCheckFailed: 'Integrity check failed', + noIntegrityFile: "Couldn't find an integrity file", + integrityFailedExpectedIsNotAJSON: 'Integrity check: integrity file is not a json', + integrityCheckLinkedModulesDontMatch: "Integrity check: Linked modules don't match", + integrityFlagsDontMatch: "Integrity check: Flags don't match", + integrityLockfilesDontMatch: "Integrity check: Lock files don't match", + integrityFailedFilesMissing: 'Integrity check: Files are missing', + integrityPatternsDontMatch: "Integrity check: Top level patterns don't match", + integrityModulesFoldersMissing: 'Integrity check: Some module folders are missing', + packageNotInstalled: '$0 not installed', + optionalDepNotInstalled: 'Optional dependency $0 not installed', + packageWrongVersion: '$0 is wrong version: expected $1, got $2', + packageDontSatisfy: "$0 doesn't satisfy found match of $1", - var len = children.length - , errState = null - children.forEach(function (child) { - var pathChild = path.resolve(p, child); - fs.lstat(pathChild, function(er, stats) { - if (er) - return cb(er) - if (!stats.isSymbolicLink()) - chownr(pathChild, uid, gid, then) - else - then() - }) - }) - function then (er) { - if (errState) return - if (er) return cb(errState = er) - if (-- len === 0) return fs.chown(p, uid, gid, cb) - } - }) -} + lockfileExists: 'Lockfile already exists, not importing.', + skippingImport: 'Skipping import of $0 for $1', + importFailed: 'Import of $0 for $1 failed, resolving normally.', + importResolveFailed: 'Import of $0 failed starting in $1', + importResolvedRangeMatch: 'Using version $0 of $1 instead of $2 for $3', + packageContainsYarnAsGlobal: 'Installing Yarn via Yarn will result in you having two separate versions of Yarn installed at the same time, which is not recommended. To update Yarn please follow https://yarnpkg.com/en/docs/install .', -function chownrSync (p, uid, gid) { - var children - try { - children = fs.readdirSync(p) - } catch (er) { - if (er && er.code === "ENOTDIR") return fs.chownSync(p, uid, gid) - throw er - } - if (!children.length) return fs.chownSync(p, uid, gid) + scopeNotValid: 'The specified scope is not valid.', - children.forEach(function (child) { - var pathChild = path.resolve(p, child) - var stats = fs.lstatSync(pathChild) - if (!stats.isSymbolicLink()) - chownrSync(pathChild, uid, gid) - }) - return fs.chownSync(p, uid, gid) -} + deprecatedCommand: '$0 is deprecated. Please use $1.', + implicitFileDeprecated: 'Using the "file:" protocol implicitly is deprecated. Please either the protocol or prepend the path $0 with "./".' +}; +exports.default = messages; /***/ }), -/* 408 */ +/* 427 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var env = process.env +Object.defineProperty(exports, "__esModule", { + value: true +}); -var vendors = [ - // Constant, Name, Envs - ['TRAVIS', 'Travis CI', 'TRAVIS'], - ['CIRCLE', 'CircleCI', 'CIRCLECI'], - ['GITLAB', 'GitLab CI', 'GITLAB_CI'], - ['APPVEYOR', 'AppVeyor', 'APPVEYOR'], - ['CODESHIP', 'Codeship', {CI_NAME: 'codeship'}], - ['DRONE', 'Drone', 'DRONE'], - ['MAGNUM', 'Magnum CI', 'MAGNUM'], - ['SEMAPHORE', 'Semaphore', 'SEMAPHORE'], - ['JENKINS', 'Jenkins', 'JENKINS_URL'], - ['BAMBOO', 'Bamboo', 'bamboo_planKey'], - ['TFS', 'Team Foundation Server', 'TF_BUILD'], - ['TEAMCITY', 'TeamCity', 'TEAMCITY_VERSION'], - ['BUILDKITE', 'Buildkite', 'BUILDKITE'], - ['HUDSON', 'Hudsun', 'HUDSON_URL'], - ['TASKCLUSTER', 'TaskCluster', 'TASK_ID', 'RUN_ID'], - ['GOCD', 'GoCD', 'GO_PIPELINE_LABEL'], - ['BITBUCKET', 'Bitbucket Pipelines', 'BITBUCKET_COMMIT'] -] +var _asyncToGenerator2; -exports.name = null +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} -vendors.forEach(function (vendor) { - var constant = vendor.shift() - var name = vendor.shift() - var isCI = vendor.every(function (obj) { - if (typeof obj === 'string') return !!env[obj] - return Object.keys(obj).every(function (k) { - return env[k] === obj[k] - }) - }) - exports[constant] = isCI - if (isCI) exports.name = name -}) +var _format; -exports.isCI = !!( - env.CI || // Travis CI, CircleCI, Gitlab CI, Appveyor, CodeShip - env.CONTINUOUS_INTEGRATION || // Travis CI - env.BUILD_NUMBER || // Jenkins, TeamCity - exports.name || - false -) +function _load_format() { + return _format = __webpack_require__(265); +} +var _index; -/***/ }), -/* 409 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_index() { + return _index = _interopRequireWildcard(__webpack_require__(266)); +} -"use strict"; +var _isCi; +function _load_isCi() { + return _isCi = _interopRequireDefault(__webpack_require__(213)); +} -exports = module.exports = cliWidth; +var _baseReporter; -function normalizeOpts(options) { - var defaultOpts = { - defaultWidth: 0, - output: process.stdout, - tty: __webpack_require__(116) - }; - if (!options) { - return defaultOpts; - } else { - Object.keys(defaultOpts).forEach(function (key) { - if (!options[key]) { - options[key] = defaultOpts[key]; - } - }); - return options; - } +function _load_baseReporter() { + return _baseReporter = _interopRequireDefault(__webpack_require__(77)); } -function cliWidth(options) { - var opts = normalizeOpts(options); - if (opts.output.getWindowSize) { - return opts.output.getWindowSize()[0] || opts.defaultWidth; - } - else { - if (opts.tty.getWindowSize) { - return opts.tty.getWindowSize()[1] || opts.defaultWidth; - } - else { - if (opts.output.columns) { - return opts.output.columns; - } - else { - if (process.env.CLI_WIDTH) { - var width = parseInt(process.env.CLI_WIDTH, 10); +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - if (!isNaN(width)) { - return width; - } - } - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return opts.defaultWidth; - } +class NoopReporter extends (_baseReporter || _load_baseReporter()).default { + lang(key) { + return 'do nothing'; } -}; - + verbose(msg) {} + verboseInspect(val) {} + initPeakMemoryCounter() {} + checkPeakMemory() {} + close() {} + getTotalTime() { + return 0; + } + list(key, items, hints) {} + tree(key, obj) {} + step(current, total, message, emoji) {} + error(message) {} + info(message) {} + warn(message) {} + success(message) {} + log(message) {} + command(command) {} + inspect(value) {} + header(command, pkg) {} + footer(showPeakMemory) {} + table(head, body) {} -/***/ }), -/* 410 */ -/***/ (function(module, exports, __webpack_require__) { + activity() { + return { + tick(name) {}, + end() {} + }; + } -// On windows, create a .cmd file. -// Read the #! in the file to see what it uses. The vast majority -// of the time, this will be either: -// "#!/usr/bin/env <prog> <args...>" -// or: -// "#!<prog> <args...>" -// -// Write a binroot/pkg.bin + ".cmd" file that has this line in it: -// @<prog> <args...> %~dp0<target> %* + activitySet(total, workers) { + return { + spinners: Array(workers).fill({ + clear() {}, + setPrefix() {}, + tick() {}, + end() {} + }), + end() {} + }; + } -module.exports = cmdShim -cmdShim.ifExists = cmdShimIfExists + question(question) { + let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -var fs = __webpack_require__(236) + return Promise.reject(new Error('Not implemented')); + } -var mkdir = __webpack_require__(160) - , path = __webpack_require__(1) - , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/ + questionAffirm(question) { + var _this = this; -function cmdShimIfExists (from, to, cb) { - fs.stat(from, function (er) { - if (er) return cb() - cmdShim(from, to, cb) - }) -} + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + yield _this.question(question); + return false; + })(); + } -// Try to unlink, but ignore errors. -// Any problems will surface later. -function rm (path, cb) { - fs.unlink(path, function(er) { - cb() - }) -} + select(header, question, options) { + return Promise.reject(new Error('Not implemented')); + } -function cmdShim (from, to, cb) { - fs.stat(from, function (er, stat) { - if (er) - return cb(er) + progress(total) { + return function () {}; + } - cmdShim_(from, to, cb) - }) -} + disableProgress() { + this.noProgress = true; + } -function cmdShim_ (from, to, cb) { - var then = times(2, next, cb) - rm(to, then) - rm(to + ".cmd", then) + prompt(message, choices) { + let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - function next(er) { - writeShim(from, to, cb) + return Promise.reject(new Error('Not implemented')); } } +exports.default = NoopReporter; +/* eslint no-unused-vars: 0 */ -function writeShim (from, to, cb) { - // make a cmd file and a sh script - // First, check if the bin is a #! of some sort. - // If not, then assume it's something that'll be compiled, or some other - // sort of script, and just call it directly. - mkdir(path.dirname(to), function (er) { - if (er) - return cb(er) - fs.readFile(from, "utf8", function (er, data) { - if (er) return writeShim_(from, to, null, null, cb) - var firstLine = data.trim().split(/\r*\n/)[0] - , shebang = firstLine.match(shebangExpr) - if (!shebang) return writeShim_(from, to, null, null, cb) - var prog = shebang[1] - , args = shebang[2] || "" - return writeShim_(from, to, prog, args, cb) - }) - }) -} +/***/ }), +/* 428 */ +/***/ (function(module, exports, __webpack_require__) { -function writeShim_ (from, to, prog, args, cb) { - var shTarget = path.relative(path.dirname(to), from) - , target = shTarget.split("/").join("\\") - , longProg - , shProg = prog && prog.split("\\").join("/") - , shLongProg - shTarget = shTarget.split("\\").join("/") - args = args || "" - if (!prog) { - prog = "\"%~dp0\\" + target + "\"" - shProg = "\"$basedir/" + shTarget + "\"" - args = "" - target = "" - shTarget = "" - } else { - longProg = "\"%~dp0\\" + prog + ".exe\"" - shLongProg = "\"$basedir/" + prog + "\"" - target = "\"%~dp0\\" + target + "\"" - shTarget = "\"$basedir/" + shTarget + "\"" - } +"use strict"; - // @IF EXIST "%~dp0\node.exe" ( - // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* - // ) ELSE ( - // SETLOCAL - // SET PATHEXT=%PATHEXT:;.JS;=;% - // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* - // ) - var cmd - if (longProg) { - cmd = "@IF EXIST " + longProg + " (\r\n" - + " " + longProg + " " + args + " " + target + " %*\r\n" - + ") ELSE (\r\n" - + " @SETLOCAL\r\n" - + " @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" - + " " + prog + " " + args + " " + target + " %*\r\n" - + ")" - } else { - cmd = "@" + prog + " " + args + " " + target + " %*\r\n" - } - // #!/bin/sh - // basedir=`dirname "$0"` - // - // case `uname` in - // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; - // esac - // - // if [ -x "$basedir/node.exe" ]; then - // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // ret=$? - // else - // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" - // ret=$? - // fi - // exit $ret +Object.defineProperty(exports, "__esModule", { + value: true +}); - var sh = "#!/bin/sh\n" +var _packageRequest; - if (shLongProg) { - sh = sh - + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" - + "\n" - + "case `uname` in\n" - + " *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;\n" - + "esac\n" - + "\n" +function _load_packageRequest() { + return _packageRequest = _interopRequireDefault(__webpack_require__(94)); +} - sh = sh - + "if [ -x "+shLongProg+" ]; then\n" - + " " + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" - + " ret=$?\n" - + "else \n" - + " " + shProg + " " + args + " " + shTarget + " \"$@\"\n" - + " ret=$?\n" - + "fi\n" - + "exit $ret\n" - } else { - sh = shProg + " " + args + " " + shTarget + " \"$@\"\n" - + "exit $?\n" - } +var _baseResolver; - var then = times(2, next, cb) - fs.writeFile(to + ".cmd", cmd, "utf8", then) - fs.writeFile(to, sh, "utf8", then) - function next () { - chmodShim(to, cb) - } +function _load_baseResolver() { + return _baseResolver = _interopRequireDefault(__webpack_require__(95)); } -function chmodShim (to, cb) { - var then = times(2, cb, cb) - fs.chmod(to, 0755, then) - fs.chmod(to + ".cmd", 0755, then) +var _workspaceLayout; + +function _load_workspaceLayout() { + return _workspaceLayout = _interopRequireDefault(__webpack_require__(80)); } -function times(n, ok, cb) { - var errState = null - return function(er) { - if (!errState) { - if (er) - cb(errState = er) - else if (--n === 0) - ok() - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const invariant = __webpack_require__(7); + +class WorkspaceResolver extends (_baseResolver || _load_baseResolver()).default { + static isWorkspace(pattern, workspaceLayout) { + return !!workspaceLayout && !!workspaceLayout.getManifestByPattern(pattern); } -} + constructor(request, fragment, workspaceLayout) { + super(request, fragment); + this.workspaceLayout = workspaceLayout; + } + + resolve() { + const workspace = this.workspaceLayout.getManifestByPattern(this.request.pattern); + invariant(workspace, 'expected workspace'); + const manifest = workspace.manifest, + loc = workspace.loc; + + const registry = manifest._registry; + invariant(registry, 'expected reference'); + + manifest._remote = { + type: 'workspace', + registry, + hash: '', + reference: loc + }; + + manifest._uid = manifest.version; + + return Promise.resolve(manifest); + } +} +exports.default = WorkspaceResolver; /***/ }), -/* 411 */ +/* 429 */ /***/ (function(module, exports, __webpack_require__) { -/** - * Module dependencies. - */ +"use strict"; -var EventEmitter = __webpack_require__(49).EventEmitter; -var spawn = __webpack_require__(111).spawn; -var readlink = __webpack_require__(481).readlinkSync; -var path = __webpack_require__(1); -var dirname = path.dirname; -var basename = path.basename; -var fs = __webpack_require__(6); -/** - * Expose the root command. - */ +Object.defineProperty(exports, "__esModule", { + value: true +}); -exports = module.exports = new Command(); +var _hostedGitResolver; -/** - * Expose `Command`. - */ +function _load_hostedGitResolver() { + return _hostedGitResolver = _interopRequireDefault(__webpack_require__(78)); +} -exports.Command = Command; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/** - * Expose `Option`. - */ +class BitbucketResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default { -exports.Option = Option; + static getTarballUrl(parts, hash) { + return `https://${this.hostname}/${parts.user}/${parts.repo}/get/${hash}.tar.gz`; + } -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ + static getGitHTTPBaseUrl(parts) { + return `https://${this.hostname}/${parts.user}/${parts.repo}`; + } -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/); - if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); - this.long = flags.shift(); - this.description = description || ''; + static getGitHTTPUrl(parts) { + return `${BitbucketResolver.getGitHTTPBaseUrl(parts)}.git`; + } + + static getGitSSHUrl(parts) { + return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; + } + + static getHTTPFileUrl(parts, filename, commit) { + return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`; + } } +exports.default = BitbucketResolver; +BitbucketResolver.hostname = 'bitbucket.org'; +BitbucketResolver.protocol = 'bitbucket'; -/** - * Return option name. - * - * @return {String} - * @api private - */ +/***/ }), +/* 430 */ +/***/ (function(module, exports, __webpack_require__) { -Option.prototype.name = function() { - return this.long - .replace('--', '') - .replace('no-', ''); -}; +"use strict"; -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ -Option.prototype.is = function(arg) { - return arg == this.short || arg == this.long; -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ +var _hostedGitResolver; -function Command(name) { - this.commands = []; - this.options = []; - this._execs = {}; - this._allowUnknownOption = false; - this._args = []; - this._name = name || ''; +function _load_hostedGitResolver() { + return _hostedGitResolver = _interopRequireDefault(__webpack_require__(78)); } -/** - * Inherit from `EventEmitter.prototype`. - */ +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -Command.prototype.__proto__ = EventEmitter.prototype; +class GitLabResolver extends (_hostedGitResolver || _load_hostedGitResolver()).default { -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir <path>', 'change the working directory') - * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function() { - * console.log('setup'); - * }); - * - * program - * .command('exec <cmd>') - * .description('run the given remote command') - * .action(function(cmd) { - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('teardown <dir> [otherDirs...]') - * .description('run teardown commands') - * .action(function(dir, otherDirs) { - * console.log('dir "%s"', dir); - * if (otherDirs) { - * otherDirs.forEach(function (oDir) { - * console.log('dir "%s"', oDir); - * }); - * } - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env) { - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @param {String} [desc] for git-style sub-commands - * @return {Command} the new command - * @api public - */ + static getTarballUrl(parts, hash) { + return `https://${this.hostname}/${parts.user}/${parts.repo}/repository/archive.tar.gz?ref=${hash}`; + } -Command.prototype.command = function(name, desc, opts) { - opts = opts || {}; - var args = name.split(/ +/); - var cmd = new Command(args.shift()); + static getGitHTTPBaseUrl(parts) { + return `https://${this.hostname}/${parts.user}/${parts.repo}`; + } - if (desc) { - cmd.description(desc); - this.executables = true; - this._execs[cmd._name] = true; - if (opts.isDefault) this.defaultExecutable = cmd._name; + static getGitHTTPUrl(parts) { + return `${GitLabResolver.getGitHTTPBaseUrl(parts)}.git`; } - cmd._noHelp = !!opts.noHelp; - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; + static getGitSSHUrl(parts) { + return `git+ssh://git@${this.hostname}/${parts.user}/${parts.repo}.git` + `${parts.hash ? '#' + decodeURIComponent(parts.hash) : ''}`; + } - if (desc) return this; - return cmd; -}; + static getHTTPFileUrl(parts, filename, commit) { + return `https://${this.hostname}/${parts.user}/${parts.repo}/raw/${commit}/${filename}`; + } +} +exports.default = GitLabResolver; +GitLabResolver.hostname = 'gitlab.com'; +GitLabResolver.protocol = 'gitlab'; -/** - * Define argument syntax for the top-level command. - * - * @api public - */ +/***/ }), +/* 431 */ +/***/ (function(module, exports, __webpack_require__) { -Command.prototype.arguments = function (desc) { - return this.parseExpectedArgs(desc.split(/ +/)); -}; +"use strict"; -/** - * Add an implicit `help [cmd]` subcommand - * which invokes `--help` for the given command. - * - * @api private - */ -Command.prototype.addImplicitHelpCommand = function() { - this.command('help [cmd]', 'display help for [cmd]'); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ +var _errors; -Command.prototype.parseExpectedArgs = function(args) { - if (!args.length) return; - var self = this; - args.forEach(function(arg) { - var argDetails = { - required: false, - name: '', - variadic: false - }; +function _load_errors() { + return _errors = __webpack_require__(3); +} - switch (arg[0]) { - case '<': - argDetails.required = true; - argDetails.name = arg.slice(1, -1); - break; - case '[': - argDetails.name = arg.slice(1, -1); - break; - } +var _exoticResolver; - if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { - argDetails.variadic = true; - argDetails.name = argDetails.name.slice(0, -3); - } - if (argDetails.name) { - self._args.push(argDetails); +function _load_exoticResolver() { + return _exoticResolver = _interopRequireDefault(__webpack_require__(61)); +} + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +class RegistryResolver extends (_exoticResolver || _load_exoticResolver()).default { + constructor(request, fragment) { + super(request, fragment); + + const match = fragment.match(/^(\S+):(.*?)(@(.*?)|)$/); + if (match) { + this.range = match[4] || 'latest'; + this.name = match[2]; + } else { + throw new (_errors || _load_errors()).MessageError(this.reporter.lang('invalidFragment', fragment)); } - }); - return this; -}; -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function() { - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ + // $FlowFixMe + this.registry = this.constructor.protocol; + } -Command.prototype.action = function(fn) { - var self = this; - var listener = function(args, unknown) { - // Parse any so-far unknown options - args = args || []; - unknown = unknown || []; + resolve() { + return this.fork(this.constructor.factory, false, this.name, this.range); + } +} +exports.default = RegistryResolver; - var parsed = self.parseOptions(unknown); +/***/ }), +/* 432 */ +/***/ (function(module, exports, __webpack_require__) { - // Output help if necessary - outputHelpIfNecessary(self, parsed.unknown); +"use strict"; - // If there are still any unknown options, then we simply - // die, unless someone asked for help, in which case we give it - // to them, and then we die. - if (parsed.unknown.length > 0) { - self.unknownOption(parsed.unknown[0]); - } - // Leftover arguments need to be pushed back. Fixes issue #56 - if (parsed.args.length) args = parsed.args.concat(args); +Object.defineProperty(exports, "__esModule", { + value: true +}); - self._args.forEach(function(arg, i) { - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } else if (arg.variadic) { - if (i !== self._args.length - 1) { - self.variadicArgNotLast(arg.name); - } +var _asyncToGenerator2; - args[i] = args.splice(i); - } - }); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - // Always append ourselves to the end of the arguments, - // to make sure we match the number of arguments the user - // expects - if (self._args.length) { - args[self._args.length] = self; - } else { - args.push(self); - } +var _tarballFetcher; - fn.apply(self, args); - }; - var parent = this.parent || this; - var name = parent === this ? '*' : this._name; - parent.on(name, listener); - if (this._alias) parent.on(this._alias, listener); - return this; -}; +function _load_tarballFetcher() { + return _tarballFetcher = _interopRequireDefault(__webpack_require__(261)); +} -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to true - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => false - * - * // required argument - * program.option('-C, --chdir <path>', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ +var _exoticResolver; + +function _load_exoticResolver() { + return _exoticResolver = _interopRequireDefault(__webpack_require__(61)); +} + +var _gitResolver; + +function _load_gitResolver() { + return _gitResolver = _interopRequireDefault(__webpack_require__(96)); +} + +var _guessName; + +function _load_guessName() { + return _guessName = _interopRequireDefault(__webpack_require__(166)); +} -Command.prototype.option = function(flags, description, fn, defaultValue) { - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); +var _version; - // default as 3rd arg - if (typeof fn != 'function') { - if (fn instanceof RegExp) { - var regex = fn; - fn = function(val, def) { - var m = regex.exec(val); - return m ? m[0] : def; - } - } - else { - defaultValue = fn; - fn = null; - } - } +function _load_version() { + return _version = _interopRequireWildcard(__webpack_require__(170)); +} - // preassign default value only for --no-*, [optional], or <required> - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; +var _crypto; + +function _load_crypto() { + return _crypto = _interopRequireWildcard(__webpack_require__(123)); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +const invariant = __webpack_require__(7); + +class TarballResolver extends (_exoticResolver || _load_exoticResolver()).default { + constructor(request, fragment) { + super(request, fragment); + + var _versionUtil$explodeH = (_version || _load_version()).explodeHashedUrl(fragment); + + const hash = _versionUtil$explodeH.hash, + url = _versionUtil$explodeH.url; + + this.hash = hash; + this.url = url; } - // register the option - this.options.push(option); + static isVersion(pattern) { + // we can sometimes match git urls which we don't want + if ((_gitResolver || _load_gitResolver()).default.isVersion(pattern)) { + return false; + } - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val) { - // coercion - if (null !== val && fn) val = fn(val, undefined === self[name] - ? defaultValue - : self[name]); + // full http url + if (pattern.startsWith('http://') || pattern.startsWith('https://')) { + return true; + } - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; + // local file reference - ignore patterns with names + if (pattern.indexOf('@') < 0) { + if (pattern.endsWith('.tgz') || pattern.endsWith('.tar.gz')) { + return true; } - } else if (null !== val) { - // reassign - self[name] = val; } - }); - return this; -}; + return false; + } -/** - * Allow unknown options on the command line. - * - * @param {Boolean} arg if `true` or omitted, no error will be thrown - * for unknown options. - * @api public - */ -Command.prototype.allowUnknownOption = function(arg) { - this._allowUnknownOption = arguments.length === 0 || arg; - return this; -}; + resolve() { + var _this = this; -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ + return (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* () { + const shrunk = _this.request.getLocked('tarball'); + if (shrunk) { + return shrunk; + } -Command.prototype.parse = function(argv) { - // implicit help - if (this.executables) this.addImplicitHelpCommand(); + const url = _this.url; + let hash = _this.hash, + registry = _this.registry; - // store raw args - this.rawArgs = argv; + let pkgJson; - // guess name - this._name = this._name || basename(argv[1], '.js'); + // generate temp directory + const dest = _this.config.getTemp((_crypto || _load_crypto()).hash(url)); - // github-style sub-commands with no sub-command - if (this.executables && argv.length < 3 && !this.defaultExecutable) { - // this user needs help - argv.push('--help'); - } + if (yield _this.config.isValidModuleDest(dest)) { + var _ref = yield _this.config.readPackageMetadata(dest); + // load from local cache - // process argv - var parsed = this.parseOptions(this.normalize(argv.slice(2))); - var args = this.args = parsed.args; - var result = this.parseArgs(this.args, parsed.unknown); + pkgJson = _ref.package; + hash = _ref.hash; + registry = _ref.registry; + } else { + // delete if invalid + yield (_fs || _load_fs()).unlink(dest); - // executable sub-commands - var name = result.args[0]; - if (this._execs[name] && typeof this._execs[name] != "function") { - return this.executeSubCommand(argv, args, parsed.unknown); - } else if (this.defaultExecutable) { - // use the default subcommand - args.unshift(name = this.defaultExecutable); - return this.executeSubCommand(argv, args, parsed.unknown); - } + const fetcher = new (_tarballFetcher || _load_tarballFetcher()).default(dest, { + type: 'tarball', + reference: url, + registry, + hash + }, _this.config); - return result; -}; + // fetch file and get it's hash + const fetched = yield fetcher.fetch({ + name: (0, (_guessName || _load_guessName()).default)(url), + version: '0.0.0', + _registry: 'npm' + }); + pkgJson = fetched.package; + hash = fetched.hash; -/** - * Execute a sub-command executable. - * - * @param {Array} argv - * @param {Array} args - * @param {Array} unknown - * @api private - */ + registry = pkgJson._registry; + invariant(registry, 'expected registry'); + } -Command.prototype.executeSubCommand = function(argv, args, unknown) { - args = args.concat(unknown); + // use the commit/tarball hash as the uid as we can't rely on the version as it's not + // in the registry + pkgJson._uid = hash; - if (!args.length) this.help(); - if ('help' == args[0] && 1 == args.length) this.help(); + // set remote so it can be "fetched" + pkgJson._remote = { + type: 'copy', + resolved: `${url}#${hash}`, + hash, + registry, + reference: dest + }; - // <cmd> --help - if ('help' == args[0]) { - args[0] = args[1]; - args[1] = '--help'; + return pkgJson; + })(); } +} +exports.default = TarballResolver; - // executable - var f = argv[1]; - // name of the subcommand, link `pm-install` - var bin = basename(f, '.js') + '-' + args[0]; +/***/ }), +/* 433 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; - // In case of globally installed, get the base dir where executable - // subcommand file should be located at - var baseDir - , link = readlink(f); - // when symbolink is relative path - if (link !== f && link.charAt(0) !== '/') { - link = path.join(dirname(f), link) - } - baseDir = dirname(link); +Object.defineProperty(exports, "__esModule", { + value: true +}); - // prefer local `./<bin>` to bin in the $PATH - var localBin = path.join(baseDir, bin); +var _baseResolver; - // whether bin file is a js script with explicit `.js` extension - var isExplicitJS = false; - if (exists(localBin + '.js')) { - bin = localBin + '.js'; - isExplicitJS = true; - } else if (exists(localBin)) { - bin = localBin; - } +function _load_baseResolver() { + return _baseResolver = _interopRequireDefault(__webpack_require__(95)); +} - args = args.slice(1); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - var proc; - if (process.platform !== 'win32') { - if (isExplicitJS) { - args.unshift(localBin); - // add executable arguments to spawn - args = (process.execArgv || []).concat(args); +class RegistryResolver extends (_baseResolver || _load_baseResolver()).default { + constructor(request, name, range) { + super(request, `${name}@${range}`); + this.name = name; + this.range = range; - proc = spawn('node', args, { stdio: 'inherit', customFds: [0, 1, 2] }); - } else { - proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] }); - } - } else { - args.unshift(localBin); - proc = spawn(process.execPath, args, { stdio: 'inherit'}); + this.registryConfig = request.config.registries[this.constructor.registry].config; } - proc.on('close', process.exit.bind(process)); - proc.on('error', function(err) { - if (err.code == "ENOENT") { - console.error('\n %s(1) does not exist, try --help\n', bin); - } else if (err.code == "EACCES") { - console.error('\n %s(1) not executable. try chmod or run with root\n', bin); - } - process.exit(1); - }); +} +exports.default = RegistryResolver; - // Store the reference to the child process - this.runningCommand = proc; -}; +/***/ }), +/* 434 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * This also normalizes equal sign and splits "--abc=def" into "--abc def". - * - * @param {Array} args - * @return {Array} - * @api private - */ +"use strict"; -Command.prototype.normalize = function(args) { - var ret = [] - , arg - , lastOpt - , index; - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - if (i > 0) { - lastOpt = this.optionFor(args[i-1]); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = envReplace; +const ENV_EXPR = /(\\*)\$\{([^}]+)\}/g; - if (arg === '--') { - // Honor option terminator - ret = ret.concat(args.slice(i)); - break; - } else if (lastOpt && lastOpt.required) { - ret.push(arg); - } else if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c) { - ret.push('-' + c); - }); - } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { - ret.push(arg.slice(0, index), arg.slice(index + 1)); - } else { - ret.push(arg); - } +function envReplace(value) { + let env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : process.env; + + if (typeof value !== 'string' || !value) { + return value; } - return ret; -}; + return value.replace(ENV_EXPR, (match, esc, envVarName) => { + if (esc.length && esc.length % 2) { + return match; + } + if (undefined === env[envVarName]) { + throw new Error('Failed to replace env in config: ' + match); + } + return env[envVarName] || ''; + }); +} -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ +/***/ }), +/* 435 */ +/***/ (function(module, exports, __webpack_require__) { -Command.prototype.parseArgs = function(args, unknown) { - var name; +"use strict"; - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args, unknown); - } else { - this.emit('*', args); - } - } else { - outputHelpIfNecessary(this, unknown); - // If there were no args and we have unknown options, - // then they are extraneous and we need to error. - if (unknown.length > 0) { - this.unknownOption(unknown[0]); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.fixCmdWinSlashes = fixCmdWinSlashes; +function fixCmdWinSlashes(cmd) { + function findQuotes(quoteSymbol) { + const quotes = []; + const addQuote = (_, index) => { + quotes.push({ from: index, to: index + _.length }); + return _; + }; + const regEx = new RegExp(quoteSymbol + '.*' + quoteSymbol); + cmd.replace(regEx, addQuote); + return quotes; } + const quotes = findQuotes('"').concat(findQuotes("'")); - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ + function isInsideQuotes(index) { + return quotes.reduce((result, quote) => { + return result || quote.from <= index && index <= quote.to; + }, false); + } -Command.prototype.optionFor = function(arg) { - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; + const cmdPrePattern = '((?:^|&&|&|\\|\\||\\|)\\s*)'; + const cmdPattern = '(".*?"|\'.*?\'|\\S*)'; + const regExp = new RegExp(`${cmdPrePattern}${cmdPattern}`, 'g'); + return cmd.replace(regExp, (whole, pre, cmd, index) => { + if ((pre[0] === '&' || pre[0] === '|') && isInsideQuotes(index)) { + return whole; } - } -}; + return pre + cmd.replace(/\//g, '\\'); + }); +} -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ +/***/ }), +/* 436 */ +/***/ (function(module, exports, __webpack_require__) { -Command.prototype.parseOptions = function(argv) { - var args = [] - , len = argv.length - , literal - , option - , arg; +"use strict"; - var unknownOptions = []; - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.parseRefs = exports.resolveVersion = exports.isCommitSha = undefined; - // literal args after -- - if ('--' == arg) { - literal = true; - continue; - } +var _asyncToGenerator2; - if (literal) { - args.push(arg); - continue; - } +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); +} - // find matching Option - option = this.optionFor(arg); +var _slicedToArray2; - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || ('-' == arg[0] && '-' != arg)) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - unknownOptions.push(arg); +var _misc; - // If the next argument looks like it might be - // an argument for this option, we pass it on. - // If it isn't, then it'll simply be ignored - if (argv[i+1] && '-' != argv[i+1][0]) { - unknownOptions.push(argv[++i]); - } - continue; - } +function _load_misc() { + return _misc = __webpack_require__(10); +} - // arg - args.push(arg); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return { args: args, unknown: unknownOptions }; -}; +const semver = __webpack_require__(22); -/** - * Return an object containing options as key-value pairs - * - * @return {Object} - * @api public - */ -Command.prototype.opts = function() { - var result = {} - , len = this.options.length; +const REF_TAG_PREFIX = 'refs/tags/'; +const REF_BRANCH_PREFIX = 'refs/heads/'; + +// This regex is designed to match output from git of the style: +// ebeb6eafceb61dd08441ffe086c77eb472842494 refs/tags/v0.21.0 +// and extract the hash and ref name as capture groups +const GIT_REF_LINE_REGEXP = /^([a-fA-F0-9]+)\s+(refs\/(?:tags|heads)\/.*)$/; + +const COMMIT_SHA_REGEXP = /^[a-f0-9]{5,40}$/; +const REF_NAME_REGEXP = /^refs\/(tags|heads)\/(.+)$/; - for (var i = 0 ; i < len; i++) { - var key = camelcase(this.options[i].name()); - result[key] = key === 'version' ? this._version : this[key]; - } - return result; -}; +const isCommitSha = exports.isCommitSha = target => COMMIT_SHA_REGEXP.test(target); -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ +const tryVersionAsGitCommit = (_ref) => { + let version = _ref.version, + refs = _ref.refs, + git = _ref.git; -Command.prototype.missingArgument = function(name) { - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; + const lowercaseVersion = version.toLowerCase(); + if (!isCommitSha(lowercaseVersion)) { + return Promise.resolve(null); + } + for (const _ref2 of refs.entries()) { + var _ref3 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_ref2, 2); -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ + const ref = _ref3[0]; + const sha = _ref3[1]; -Command.prototype.optionMissingArgument = function(option, flag) { - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); + if (sha.startsWith(lowercaseVersion)) { + return Promise.resolve({ sha, ref }); + } } - console.error(); - process.exit(1); + return git.resolveCommit(lowercaseVersion); }; -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ +const tryEmptyVersionAsDefaultBranch = (_ref4) => { + let version = _ref4.version, + git = _ref4.git; + return version.trim() === '' ? git.resolveDefaultBranch() : Promise.resolve(null); +}; -Command.prototype.unknownOption = function(flag) { - if (this._allowUnknownOption) return; - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); +const tryWildcardVersionAsDefaultBranch = (_ref5) => { + let version = _ref5.version, + git = _ref5.git; + return version === '*' ? git.resolveDefaultBranch() : Promise.resolve(null); }; -/** - * Variadic argument with `name` is not the last argument as required. - * - * @param {String} name - * @api private - */ +const tryRef = (refs, ref) => { + const sha = refs.get(ref); + return sha ? { sha, ref } : null; +}; -Command.prototype.variadicArgNotLast = function(name) { - console.error(); - console.error(" error: variadic arguments must be last `%s'", name); - console.error(); - process.exit(1); +const tryVersionAsFullRef = (_ref6) => { + let version = _ref6.version, + refs = _ref6.refs; + return version.startsWith('refs/') ? tryRef(refs, version) : null; }; -/** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @param {String} flags - * @return {Command} for chaining - * @api public - */ +const tryVersionAsTagName = (_ref7) => { + let version = _ref7.version, + refs = _ref7.refs; + return tryRef(refs, `${REF_TAG_PREFIX}${version}`); +}; -Command.prototype.version = function(str, flags) { - if (0 == arguments.length) return this._version; - this._version = str; - flags = flags || '-V, --version'; - this.option(flags, 'output the version number'); - this.on('version', function() { - process.stdout.write(str + '\n'); - process.exit(0); - }); - return this; +const tryVersionAsBranchName = (_ref8) => { + let version = _ref8.version, + refs = _ref8.refs; + return tryRef(refs, `${REF_BRANCH_PREFIX}${version}`); }; -/** - * Set the description to `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ +const computeSemverNames = (_ref9) => { + let config = _ref9.config, + refs = _ref9.refs; -Command.prototype.description = function(str) { - if (0 === arguments.length) return this._description; - this._description = str; - return this; -}; + const names = { + tags: [], + heads: [] + }; + for (const ref of refs.keys()) { + const match = REF_NAME_REGEXP.exec(ref); + if (!match) { + continue; + } -/** - * Set an alias for the command - * - * @param {String} alias - * @return {String|Command} - * @api public - */ + var _match = (0, (_slicedToArray2 || _load_slicedToArray()).default)(match, 3); -Command.prototype.alias = function(alias) { - if (0 == arguments.length) return this._alias; - this._alias = alias; - return this; + const type = _match[1], + name = _match[2]; + + if (semver.valid(name, config.looseSemver)) { + names[type].push(name); + } + } + return names; }; -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ +const findSemver = (version, config, namesList) => config.resolveConstraints(namesList, version); -Command.prototype.usage = function(str) { - var args = this._args.map(function(arg) { - return humanReadableArgName(arg); +const tryVersionAsTagSemver = (() => { + var _ref10 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref11, names) { + let version = _ref11.version, + config = _ref11.config, + refs = _ref11.refs; + + const result = yield findSemver(version, config, names.tags); + return result ? tryRef(refs, `${REF_TAG_PREFIX}${result}`) : null; }); - var usage = '[options]' - + (this.commands.length ? ' [command]' : '') - + (this._args.length ? ' ' + args.join(' ') : ''); + return function tryVersionAsTagSemver(_x, _x2) { + return _ref10.apply(this, arguments); + }; +})(); - if (0 == arguments.length) return this._usage || usage; - this._usage = str; +const tryVersionAsBranchSemver = (() => { + var _ref12 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (_ref13, names) { + let version = _ref13.version, + config = _ref13.config, + refs = _ref13.refs; - return this; -}; + const result = yield findSemver(version, config, names.heads); + return result ? tryRef(refs, `${REF_BRANCH_PREFIX}${result}`) : null; + }); -/** - * Get the name of the command - * - * @param {String} name - * @return {String|Command} - * @api public - */ + return function tryVersionAsBranchSemver(_x3, _x4) { + return _ref12.apply(this, arguments); + }; +})(); -Command.prototype.name = function() { - return this._name; -}; +const tryVersionAsSemverRange = (() => { + var _ref14 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (options) { + const names = computeSemverNames(options); + return (yield tryVersionAsTagSemver(options, names)) || tryVersionAsBranchSemver(options, names); + }); -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ + return function tryVersionAsSemverRange(_x5) { + return _ref14.apply(this, arguments); + }; +})(); -Command.prototype.largestOptionLength = function() { - return this.options.reduce(function(max, option) { - return Math.max(max, option.flags.length); - }, 0); -}; +const VERSION_RESOLUTION_STEPS = [tryEmptyVersionAsDefaultBranch, tryVersionAsGitCommit, tryVersionAsFullRef, tryVersionAsTagName, tryVersionAsBranchName, tryVersionAsSemverRange, tryWildcardVersionAsDefaultBranch]; /** - * Return help for options. - * - * @return {String} - * @api private + * Resolve a git-url hash (version) to a git commit sha and branch/tag ref + * Returns null if the version cannot be resolved to any commit */ -Command.prototype.optionHelp = function() { - var width = this.largestOptionLength(); +const resolveVersion = exports.resolveVersion = (() => { + var _ref15 = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (options) { + for (const testFunction of VERSION_RESOLUTION_STEPS) { + const result = yield testFunction(options); + if (result !== null) { + return result; + } + } + return null; + }); - // Prepend the help information - return [pad('-h, --help', width) + ' ' + 'output usage information'] - .concat(this.options.map(function(option) { - return pad(option.flags, width) + ' ' + option.description; - })) - .join('\n'); -}; + return function resolveVersion(_x6) { + return _ref15.apply(this, arguments); + }; +})(); /** - * Return command help documentation. - * - * @return {String} - * @api private + * Parse Git ref lines into hash of ref names to SHA hashes */ -Command.prototype.commandHelp = function() { - if (!this.commands.length) return ''; +const parseRefs = exports.parseRefs = stdout => { + // store references + const refs = new Map(); - var commands = this.commands.filter(function(cmd) { - return !cmd._noHelp; - }).map(function(cmd) { - var args = cmd._args.map(function(arg) { - return humanReadableArgName(arg); - }).join(' '); + // line delimited + const refLines = stdout.split('\n'); - return [ - cmd._name - + (cmd._alias ? '|' + cmd._alias : '') - + (cmd.options.length ? ' [options]' : '') - + ' ' + args - , cmd.description() - ]; - }); + for (const line of refLines) { + const match = GIT_REF_LINE_REGEXP.exec(line); - var width = commands.reduce(function(max, command) { - return Math.max(max, command[0].length); - }, 0); + if (match) { + var _match2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(match, 3); - return [ - '' - , ' Commands:' - , '' - , commands.map(function(cmd) { - var desc = cmd[1] ? ' ' + cmd[1] : ''; - return pad(cmd[0], width) + desc; - }).join('\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; + const sha = _match2[1], + tagName = _match2[2]; -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ + // As documented in gitrevisions: + // https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html#_specifying_revisions + // "A suffix ^ followed by an empty brace pair means the object could be a tag, + // and dereference the tag recursively until a non-tag object is found." + // In other words, the hash without ^{} is the hash of the tag, + // and the hash with ^{} is the hash of the commit at which the tag was made. -Command.prototype.helpInformation = function() { - var desc = []; - if (this._description) { - desc = [ - ' ' + this._description - , '' - ]; - } + const name = (0, (_misc || _load_misc()).removeSuffix)(tagName, '^{}'); - var cmdName = this._name; - if (this._alias) { - cmdName = cmdName + '|' + this._alias; + refs.set(name, sha); + } } - var usage = [ - '' - ,' Usage: ' + cmdName + ' ' + this.usage() - , '' - ]; - var cmds = []; - var commandHelp = this.commandHelp(); - if (commandHelp) cmds = [commandHelp]; + return refs; +}; - var options = [ - ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ]; +/***/ }), +/* 437 */ +/***/ (function(module, exports, __webpack_require__) { - return usage - .concat(cmds) - .concat(desc) - .concat(options) - .join('\n'); -}; +"use strict"; -/** - * Output help information for this command - * - * @api public - */ -Command.prototype.outputHelp = function(cb) { - if (!cb) { - cb = function(passthru) { - return passthru; - } - } - process.stdout.write(cb(this.helpInformation())); - this.emit('--help'); -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); +const lockPromises = new Map(); /** - * Output help information and exit. - * - * @api public + * Acquires a mutex lock over the given key. If the lock can't be acquired, it waits until it's available. + * @param key Key to get the lock for. + * @return {Promise.<Function>} A Promise that resolves when the lock is acquired, with the function that + * must be called to release the lock. */ -Command.prototype.help = function(cb) { - this.outputHelp(cb); - process.exit(); +exports.default = key => { + let unlockNext; + const willLock = new Promise(resolve => unlockNext = resolve); + const lockPromise = lockPromises.get(key) || Promise.resolve(); + const willUnlock = lockPromise.then(() => unlockNext); + lockPromises.set(key, lockPromise.then(() => willLock)); + return willUnlock; }; -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ +/***/ }), +/* 438 */ +/***/ (function(module, exports, __webpack_require__) { -function camelcase(flag) { - return flag.split('-').reduce(function(str, word) { - return str + word[0].toUpperCase() + word.slice(1); - }); +"use strict"; + + +Object.defineProperty(exports, "__esModule", { + value: true +}); + +var _toArray2; + +function _load_toArray() { + return _toArray2 = _interopRequireDefault(__webpack_require__(99)); } -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ +var _asyncToGenerator2; -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); +function _load_asyncToGenerator() { + return _asyncToGenerator2 = _interopRequireDefault(__webpack_require__(1)); } -/** - * Output help information if necessary - * - * @param {Command} command to output help for - * @param {Array} array of options to search for -h or --help - * @api private - */ +var _constants; -function outputHelpIfNecessary(cmd, options) { - options = options || []; - for (var i = 0; i < options.length; i++) { - if (options[i] == '--help' || options[i] == '-h') { - cmd.outputHelp(); - process.exit(0); - } - } +function _load_constants() { + return _constants = __webpack_require__(6); } -/** - * Takes an argument an returns its human readable equivalent for help usage. - * - * @param {Object} arg - * @return {String} - * @api private - */ +var _util; -function humanReadableArgName(arg) { - var nameOutput = arg.name + (arg.variadic === true ? '...' : ''); +function _load_util() { + return _util = __webpack_require__(168); +} - return arg.required - ? '<' + nameOutput + '>' - : '[' + nameOutput + ']' +var _index; + +function _load_index() { + return _index = __webpack_require__(35); } -// for versions before node v0.8 when there weren't `fs.existsSync` -function exists(file) { - try { - if (fs.statSync(file).isFile()) { - return true; - } - } catch (e) { - return false; - } +var _inferLicense; + +function _load_inferLicense() { + return _inferLicense = _interopRequireDefault(__webpack_require__(439)); +} + +var _fs; + +function _load_fs() { + return _fs = _interopRequireWildcard(__webpack_require__(4)); } +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 412 */ -/***/ (function(module, exports) { +const semver = __webpack_require__(22); +const path = __webpack_require__(0); +const url = __webpack_require__(14); -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); +const LICENSE_RENAMES = { + 'MIT/X11': 'MIT', + X11: 'MIT' +}; + +exports.default = (() => { + var _ref = (0, (_asyncToGenerator2 || _load_asyncToGenerator()).default)(function* (info, moduleLoc, reporter, warn, looseSemver) { + const files = yield (_fs || _load_fs()).readdir(moduleLoc); + + // clean info.version + if (typeof info.version === 'string') { + info.version = semver.clean(info.version, looseSemver) || info.version; + } + + // if name or version aren't set then set them to empty strings + info.name = info.name || ''; + info.version = info.version || ''; + + // if the man field is a string then coerce it to an array + if (typeof info.man === 'string') { + info.man = [info.man]; + } + + // if the keywords field is a string then split it on any whitespace + if (typeof info.keywords === 'string') { + info.keywords = info.keywords.split(/\s+/g); + } + + // if there's no contributors field but an authors field then expand it + if (!info.contributors && files.indexOf('AUTHORS') >= 0) { + const authorsFilepath = path.join(moduleLoc, 'AUTHORS'); + const authorsFilestats = yield (_fs || _load_fs()).stat(authorsFilepath); + if (authorsFilestats.isFile()) { + let authors = yield (_fs || _load_fs()).readFile(authorsFilepath); + authors = authors.split(/\r?\n/g) // split on lines + .map(function (line) { + return line.replace(/^\s*#.*$/, '').trim(); + }) // remove comments + .filter(function (line) { + return !!line; + }); // remove empty lines + info.contributors = authors; + } + } + + // expand people fields to objects + if (typeof info.author === 'string' || typeof info.author === 'object') { + info.author = (0, (_util || _load_util()).normalizePerson)(info.author); + } + if (Array.isArray(info.contributors)) { + info.contributors = info.contributors.map((_util || _load_util()).normalizePerson); + } + if (Array.isArray(info.maintainers)) { + info.maintainers = info.maintainers.map((_util || _load_util()).normalizePerson); + } + + // if there's no readme field then load the README file from the cwd + if (!info.readme) { + const readmeCandidates = files.filter(function (filename) { + const lower = filename.toLowerCase(); + return lower === 'readme' || lower.indexOf('readme.') === 0; + }).sort(function (filename1, filename2) { + // favor files with extensions + return filename2.indexOf('.') - filename1.indexOf('.'); + }); + + for (const readmeFilename of readmeCandidates) { + const readmeFilepath = path.join(moduleLoc, readmeFilename); + const readmeFileStats = yield (_fs || _load_fs()).stat(readmeFilepath); + if (readmeFileStats.isFile()) { + info.readmeFilename = readmeFilename; + info.readme = yield (_fs || _load_fs()).readFile(readmeFilepath); + break; + } + } + } + + // if there's no description then take the first paragraph from the readme + if (!info.description && info.readme) { + const desc = (0, (_util || _load_util()).extractDescription)(info.readme); + if (desc) { + info.description = desc; + } + } + + // support array of engine keys + if (Array.isArray(info.engines)) { + const engines = {}; + for (const str of info.engines) { + if (typeof str === 'string') { + var _str$trim$split = str.trim().split(/ +/g), + _str$trim$split2 = (0, (_toArray2 || _load_toArray()).default)(_str$trim$split); + + const name = _str$trim$split2[0], + patternParts = _str$trim$split2.slice(1); + + engines[name] = patternParts.join(' '); + } + } + info.engines = engines; + } + + // if the repository field is a string then assume it's a git repo and expand it + if (typeof info.repository === 'string') { + info.repository = { + type: 'git', + url: info.repository + }; + } + + const repo = info.repository; + + // explode info.repository.url if it's a hosted git shorthand + if (repo && typeof repo === 'object' && typeof repo.url === 'string') { + repo.url = (0, (_index || _load_index()).hostedGitFragmentToGitUrl)(repo.url, reporter); } - return res; -}; -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; + // allow bugs to be specified as a string, expand it to an object with a single url prop + if (typeof info.bugs === 'string') { + info.bugs = { url: info.bugs }; + } + // normalize homepage url to http + if (typeof info.homepage === 'string') { + const parts = url.parse(info.homepage); + parts.protocol = parts.protocol || 'http:'; + if (parts.pathname && !parts.hostname) { + parts.hostname = parts.pathname; + parts.pathname = ''; + } + info.homepage = url.format(parts); + } -/***/ }), -/* 413 */ -/***/ (function(module, exports, __webpack_require__) { + // if the `bin` field is as string then expand it to an object with a single property + // based on the original `bin` field and `name field` + // { name: "foo", bin: "cli.js" } -> { name: "foo", bin: { foo: "cli.js" } } + if (typeof info.name === 'string' && typeof info.bin === 'string') { + // Remove scoped package name for consistency with NPM's bin field fixing behaviour + const name = info.name.replace(/^@[^\/]+\//, ''); + info.bin = { [name]: info.bin }; + } -__webpack_require__(92); -__webpack_require__(444); -module.exports = __webpack_require__(31).Array.from; + // bundleDependencies is an alias for bundledDependencies + if (info.bundledDependencies) { + info.bundleDependencies = info.bundledDependencies; + delete info.bundledDependencies; + } -/***/ }), -/* 414 */ -/***/ (function(module, exports, __webpack_require__) { + let scripts; -__webpack_require__(147); -__webpack_require__(92); -module.exports = __webpack_require__(442); + // dummy script object to shove file inferred scripts onto + if (info.scripts && typeof info.scripts === 'object') { + scripts = info.scripts; + } else { + scripts = {}; + } -/***/ }), -/* 415 */ -/***/ (function(module, exports, __webpack_require__) { + // if there's a server.js file and no start script then set it to `node server.js` + if (!scripts.start && files.indexOf('server.js') >= 0) { + scripts.start = 'node server.js'; + } -__webpack_require__(147); -__webpack_require__(92); -module.exports = __webpack_require__(443); + // if there's a binding.gyp file and no install script then set it to `node-gyp rebuild` + if (!scripts.install && files.indexOf('binding.gyp') >= 0) { + scripts.install = 'node-gyp rebuild'; + } -/***/ }), -/* 416 */ -/***/ (function(module, exports, __webpack_require__) { + // set scripts if we've polluted the empty object + if (Object.keys(scripts).length) { + info.scripts = scripts; + } -__webpack_require__(446); -module.exports = __webpack_require__(31).Object.assign; + const dirs = info.directories; -/***/ }), -/* 417 */ -/***/ (function(module, exports, __webpack_require__) { + if (dirs && typeof dirs === 'object') { + const binDir = dirs.bin; -__webpack_require__(447); -__webpack_require__(92); -__webpack_require__(147); -__webpack_require__(448); -module.exports = __webpack_require__(31).Promise; + if (!info.bin && binDir && typeof binDir === 'string') { + const bin = info.bin = {}; + const fullBinDir = path.join(moduleLoc, binDir); -/***/ }), -/* 418 */ -/***/ (function(module, exports) { + if (yield (_fs || _load_fs()).exists(fullBinDir)) { + for (const scriptName of yield (_fs || _load_fs()).readdir(fullBinDir)) { + if (scriptName[0] === '.') { + continue; + } + bin[scriptName] = path.join('.', binDir, scriptName); + } + } else { + warn(reporter.lang('manifestDirectoryNotFound', binDir, info.name)); + } + } -module.exports = function(){ /* empty */ }; + const manDir = dirs.man; -/***/ }), -/* 419 */ -/***/ (function(module, exports) { + if (!info.man && typeof manDir === 'string') { + const man = info.man = []; + const fullManDir = path.join(moduleLoc, manDir); -module.exports = function(it, Constructor, name, forbiddenField){ - if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ - throw TypeError(name + ': incorrect invocation!'); - } return it; -}; + if (yield (_fs || _load_fs()).exists(fullManDir)) { + for (const filename of yield (_fs || _load_fs()).readdir(fullManDir)) { + if (/^(.*?)\.[0-9]$/.test(filename)) { + man.push(path.join('.', manDir, filename)); + } + } + } else { + warn(reporter.lang('manifestDirectoryNotFound', manDir, info.name)); + } + } + } -/***/ }), -/* 420 */ -/***/ (function(module, exports, __webpack_require__) { + delete info.directories; -// false -> Array#indexOf -// true -> Array#includes -var toIObject = __webpack_require__(143) - , toLength = __webpack_require__(144) - , toIndex = __webpack_require__(440); -module.exports = function(IS_INCLUDES){ - return function($this, el, fromIndex){ - var O = toIObject($this) - , length = toLength(O.length) - , index = toIndex(fromIndex, length) - , value; - // Array#includes uses SameValueZero equality algorithm - if(IS_INCLUDES && el != el)while(length > index){ - value = O[index++]; - if(value != value)return true; - // Array#toIndex ignores holes, Array#includes - not - } else for(;length > index; index++)if(IS_INCLUDES || index in O){ - if(O[index] === el)return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; -}; + // normalize licenses field + const licenses = info.licenses; + if (Array.isArray(licenses) && !info.license) { + let licenseTypes = []; -/***/ }), -/* 421 */ -/***/ (function(module, exports, __webpack_require__) { + for (let license of licenses) { + if (license && typeof license === 'object') { + license = license.type; + } + if (typeof license === 'string') { + licenseTypes.push(license); + } + } -"use strict"; + licenseTypes = licenseTypes.filter((_util || _load_util()).isValidLicense); -var $defineProperty = __webpack_require__(70) - , createDesc = __webpack_require__(139); + if (licenseTypes.length === 1) { + info.license = licenseTypes[0]; + } else if (licenseTypes.length) { + info.license = `(${licenseTypes.join(' OR ')})`; + } + } -module.exports = function(object, index, value){ - if(index in object)$defineProperty.f(object, index, createDesc(0, value)); - else object[index] = value; -}; + const license = info.license; -/***/ }), -/* 422 */ -/***/ (function(module, exports, __webpack_require__) { + // normalize license + if (license && typeof license === 'object') { + info.license = license.type; + } -var ctx = __webpack_require__(68) - , call = __webpack_require__(218) - , isArrayIter = __webpack_require__(217) - , anObject = __webpack_require__(46) - , toLength = __webpack_require__(144) - , getIterFn = __webpack_require__(146) - , BREAK = {} - , RETURN = {}; -var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ - var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) - , f = ctx(fn, that, entries ? 2 : 1) - , index = 0 - , length, step, iterator, result; - if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); - // fast case for arrays with default iterator - if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ - result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); - if(result === BREAK || result === RETURN)return result; - } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ - result = call(iterator, f, step.value, entries); - if(result === BREAK || result === RETURN)return result; - } -}; -exports.BREAK = BREAK; -exports.RETURN = RETURN; + // get license file + const licenseFile = files.find(function (filename) { + const lower = filename.toLowerCase(); + return lower === 'license' || lower.startsWith('license.') || lower === 'unlicense' || lower.startsWith('unlicense.'); + }); + if (licenseFile) { + const licenseFilepath = path.join(moduleLoc, licenseFile); + const licenseFileStats = yield (_fs || _load_fs()).stat(licenseFilepath); + if (licenseFileStats.isFile()) { + const licenseContent = yield (_fs || _load_fs()).readFile(licenseFilepath); + const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(licenseContent); + info.licenseText = licenseContent; -/***/ }), -/* 423 */ -/***/ (function(module, exports, __webpack_require__) { + const license = info.license; -module.exports = !__webpack_require__(69) && !__webpack_require__(138)(function(){ - return Object.defineProperty(__webpack_require__(137)('div'), 'a', {get: function(){ return 7; }}).a != 7; -}); + if (typeof license === 'string') { + if (inferredLicense && (0, (_util || _load_util()).isValidLicense)(inferredLicense) && !(0, (_util || _load_util()).isValidLicense)(license)) { + // some packages don't specify their license version but we can infer it based on their license file + const basicLicense = license.toLowerCase().replace(/(-like|\*)$/g, ''); + const expandedLicense = inferredLicense.toLowerCase(); + if (expandedLicense.startsWith(basicLicense)) { + // TODO consider doing something to notify the user + info.license = inferredLicense; + } + } + } else if (inferredLicense) { + // if there's no license then infer it based on the license file + info.license = inferredLicense; + } else { + // valid expression to refer to a license in a file + info.license = `SEE LICENSE IN ${licenseFile}`; + } + } + } -/***/ }), -/* 424 */ -/***/ (function(module, exports) { + if (typeof info.license === 'string') { + // sometimes licenses are known by different names, reduce them + info.license = LICENSE_RENAMES[info.license] || info.license; + } else if (typeof info.readme === 'string') { + // the license might be at the bottom of the README + const inferredLicense = (0, (_inferLicense || _load_inferLicense()).default)(info.readme); + if (inferredLicense) { + info.license = inferredLicense; + } + } -// fast apply, http://jsperf.lnkit.com/fast-apply/5 -module.exports = function(fn, args, that){ - var un = that === undefined; - switch(args.length){ - case 0: return un ? fn() - : fn.call(that); - case 1: return un ? fn(args[0]) - : fn.call(that, args[0]); - case 2: return un ? fn(args[0], args[1]) - : fn.call(that, args[0], args[1]); - case 3: return un ? fn(args[0], args[1], args[2]) - : fn.call(that, args[0], args[1], args[2]); - case 4: return un ? fn(args[0], args[1], args[2], args[3]) - : fn.call(that, args[0], args[1], args[2], args[3]); - } return fn.apply(that, args); -}; + for (const dependencyType of (_constants || _load_constants()).DEPENDENCY_TYPES) { + if (info[dependencyType] && typeof info[dependencyType] === 'object') { + delete info[dependencyType]['//']; + } + } + }); + + return function (_x, _x2, _x3, _x4, _x5) { + return _ref.apply(this, arguments); + }; +})(); /***/ }), -/* 425 */ +/* 439 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var create = __webpack_require__(429) - , descriptor = __webpack_require__(139) - , setToStringTag = __webpack_require__(140) - , IteratorPrototype = {}; -// 25.1.2.1.1 %IteratorPrototype%[@@iterator]() -__webpack_require__(54)(IteratorPrototype, __webpack_require__(26)('iterator'), function(){ return this; }); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = inferLicense; -module.exports = function(Constructor, NAME, next){ - Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); - setToStringTag(Constructor, NAME + ' Iterator'); -}; +var _licenses; -/***/ }), -/* 426 */ -/***/ (function(module, exports) { +function _load_licenses() { + return _licenses = _interopRequireDefault(__webpack_require__(440)); +} -module.exports = function(done, value){ - return {value: value, done: !!done}; -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 427 */ -/***/ (function(module, exports, __webpack_require__) { +function clean(str) { + return str.replace(/[^A-Za-z\s]/g, ' ').replace(/[\s]+/g, ' ').trim().toLowerCase(); +} -var global = __webpack_require__(29) - , macrotask = __webpack_require__(224).set - , Observer = global.MutationObserver || global.WebKitMutationObserver - , process = global.process - , Promise = global.Promise - , isNode = __webpack_require__(88)(process) == 'process'; +const REGEXES = { + Apache: [/Apache License\b/], + BSD: [/BSD\b/], + ISC: [/The ISC License/, /ISC\b/], + MIT: [/MIT\b/], + Unlicense: [/http:\/\/unlicense.org\//], + WTFPL: [/DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE/, /WTFPL\b/] +}; -module.exports = function(){ - var head, last, notify; +function inferLicense(license) { + // check if we have any explicit licenses + const cleanLicense = clean(license); + for (const licenseName in (_licenses || _load_licenses()).default) { + const testLicense = (_licenses || _load_licenses()).default[licenseName]; + if (cleanLicense.search(testLicense) >= 0) { + return licenseName; + } + } - var flush = function(){ - var parent, fn; - if(isNode && (parent = process.domain))parent.exit(); - while(head){ - fn = head.fn; - head = head.next; - try { - fn(); - } catch(e){ - if(head)notify(); - else last = undefined; - throw e; + // infer based on some keywords + for (const licenseName in REGEXES) { + for (const regex of REGEXES[licenseName]) { + if (license.search(regex) >= 0) { + return `${licenseName}*`; } - } last = undefined; - if(parent)parent.enter(); - }; - - // Node.js - if(isNode){ - notify = function(){ - process.nextTick(flush); - }; - // browsers with MutationObserver - } else if(Observer){ - var toggle = true - , node = document.createTextNode(''); - new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new - notify = function(){ - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if(Promise && Promise.resolve){ - var promise = Promise.resolve(); - notify = function(){ - promise.then(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function(){ - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global, flush); - }; + } } - return function(fn){ - var task = {fn: fn, next: undefined}; - if(last)last.next = task; - if(!head){ - head = task; - notify(); - } last = task; - }; -}; + return null; +} /***/ }), -/* 428 */ +/* 440 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -// 19.1.2.1 Object.assign(target, source, ...) -var getKeys = __webpack_require__(222) - , gOPS = __webpack_require__(431) - , pIE = __webpack_require__(434) - , toObject = __webpack_require__(145) - , IObject = __webpack_require__(216) - , $assign = Object.assign; -// should work with symbols and should have deterministic property order (V8 bug) -module.exports = !$assign || __webpack_require__(138)(function(){ - var A = {} - , B = {} - , S = Symbol() - , K = 'abcdefghijklmnopqrst'; - A[S] = 7; - K.split('').forEach(function(k){ B[k] = k; }); - return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; -}) ? function assign(target, source){ // eslint-disable-line no-unused-vars - var T = toObject(target) - , aLen = arguments.length - , index = 1 - , getSymbols = gOPS.f - , isEnum = pIE.f; - while(aLen > index){ - var S = IObject(arguments[index++]) - , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) - , length = keys.length - , j = 0 - , key; - while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; - } return T; -} : $assign; +Object.defineProperty(exports, "__esModule", { + value: true +}); -/***/ }), -/* 429 */ -/***/ (function(module, exports, __webpack_require__) { -// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) -var anObject = __webpack_require__(46) - , dPs = __webpack_require__(430) - , enumBugKeys = __webpack_require__(214) - , IE_PROTO = __webpack_require__(141)('IE_PROTO') - , Empty = function(){ /* empty */ } - , PROTOTYPE = 'prototype'; +/* eslint-disable max-len */ -// Create object with fake `null` prototype: use iframe Object with cleared prototype -var createDict = function(){ - // Thrash, waste and sodomy: IE GC bug - var iframe = __webpack_require__(137)('iframe') - , i = enumBugKeys.length - , lt = '<' - , gt = '>' - , iframeDocument; - iframe.style.display = 'none'; - __webpack_require__(215).appendChild(iframe); - iframe.src = 'javascript:'; // eslint-disable-line no-script-url - // createDict = iframe.contentWindow.Object; - // html.removeChild(iframe); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); - iframeDocument.close(); - createDict = iframeDocument.F; - while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; - return createDict(); -}; +/** + * DO NOT EDIT THIS FILE MANUALLY. + * THIS FILE WAS GENERATED BY "generate-licenses-js.js". + */ -module.exports = Object.create || function create(O, Properties){ - var result; - if(O !== null){ - Empty[PROTOTYPE] = anObject(O); - result = new Empty; - Empty[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO] = O; - } else result = createDict(); - return Properties === undefined ? result : dPs(result, Properties); +exports.default = { + 'Apache-2.0': new RegExp('(licensed under the apache license version the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license$|apache license version january http www apache org licenses terms and conditions for use reproduction and distribution definitions license shall mean the terms and conditions for use reproduction and distribution as defined by sections through of this document licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the license legal entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity for the purposes of this definition control means i the power direct or indirect to cause the direction or management of such entity whether by contract or otherwise or ii ownership of fifty percent or more of the outstanding shares or iii beneficial ownership of such entity you or your shall mean an individual or legal entity exercising permissions granted by this license source form shall mean the preferred form for making modifications including but not limited to software source code documentation source and configuration files object form shall mean any form resulting from mechanical transformation or translation of a source form including but not limited to compiled object code generated documentation and conversions to other media types work shall mean the work of authorship whether in source or object form made available under the license as indicated by a copyright notice that is included in or attached to the work an example is provided in the appendix below derivative works shall mean any work whether in source or object form that is based on or derived from the work and for which the editorial revisions annotations elaborations or other modifications represent as a whole an original work of authorship for the purposes of this license derivative works shall not include works that remain separable from or merely link or bind by name to the interfaces of the work and derivative works thereof contribution shall mean any work of authorship including the original version of the work and any modifications or additions to that work or derivative works thereof that is intentionally submitted to licensor for inclusion in the work by the copyright owner or by an individual or legal entity authorized to submit on behalf of the copyright owner for the purposes of this definition submitted means any form of electronic verbal or written communication sent to the licensor or its representatives including but not limited to communication on electronic mailing lists source code control systems and issue tracking systems that are managed by or on behalf of the licensor for the purpose of discussing and improving the work but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as not a contribution contributor shall mean licensor and any individual or legal entity on behalf of whom a contribution has been received by licensor and subsequently incorporated within the work grant of copyright license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable copyright license to reproduce prepare derivative works of publicly display publicly perform sublicense and distribute the work and such derivative works in source or object form grant of patent license subject to the terms and conditions of this license each contributor hereby grants to you a perpetual worldwide non exclusive no charge royalty free irrevocable except as stated in this section patent license to make have made use offer to sell sell import and otherwise transfer the work where such license applies only to those patent claims licensable by such contributor that are necessarily infringed by their contribution s alone or by combination of their contribution s with the work to which such contribution s was submitted if you institute patent litigation against any entity including a cross claim or counterclaim in a lawsuit alleging that the work or a contribution incorporated within the work constitutes direct or contributory patent infringement then any patent licenses granted to you under this license for that work shall terminate as of the date such litigation is filed redistribution you may reproduce and distribute copies of the work or derivative works thereof in any medium with or without modifications and in source or object form provided that you meet the following conditions a you must give any other recipients of the work or derivative works a copy of this license and b you must cause any modified files to carry prominent notices stating that you changed the files and c you must retain in the source form of any derivative works that you distribute all copyright patent trademark and attribution notices from the source form of the work excluding those notices that do not pertain to any part of the derivative works and d if the work includes a notice text file as part of its distribution then any derivative works that you distribute must include a readable copy of the attribution notices contained within such notice file excluding those notices that do not pertain to any part of the derivative works in at least one of the following places within a notice text file distributed as part of the derivative works within the source form or documentation if provided along with the derivative works or within a display generated by the derivative works if and wherever such third party notices normally appear the contents of the notice file are for informational purposes only and do not modify the license you may add your own attribution notices within derivative works that you distribute alongside or as an addendum to the notice text from the work provided that such additional attribution notices cannot be construed as modifying the license you may add your own copyright statement to your modifications and may provide additional or different license terms and conditions for use reproduction or distribution of your modifications or for any such derivative works as a whole provided your use reproduction and distribution of the work otherwise complies with the conditions stated in this license submission of contributions unless you explicitly state otherwise any contribution intentionally submitted for inclusion in the work by you to the licensor shall be under the terms and conditions of this license without any additional terms or conditions notwithstanding the above nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with licensor regarding such contributions trademarks this license does not grant permission to use the trade names trademarks service marks or product names of the licensor except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the notice file disclaimer of warranty unless required by applicable law or agreed to in writing licensor provides the work and each contributor provides its contributions on an as is basis without warranties or conditions of any kind either express or implied including without limitation any warranties or conditions of title non infringement merchantability or fitness for a particular purpose you are solely responsible for determining the appropriateness of using or redistributing the work and assume any risks associated with your exercise of permissions under this license limitation of liability in no event and under no legal theory whether in tort including negligence contract or otherwise unless required by applicable law such as deliberate and grossly negligent acts or agreed to in writing shall any contributor be liable to you for damages including any direct indirect special incidental or consequential damages of any character arising as a result of this license or out of the use or inability to use the work including but not limited to damages for loss of goodwill work stoppage computer failure or malfunction or any and all other commercial damages or losses even if such contributor has been advised of the possibility of such damages accepting warranty or additional liability while redistributing the work or derivative works thereof you may choose to offer and charge a fee for acceptance of support warranty indemnity or other liability obligations and or rights consistent with this license however in accepting such obligations you may act only on your own behalf and on your sole responsibility not on behalf of any other contributor and only if you agree to indemnify defend and hold each contributor harmless for any liability incurred by or claims asserted against such contributor by reason of your accepting any such warranty or additional liability end of terms and conditions$)', 'g'), + 'BSD-2-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this(.*?| )is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this(.*?| )even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$)', 'g'), + 'BSD-3-Clause': new RegExp('(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name of(.*?| )nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|(redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution the names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission this software is provided by the copyright holders and contributors as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall the copyright holders and contributors be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$|redistribution and use in source and binary forms with or without modification are permitted provided that the following conditions are met redistributions of source code must retain the above copyright notice this list of conditions and the following disclaimer redistributions in binary form must reproduce the above copyright notice this list of conditions and the following disclaimer in the documentation and or other materials provided with the distribution neither the name(.*?| )nor the names of(.*?| )contributors may be used to endorse or promote products derived from this software without specific prior written permission this software is provided by(.*?| )as is and any express or implied warranties including but not limited to the implied warranties of merchantability and fitness for a particular purpose are disclaimed in no event shall(.*?| )be liable for any direct indirect incidental special exemplary or consequential damages including but not limited to procurement of substitute goods or services loss of use data or profits or business interruption however caused and on any theory of liability whether in contract strict liability or tort including negligence or otherwise arising in any way out of the use of this software even if advised of the possibility of such damage$))', 'g'), + MIT: new RegExp('permission is hereby granted free of charge to any person obtaining a copy of this software and associated documentation files the software to deal in the software without restriction including without limitation the rights to use copy modify merge publish distribute sublicense and or sell copies of the software and to permit persons to whom the software is furnished to do so subject to the following conditions the above copyright notice and this permission notice shall be included in all copies or substantial portions of the software the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors or copyright holders be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software$', 'g'), + Unlicense: new RegExp('this is free and unencumbered software released into the public domain anyone is free to copy modify publish use compile sell or distribute this software either in source code form or as a compiled binary for any purpose commercial or non commercial and by any means in jurisdictions that recognize copyright laws the author or authors of this software dedicate any and all copyright interest in the software to the public domain we make this dedication for the benefit of the public at large and to the detriment of our heirs and successors we intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law the software is provided as is without warranty of any kind express or implied including but not limited to the warranties of merchantability fitness for a particular purpose and noninfringement in no event shall the authors be liable for any claim damages or other liability whether in an action of contract tort or otherwise arising from out of or in connection with the software or the use or other dealings in the software for more information please refer to wildcard$', 'g') }; - /***/ }), -/* 430 */ +/* 441 */ /***/ (function(module, exports, __webpack_require__) { -var dP = __webpack_require__(70) - , anObject = __webpack_require__(46) - , getKeys = __webpack_require__(222); +"use strict"; -module.exports = __webpack_require__(69) ? Object.defineProperties : function defineProperties(O, Properties){ - anObject(O); - var keys = getKeys(Properties) - , length = keys.length - , i = 0 - , P; - while(length > i)dP.f(O, P = keys[i++], Properties[P]); - return O; -}; -/***/ }), -/* 431 */ -/***/ (function(module, exports) { +Object.defineProperty(exports, "__esModule", { + value: true +}); -exports.f = Object.getOwnPropertySymbols; +exports.default = function (info, moduleLoc, lockfileFolder) { + // It won't work if we don't yet know what's the folder we'll use as root. It's not a + // big deal tho, because it only happens when trying to figure out the root, and we + // don't need to know the dependencies / devDependencies at this time. + if (!lockfileFolder) { + return; + } -/***/ }), -/* 432 */ -/***/ (function(module, exports, __webpack_require__) { + for (const dependencyType of (_constants || _load_constants()).DEPENDENCY_TYPES) { + const dependencies = info[dependencyType]; + if (!dependencies) { + continue; + } -// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) -var has = __webpack_require__(90) - , toObject = __webpack_require__(145) - , IE_PROTO = __webpack_require__(141)('IE_PROTO') - , ObjectProto = Object.prototype; + for (const name of Object.keys(dependencies)) { + let value = dependencies[name]; -module.exports = Object.getPrototypeOf || function(O){ - O = toObject(O); - if(has(O, IE_PROTO))return O[IE_PROTO]; - if(typeof O.constructor == 'function' && O instanceof O.constructor){ - return O.constructor.prototype; - } return O instanceof Object ? ObjectProto : null; -}; + if (path.isAbsolute(value)) { + value = (_fileResolver || _load_fileResolver()).FILE_PROTOCOL_PREFIX + value; + } -/***/ }), -/* 433 */ -/***/ (function(module, exports, __webpack_require__) { + let prefix; + if (value.startsWith((_fileResolver || _load_fileResolver()).FILE_PROTOCOL_PREFIX)) { + prefix = (_fileResolver || _load_fileResolver()).FILE_PROTOCOL_PREFIX; + } else if (value.startsWith((_linkResolver || _load_linkResolver()).LINK_PROTOCOL_PREFIX)) { + prefix = (_linkResolver || _load_linkResolver()).LINK_PROTOCOL_PREFIX; + } else { + continue; + } + (0, (_invariant || _load_invariant()).default)(prefix, 'prefix is definitely defined here'); -var has = __webpack_require__(90) - , toIObject = __webpack_require__(143) - , arrayIndexOf = __webpack_require__(420)(false) - , IE_PROTO = __webpack_require__(141)('IE_PROTO'); + const unprefixed = value.substr(prefix.length); + const hasPathPrefix = /^\.(\/|$)/.test(unprefixed); -module.exports = function(object, names){ - var O = toIObject(object) - , i = 0 - , result = [] - , key; - for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while(names.length > i)if(has(O, key = names[i++])){ - ~arrayIndexOf(result, key) || result.push(key); + const absoluteTarget = path.resolve(lockfileFolder, moduleLoc, unprefixed); + let relativeTarget = path.relative(lockfileFolder, absoluteTarget) || '.'; + + if (hasPathPrefix) { + // TODO: This logic should be removed during the next major bump + // If the original value was using the "./" prefix, then we output a similar path. + // We need to do this because otherwise it would cause problems with already existing + // lockfile, which would see some of their entries being unrecognized. + relativeTarget = relativeTarget.replace(/^(?!\.{0,2}\/)/, `./`); + } + + dependencies[name] = prefix + relativeTarget.replace(/\\/g, '/'); + } } - return result; }; -/***/ }), -/* 434 */ -/***/ (function(module, exports) { +var _constants; + +function _load_constants() { + return _constants = __webpack_require__(6); +} + +var _fileResolver; + +function _load_fileResolver() { + return _fileResolver = __webpack_require__(162); +} -exports.f = {}.propertyIsEnumerable; +var _linkResolver; -/***/ }), -/* 435 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_linkResolver() { + return _linkResolver = __webpack_require__(269); +} -var hide = __webpack_require__(54); -module.exports = function(target, src, safe){ - for(var key in src){ - if(safe && target[key])target[key] = src[key]; - else hide(target, key, src[key]); - } return target; -}; +var _invariant; -/***/ }), -/* 436 */ -/***/ (function(module, exports, __webpack_require__) { +function _load_invariant() { + return _invariant = _interopRequireDefault(__webpack_require__(7)); +} + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = __webpack_require__(54); +const path = __webpack_require__(0); /***/ }), -/* 437 */ +/* 442 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var global = __webpack_require__(29) - , core = __webpack_require__(31) - , dP = __webpack_require__(70) - , DESCRIPTORS = __webpack_require__(69) - , SPECIES = __webpack_require__(26)('species'); -module.exports = function(KEY){ - var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY]; - if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { - configurable: true, - get: function(){ return this; } - }); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.default = { + autohr: 'author', + autor: 'author', + contributers: 'contributors', + depdenencies: 'dependencies', + dependancies: 'dependencies', + dependecies: 'dependencies', + depends: 'dependencies', + 'dev-dependencies': 'devDependencies', + devDependences: 'devDependencies', + devDepenencies: 'devDependencies', + devEependencies: 'devDependencies', + devdependencies: 'devDependencies', + hampage: 'homepage', + hompage: 'homepage', + prefereGlobal: 'preferGlobal', + publicationConfig: 'publishConfig', + repo: 'repository', + repostitory: 'repository', + script: 'scripts' }; /***/ }), -/* 438 */ +/* 443 */ /***/ (function(module, exports, __webpack_require__) { -// 7.3.20 SpeciesConstructor(O, defaultConstructor) -var anObject = __webpack_require__(46) - , aFunction = __webpack_require__(134) - , SPECIES = __webpack_require__(26)('species'); -module.exports = function(O, D){ - var C = anObject(O).constructor, S; - return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); -}; +"use strict"; -/***/ }), -/* 439 */ -/***/ (function(module, exports, __webpack_require__) { -var toInteger = __webpack_require__(142) - , defined = __webpack_require__(136); -// true -> String#at -// false -> String#codePointAt -module.exports = function(TO_STRING){ - return function(that, pos){ - var s = String(defined(that)) - , i = toInteger(pos) - , l = s.length - , a, b; - if(i < 0 || i >= l)return TO_STRING ? '' : undefined; - a = s.charCodeAt(i); - return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff - ? TO_STRING ? s.charAt(i) : a - : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; - }; -}; +Object.defineProperty(exports, "__esModule", { + value: true +}); -/***/ }), -/* 440 */ -/***/ (function(module, exports, __webpack_require__) { +var _slicedToArray2; -var toInteger = __webpack_require__(142) - , max = Math.max - , min = Math.min; -module.exports = function(index, length){ - index = toInteger(index); - return index < 0 ? max(index + length, 0) : min(index, length); -}; +function _load_slicedToArray() { + return _slicedToArray2 = _interopRequireDefault(__webpack_require__(15)); +} -/***/ }), -/* 441 */ -/***/ (function(module, exports, __webpack_require__) { +exports.default = parsePackageName; -// 7.1.1 ToPrimitive(input [, PreferredType]) -var isObject = __webpack_require__(91); -// instead of the ES6 spec version, we didn't implement @@toPrimitive case -// and the second argument - flag - preferred type is a string -module.exports = function(it, S){ - if(!isObject(it))return it; - var fn, val; - if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; - if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; - throw TypeError("Can't convert object to primitive value"); -}; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -/***/ }), -/* 442 */ -/***/ (function(module, exports, __webpack_require__) { +const PKG_INPUT = /(^\S?[^\s@]+)(?:@(\S+))?$/; -var anObject = __webpack_require__(46) - , get = __webpack_require__(146); -module.exports = __webpack_require__(31).getIterator = function(it){ - var iterFn = get(it); - if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); - return anObject(iterFn.call(it)); -}; +function parsePackageName(input) { + var _PKG_INPUT$exec = PKG_INPUT.exec(input), + _PKG_INPUT$exec2 = (0, (_slicedToArray2 || _load_slicedToArray()).default)(_PKG_INPUT$exec, 3); -/***/ }), -/* 443 */ -/***/ (function(module, exports, __webpack_require__) { + const name = _PKG_INPUT$exec2[1], + version = _PKG_INPUT$exec2[2]; -var classof = __webpack_require__(135) - , ITERATOR = __webpack_require__(26)('iterator') - , Iterators = __webpack_require__(55); -module.exports = __webpack_require__(31).isIterable = function(it){ - var O = Object(it); - return O[ITERATOR] !== undefined - || '@@iterator' in O - || Iterators.hasOwnProperty(classof(O)); -}; + return { name, version }; +} /***/ }), /* 444 */ @@ -85535,43 +89236,85 @@ module.exports = __webpack_require__(31).isIterable = function(it){ "use strict"; -var ctx = __webpack_require__(68) - , $export = __webpack_require__(89) - , toObject = __webpack_require__(145) - , call = __webpack_require__(218) - , isArrayIter = __webpack_require__(217) - , toLength = __webpack_require__(144) - , createProperty = __webpack_require__(421) - , getIterFn = __webpack_require__(146); -$export($export.S + $export.F * !__webpack_require__(220)(function(iter){ Array.from(iter); }), 'Array', { - // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) - from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ - var O = toObject(arrayLike) - , C = typeof this == 'function' ? this : Array - , aLen = arguments.length - , mapfn = aLen > 1 ? arguments[1] : undefined - , mapping = mapfn !== undefined - , index = 0 - , iterFn = getIterFn(O) - , length, result, step, iterator; - if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); - // if object isn't iterable or it's array with default iterator - use simple case - if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ - for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ - createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); - } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.findRc = findRc; + +var _fs; + +function _load_fs() { + return _fs = __webpack_require__(5); +} + +var _path; + +function _load_path() { + return _path = _interopRequireWildcard(__webpack_require__(0)); +} + +function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } + +const etc = '/etc'; +const isWin = process.platform === 'win32'; +const home = isWin ? process.env.USERPROFILE : process.env.HOME; + +function getRcPaths(name, cwd) { + const configPaths = []; + + function addConfigPath() { + configPaths.push((_path || _load_path()).join(...arguments)); + } + + if (!isWin) { + addConfigPath(etc, name, 'config'); + addConfigPath(etc, `${name}rc`); + } + + if (home) { + addConfigPath(home, '.config', name, 'config'); + addConfigPath(home, '.config', name); + addConfigPath(home, `.${name}`, 'config'); + addConfigPath(home, `.${name}rc`); + } + + // add .yarnrc locations relative to the cwd + while (true) { + configPaths.unshift((_path || _load_path()).join(cwd, `.${name}rc`)); + + const upperCwd = (_path || _load_path()).dirname(cwd); + if (upperCwd === cwd) { + // we've reached the root + break; } else { - length = toLength(O.length); - for(result = new C(length); length > index; index++){ - createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); - } + // continue since there's still more directories to search + cwd = upperCwd; } - result.length = index; - return result; } -}); + const envVariable = `${name}_config`.toUpperCase(); + + if (process.env[envVariable]) { + addConfigPath(process.env[envVariable]); + } + + return configPaths; +} + +function parseRcPaths(paths, parser) { + return Object.assign({}, ...paths.map(path => { + try { + return parser((0, (_fs || _load_fs()).readFileSync)(path).toString(), path); + } catch (error) { + return {}; + } + })); +} + +function findRc(name, cwd, parser) { + return parseRcPaths(getRcPaths(name, cwd), parser); +} /***/ }), /* 445 */ @@ -85579,4201 +89322,4057 @@ $export($export.S + $export.F * !__webpack_require__(220)(function(iter){ Array. "use strict"; -var addToUnscopables = __webpack_require__(418) - , step = __webpack_require__(426) - , Iterators = __webpack_require__(55) - , toIObject = __webpack_require__(143); -// 22.1.3.4 Array.prototype.entries() -// 22.1.3.13 Array.prototype.keys() -// 22.1.3.29 Array.prototype.values() -// 22.1.3.30 Array.prototype[@@iterator]() -module.exports = __webpack_require__(219)(Array, 'Array', function(iterated, kind){ - this._t = toIObject(iterated); // target - this._i = 0; // next index - this._k = kind; // kind -// 22.1.5.2.1 %ArrayIteratorPrototype%.next() -}, function(){ - var O = this._t - , kind = this._k - , index = this._i++; - if(!O || index >= O.length){ - this._t = undefined; - return step(1); +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.satisfiesWithPreleases = satisfiesWithPreleases; +const semver = __webpack_require__(22); + +/** + * Returns whether the given semver version satisfies the given range. Notably this supports + * prerelease versions so that "2.0.0-rc.0" satisfies the range ">=1.0.0", for example. + */ + +function satisfiesWithPreleases(version, range) { + let loose = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + + let semverRange; + try { + // $FlowFixMe: Add a definition for the Range class + semverRange = new semver.Range(range, loose); + } catch (err) { + return false; } - if(kind == 'keys' )return step(0, index); - if(kind == 'values')return step(0, O[index]); - return step(0, [index, O[index]]); -}, 'values'); -// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) -Iterators.Arguments = Iterators.Array; + if (!version) { + return false; + } + const semverVersion = new semver.SemVer(version, semverRange.loose); -addToUnscopables('keys'); -addToUnscopables('values'); -addToUnscopables('entries'); + // A range has multiple sets of comparators. A version must satisfy all comparators in a set + // and at least one set to satisfy the range. + return semverRange.set.some(comparatorSet => { + // node-semver converts ~ and ^ ranges into pairs of >= and < ranges but the upper bounds don't + // properly exclude prerelease versions. For example, "^1.0.0" is converted to ">=1.0.0 <2.0.0", + // which includes "2.0.0-pre" since prerelease versions are lower than their non-prerelease + // counterparts. As a practical workaround we make upper-bound ranges exclude prereleases and + // convert "<2.0.0" to "<2.0.0-0", for example. + comparatorSet = comparatorSet.map(comparator => { + if (comparator.operator !== '<' || !comparator.value || comparator.semver.prerelease.length) { + return comparator; + } + + // "0" is the lowest prerelease version + comparator.semver.inc('pre', 0); + + const comparatorString = comparator.operator + comparator.semver.version; + // $FlowFixMe: Add a definition for the Comparator class + return new semver.Comparator(comparatorString, comparator.loose); + }); + + return !comparatorSet.some(comparator => !comparator.test(semverVersion)); + }); +} /***/ }), /* 446 */ /***/ (function(module, exports, __webpack_require__) { -// 19.1.3.1 Object.assign(target, source) -var $export = __webpack_require__(89); - -$export($export.S + $export.F, 'Object', {assign: __webpack_require__(428)}); +module.exports = { "default": __webpack_require__(459), __esModule: true }; /***/ }), /* 447 */ -/***/ (function(module, exports) { - +/***/ (function(module, exports, __webpack_require__) { +module.exports = { "default": __webpack_require__(460), __esModule: true }; /***/ }), /* 448 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; +module.exports = { "default": __webpack_require__(461), __esModule: true }; -var LIBRARY = __webpack_require__(221) - , global = __webpack_require__(29) - , ctx = __webpack_require__(68) - , classof = __webpack_require__(135) - , $export = __webpack_require__(89) - , isObject = __webpack_require__(91) - , aFunction = __webpack_require__(134) - , anInstance = __webpack_require__(419) - , forOf = __webpack_require__(422) - , speciesConstructor = __webpack_require__(438) - , task = __webpack_require__(224).set - , microtask = __webpack_require__(427)() - , PROMISE = 'Promise' - , TypeError = global.TypeError - , process = global.process - , $Promise = global[PROMISE] - , process = global.process - , isNode = classof(process) == 'process' - , empty = function(){ /* empty */ } - , Internal, GenericPromiseCapability, Wrapper; +/***/ }), +/* 449 */ +/***/ (function(module, exports, __webpack_require__) { -var USE_NATIVE = !!function(){ - try { - // correct subclassing with @@species support - var promise = $Promise.resolve(1) - , FakePromise = (promise.constructor = {})[__webpack_require__(26)('species')] = function(exec){ exec(empty, empty); }; - // unhandled rejections tracking support, NodeJS Promise without it fails @@species test - return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; - } catch(e){ /* empty */ } -}(); +module.exports = { "default": __webpack_require__(462), __esModule: true }; -// helpers -var sameConstructor = function(a, b){ - // with library wrapper special case - return a === b || a === $Promise && b === Wrapper; -}; -var isThenable = function(it){ - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; -}; -var newPromiseCapability = function(C){ - return sameConstructor($Promise, C) - ? new PromiseCapability(C) - : new GenericPromiseCapability(C); -}; -var PromiseCapability = GenericPromiseCapability = function(C){ - var resolve, reject; - this.promise = new C(function($$resolve, $$reject){ - if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction(resolve); - this.reject = aFunction(reject); -}; -var perform = function(exec){ - try { - exec(); - } catch(e){ - return {error: e}; - } -}; -var notify = function(promise, isReject){ - if(promise._n)return; - promise._n = true; - var chain = promise._c; - microtask(function(){ - var value = promise._v - , ok = promise._s == 1 - , i = 0; - var run = function(reaction){ - var handler = ok ? reaction.ok : reaction.fail - , resolve = reaction.resolve - , reject = reaction.reject - , domain = reaction.domain - , result, then; - try { - if(handler){ - if(!ok){ - if(promise._h == 2)onHandleUnhandled(promise); - promise._h = 1; - } - if(handler === true)result = value; - else { - if(domain)domain.enter(); - result = handler(value); - if(domain)domain.exit(); - } - if(result === reaction.promise){ - reject(TypeError('Promise-chain cycle')); - } else if(then = isThenable(result)){ - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch(e){ - reject(e); - } - }; - while(chain.length > i)run(chain[i++]); // variable length - can't use forEach - promise._c = []; - promise._n = false; - if(isReject && !promise._h)onUnhandled(promise); - }); -}; -var onUnhandled = function(promise){ - task.call(global, function(){ - var value = promise._v - , abrupt, handler, console; - if(isUnhandled(promise)){ - abrupt = perform(function(){ - if(isNode){ - process.emit('unhandledRejection', value, promise); - } else if(handler = global.onunhandledrejection){ - handler({promise: promise, reason: value}); - } else if((console = global.console) && console.error){ - console.error('Unhandled promise rejection', value); - } - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - promise._h = isNode || isUnhandled(promise) ? 2 : 1; - } promise._a = undefined; - if(abrupt)throw abrupt.error; - }); -}; -var isUnhandled = function(promise){ - if(promise._h == 1)return false; - var chain = promise._a || promise._c - , i = 0 - , reaction; - while(chain.length > i){ - reaction = chain[i++]; - if(reaction.fail || !isUnhandled(reaction.promise))return false; - } return true; -}; -var onHandleUnhandled = function(promise){ - task.call(global, function(){ - var handler; - if(isNode){ - process.emit('rejectionHandled', promise); - } else if(handler = global.onrejectionhandled){ - handler({promise: promise, reason: promise._v}); - } - }); -}; -var $reject = function(value){ - var promise = this; - if(promise._d)return; - promise._d = true; - promise = promise._w || promise; // unwrap - promise._v = value; - promise._s = 2; - if(!promise._a)promise._a = promise._c.slice(); - notify(promise, true); -}; -var $resolve = function(value){ - var promise = this - , then; - if(promise._d)return; - promise._d = true; - promise = promise._w || promise; // unwrap - try { - if(promise === value)throw TypeError("Promise can't be resolved itself"); - if(then = isThenable(value)){ - microtask(function(){ - var wrapper = {_w: promise, _d: false}; // wrap - try { - then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); - } catch(e){ - $reject.call(wrapper, e); - } - }); - } else { - promise._v = value; - promise._s = 1; - notify(promise, false); - } - } catch(e){ - $reject.call({_w: promise, _d: false}, e); // wrap - } -}; +/***/ }), +/* 450 */ +/***/ (function(module, exports, __webpack_require__) { -// constructor polyfill -if(!USE_NATIVE){ - // 25.4.3.1 Promise(executor) - $Promise = function Promise(executor){ - anInstance(this, $Promise, PROMISE, '_h'); - aFunction(executor); - Internal.call(this); - try { - executor(ctx($resolve, this, 1), ctx($reject, this, 1)); - } catch(err){ - $reject.call(this, err); - } - }; - Internal = function Promise(executor){ - this._c = []; // <- awaiting reactions - this._a = undefined; // <- checked in isUnhandled reactions - this._s = 0; // <- state - this._d = false; // <- done - this._v = undefined; // <- value - this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled - this._n = false; // <- notify - }; - Internal.prototype = __webpack_require__(435)($Promise.prototype, { - // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) - then: function then(onFulfilled, onRejected){ - var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = isNode ? process.domain : undefined; - this._c.push(reaction); - if(this._a)this._a.push(reaction); - if(this._s)notify(this, false); - return reaction.promise; - }, - // 25.4.5.1 Promise.prototype.catch(onRejected) - 'catch': function(onRejected){ - return this.then(undefined, onRejected); - } - }); - PromiseCapability = function(){ - var promise = new Internal; - this.promise = promise; - this.resolve = ctx($resolve, promise, 1); - this.reject = ctx($reject, promise, 1); - }; +var DuplexStream = __webpack_require__(594) + , util = __webpack_require__(2) + + +function BufferList (callback) { + if (!(this instanceof BufferList)) + return new BufferList(callback) + + this._bufs = [] + this.length = 0 + + if (typeof callback == 'function') { + this._callback = callback + + var piper = function piper (err) { + if (this._callback) { + this._callback(err) + this._callback = null + } + }.bind(this) + + this.on('pipe', function onPipe (src) { + src.on('error', piper) + }) + this.on('unpipe', function onUnpipe (src) { + src.removeListener('error', piper) + }) + } else { + this.append(callback) + } + + DuplexStream.call(this) } -$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); -__webpack_require__(140)($Promise, PROMISE); -__webpack_require__(437)(PROMISE); -Wrapper = __webpack_require__(31)[PROMISE]; -// statics -$export($export.S + $export.F * !USE_NATIVE, PROMISE, { - // 25.4.4.5 Promise.reject(r) - reject: function reject(r){ - var capability = newPromiseCapability(this) - , $$reject = capability.reject; - $$reject(r); - return capability.promise; +util.inherits(BufferList, DuplexStream) + + +BufferList.prototype._offset = function _offset (offset) { + var tot = 0, i = 0, _t + if (offset === 0) return [ 0, 0 ] + for (; i < this._bufs.length; i++) { + _t = tot + this._bufs[i].length + if (offset < _t || i == this._bufs.length - 1) + return [ i, offset - tot ] + tot = _t } -}); -$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { - // 25.4.4.6 Promise.resolve(x) - resolve: function resolve(x){ - // instanceof instead of internal slot check because we should fix it without replacement native Promise core - if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; - var capability = newPromiseCapability(this) - , $$resolve = capability.resolve; - $$resolve(x); - return capability.promise; +} + + +BufferList.prototype.append = function append (buf) { + var i = 0 + + if (Buffer.isBuffer(buf)) { + this._appendBuffer(buf); + } else if (Array.isArray(buf)) { + for (; i < buf.length; i++) + this.append(buf[i]) + } else if (buf instanceof BufferList) { + // unwrap argument into individual BufferLists + for (; i < buf._bufs.length; i++) + this.append(buf._bufs[i]) + } else if (buf != null) { + // coerce number arguments to strings, since Buffer(number) does + // uninitialized memory allocation + if (typeof buf == 'number') + buf = buf.toString() + + this._appendBuffer(new Buffer(buf)); } -}); -$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(220)(function(iter){ - $Promise.all(iter)['catch'](empty); -})), PROMISE, { - // 25.4.4.1 Promise.all(iterable) - all: function all(iterable){ - var C = this - , capability = newPromiseCapability(C) - , resolve = capability.resolve - , reject = capability.reject; - var abrupt = perform(function(){ - var values = [] - , index = 0 - , remaining = 1; - forOf(iterable, false, function(promise){ - var $index = index++ - , alreadyCalled = false; - values.push(undefined); - remaining++; - C.resolve(promise).then(function(value){ - if(alreadyCalled)return; - alreadyCalled = true; - values[$index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if(abrupt)reject(abrupt.error); - return capability.promise; - }, - // 25.4.4.4 Promise.race(iterable) - race: function race(iterable){ - var C = this - , capability = newPromiseCapability(C) - , reject = capability.reject; - var abrupt = perform(function(){ - forOf(iterable, false, function(promise){ - C.resolve(promise).then(capability.resolve, reject); - }); - }); - if(abrupt)reject(abrupt.error); - return capability.promise; + + return this +} + + +BufferList.prototype._appendBuffer = function appendBuffer (buf) { + this._bufs.push(buf) + this.length += buf.length +} + + +BufferList.prototype._write = function _write (buf, encoding, callback) { + this._appendBuffer(buf) + + if (typeof callback == 'function') + callback() +} + + +BufferList.prototype._read = function _read (size) { + if (!this.length) + return this.push(null) + + size = Math.min(size, this.length) + this.push(this.slice(0, size)) + this.consume(size) +} + + +BufferList.prototype.end = function end (chunk) { + DuplexStream.prototype.end.call(this, chunk) + + if (this._callback) { + this._callback(null, this.slice()) + this._callback = null } -}); +} -/***/ }), -/* 449 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; +BufferList.prototype.get = function get (index) { + return this.slice(index, index + 1)[0] +} -var arrayFindIndex = __webpack_require__(319); -module.exports = function () { - var unhandledRejections = []; +BufferList.prototype.slice = function slice (start, end) { + if (typeof start == 'number' && start < 0) + start += this.length + if (typeof end == 'number' && end < 0) + end += this.length + return this.copy(null, 0, start, end) +} - function onUnhandledRejection(reason, promise) { - unhandledRejections.push({reason: reason, promise: promise}); - } - function onRejectionHandled(promise) { - var index = arrayFindIndex(unhandledRejections, function (x) { - return x.promise === promise; - }); +BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { + if (typeof srcStart != 'number' || srcStart < 0) + srcStart = 0 + if (typeof srcEnd != 'number' || srcEnd > this.length) + srcEnd = this.length + if (srcStart >= this.length) + return dst || new Buffer(0) + if (srcEnd <= 0) + return dst || new Buffer(0) - unhandledRejections.splice(index, 1); - } + var copy = !!dst + , off = this._offset(srcStart) + , len = srcEnd - srcStart + , bytes = len + , bufoff = (copy && dstStart) || 0 + , start = off[1] + , l + , i - function currentlyUnhandled() { - return unhandledRejections.map(function (entry) { - return { - reason: entry.reason, - promise: entry.promise - }; - }); - } + // copy/slice everything + if (srcStart === 0 && srcEnd == this.length) { + if (!copy) { // slice, but full concat if multiple buffers + return this._bufs.length === 1 + ? this._bufs[0] + : Buffer.concat(this._bufs, this.length) + } - return { - onUnhandledRejection: onUnhandledRejection, - onRejectionHandled: onRejectionHandled, - currentlyUnhandled: currentlyUnhandled - }; -}; + // copy, need to copy individual buffers + for (i = 0; i < this._bufs.length; i++) { + this._bufs[i].copy(dst, bufoff) + bufoff += this._bufs[i].length + } + return dst + } -/***/ }), -/* 450 */ -/***/ (function(module, exports, __webpack_require__) { + // easy, cheap case where it's a subset of one of the buffers + if (bytes <= this._bufs[off[0]].length - start) { + return copy + ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) + : this._bufs[off[0]].slice(start, start + bytes) + } -"use strict"; + if (!copy) // a slice, we need something to copy in to + dst = new Buffer(len) -var core = __webpack_require__(449); + for (i = off[0]; i < this._bufs.length; i++) { + l = this._bufs[i].length - start -module.exports = function (p) { - p = p || process; - var c = core(); + if (bytes > l) { + this._bufs[i].copy(dst, bufoff, start) + } else { + this._bufs[i].copy(dst, bufoff, start, start + bytes) + break + } - p.on('unhandledRejection', c.onUnhandledRejection); - p.on('rejectionHandled', c.onRejectionHandled); + bufoff += l + bytes -= l - return c.currentlyUnhandled; -}; + if (start) + start = 0 + } + return dst +} -/***/ }), -/* 451 */ -/***/ (function(module, exports) { +BufferList.prototype.shallowSlice = function shallowSlice (start, end) { + start = start || 0 + end = end || this.length + if (start < 0) + start += this.length + if (end < 0) + end += this.length -var defaultConfig = { - uncaughtException: false, - SIGINT: true, - SIGTERM: true, - SIGQUIT: true + var startOffset = this._offset(start) + , endOffset = this._offset(end) + , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) + + if (endOffset[1] == 0) + buffers.pop() + else + buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) + + if (startOffset[1] != 0) + buffers[0] = buffers[0].slice(startOffset[1]) + + return new BufferList(buffers) } -var DEBUG = false +BufferList.prototype.toString = function toString (encoding, start, end) { + return this.slice(start, end).toString(encoding) +} -function ON_DEATH (callback) { - var handlers = []; - Object.keys(defaultConfig).forEach(function(key) { - var val = defaultConfig[key] - var handler = null; - if (val) { - if (DEBUG) { - handler = function() { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift(key) - console.log('Trapped ' + key) - callback.apply(null, args) - }; - process.on(key, handler) - } else { - handler = function() { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift(key) - callback.apply(null, args) - } - process.on(key, handler) - } - handlers.push([key, handler]) +BufferList.prototype.consume = function consume (bytes) { + while (this._bufs.length) { + if (bytes >= this._bufs[0].length) { + bytes -= this._bufs[0].length + this.length -= this._bufs[0].length + this._bufs.shift() + } else { + this._bufs[0] = this._bufs[0].slice(bytes) + this.length -= bytes + break } - }) - return function OFF_DEATH() { - handlers.forEach(function (args) { - var key = args[0]; - var handler = args[1]; - process.removeListener(key, handler); - }) } + return this } -module.exports = function (arg) { - if (typeof arg === 'object') { - if (arg['debug']) - DEBUG = arg.debug - if (arg['DEBUG']) - DEBUG = arg.DEBUG - delete arg.debug; delete arg.DEBUG; - Object.keys(arg).forEach(function(key) { - defaultConfig[key] = arg[key] - }) +BufferList.prototype.duplicate = function duplicate () { + var i = 0 + , copy = new BufferList() - if (DEBUG) - console.log('ON_DEATH: debug mode enabled for pid [%d]', process.pid) + for (; i < this._bufs.length; i++) + copy.append(this._bufs[i]) - return ON_DEATH - } else if (typeof arg === 'function') { - return ON_DEATH(arg) - } + return copy +} + + +BufferList.prototype.destroy = function destroy () { + this._bufs.length = 0 + this.length = 0 + this.push(null) } +;(function () { + var methods = { + 'readDoubleBE' : 8 + , 'readDoubleLE' : 8 + , 'readFloatBE' : 4 + , 'readFloatLE' : 4 + , 'readInt32BE' : 4 + , 'readInt32LE' : 4 + , 'readUInt32BE' : 4 + , 'readUInt32LE' : 4 + , 'readInt16BE' : 2 + , 'readInt16LE' : 2 + , 'readUInt16BE' : 2 + , 'readUInt16LE' : 2 + , 'readInt8' : 1 + , 'readUInt8' : 1 + } + + for (var m in methods) { + (function (m) { + BufferList.prototype[m] = function (offset) { + return this.slice(offset, offset + methods[m])[m](0) + } + }(m)) + } +}()) + + +module.exports = BufferList + /***/ }), -/* 452 */ +/* 451 */ /***/ (function(module, exports, __webpack_require__) { -/** - * This is the web browser implementation of `debug()`. +"use strict"; +/*! + * braces <https://github.com/jonschlinkert/braces> * - * Expose `debug()` as the module. + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT license. */ -exports = module.exports = __webpack_require__(227); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + /** - * Colors. + * Module dependencies */ -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +var expand = __webpack_require__(479); +var repeat = __webpack_require__(310); +var tokens = __webpack_require__(586); /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Expose `braces` + */ + +module.exports = function(str, options) { + if (typeof str !== 'string') { + throw new Error('braces expects a string'); + } + return braces(str, options); +}; + +/** + * Expand `{foo,bar}` or `{1..5}` braces in the + * given `string`. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * @param {String} `str` + * @param {Array} `arr` + * @param {Object} `options` + * @return {Array} */ -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; +function braces(str, arr, options) { + if (str === '') { + return []; + } + + if (!Array.isArray(arr)) { + options = arr; + arr = []; + } + + var opts = options || {}; + arr = arr || []; + + if (typeof opts.nodupes === 'undefined') { + opts.nodupes = true; + } + + var fn = opts.fn; + var es6; + + if (typeof opts === 'function') { + fn = opts; + opts = {}; + } + + if (!(patternRe instanceof RegExp)) { + patternRe = patternRegex(); + } + + var matches = str.match(patternRe) || []; + var m = matches[0]; + + switch(m) { + case '\\,': + return escapeCommas(str, arr, opts); + case '\\.': + return escapeDots(str, arr, opts); + case '\/.': + return escapePaths(str, arr, opts); + case ' ': + return splitWhitespace(str); + case '{,}': + return exponential(str, opts, braces); + case '{}': + return emptyBraces(str, arr, opts); + case '\\{': + case '\\}': + return escapeBraces(str, arr, opts); + case '${': + if (!/\{[^{]+\{/.test(str)) { + return arr.concat(str); + } else { + es6 = true; + str = tokens.before(str, es6Regex()); + } + } + + if (!(braceRe instanceof RegExp)) { + braceRe = braceRegex(); + } + + var match = braceRe.exec(str); + if (match == null) { + return [str]; } - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + var outter = match[1]; + var inner = match[2]; + if (inner === '') { return [str]; } -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + var segs, segsLength; -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; + if (inner.indexOf('..') !== -1) { + segs = expand(inner, opts, fn) || inner.split(','); + segsLength = segs.length; + } else if (inner[0] === '"' || inner[0] === '\'') { + return arr.concat(str.split(/['"]/).join('')); -/** - * Colorize log arguments if enabled. - * - * @api public - */ + } else { + segs = inner.split(','); + if (opts.makeRe) { + return braces(str.replace(outter, wrap(segs, '|')), opts); + } -function formatArgs(args) { - var useColors = this.useColors; + segsLength = segs.length; + if (segsLength === 1 && opts.bash) { + segs[0] = wrap(segs[0], '\\'); + } + } - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + var len = segs.length; + var i = 0, val; - if (!useColors) return; + while (len--) { + var path = segs[i++]; - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + if (/(\.[^.\/])/.test(path)) { + if (segsLength > 1) { + return segs; + } else { + return [str]; + } + } - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + val = splice(str, outter, path); + + if (/\{[^{}]+?\}/.test(val)) { + arr = braces(val, arr, opts); + } else if (val !== '') { + if (opts.nodupes && arr.indexOf(val) !== -1) { continue; } + arr.push(es6 ? tokens.after(val) : val); } - }); + } - args.splice(lastC, 0, c); + if (opts.strict) { return filter(arr, filterEmpty); } + return arr; } /** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". + * Expand exponential ranges * - * @api public + * `a{,}{,}` => ['a', 'a', 'a', 'a'] */ -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} +function exponential(str, options, fn) { + if (typeof options === 'function') { + fn = options; + options = null; + } -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ + var opts = options || {}; + var esc = '__ESC_EXP__'; + var exp = 0; + var res; + + var parts = str.split('{,}'); + if (opts.nodupes) { + return fn(parts.join(''), opts); + } + + exp = parts.length - 1; + res = fn(parts.join(esc), opts); + var len = res.length; + var arr = []; + var i = 0; + + while (len--) { + var ele = res[i++]; + var idx = ele.indexOf(esc); + + if (idx === -1) { + arr.push(ele); -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); } else { - exports.storage.debug = namespaces; + ele = ele.split('__ESC_EXP__').join(''); + if (!!ele && opts.nodupes !== false) { + arr.push(ele); + + } else { + var num = Math.pow(2, exp); + arr.push.apply(arr, repeat(ele, num)); + } } - } catch(e) {} + } + return arr; } /** - * Load `namespaces`. + * Wrap a value with parens, brackets or braces, + * based on the given character/separator. * - * @return {String} returns the previously persisted debug modes - * @api private + * @param {String|Array} `val` + * @param {String} `ch` + * @return {String} */ -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; +function wrap(val, ch) { + if (ch === '|') { + return '(' + val.join(ch) + ')'; + } + if (ch === ',') { + return '{' + val.join(ch) + '}'; + } + if (ch === '-') { + return '[' + val.join(ch) + ']'; + } + if (ch === '\\') { + return '\\{' + val + '\\}'; } - - return r; } /** - * Enable namespaces listed in `localStorage.debug` initially. + * Handle empty braces: `{}` */ -exports.enable(load()); +function emptyBraces(str, arr, opts) { + return braces(str.split('{}').join('\\{\\}'), arr, opts); +} /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private + * Filter out empty-ish values */ -function localstorage() { - try { - return window.localStorage; - } catch (e) {} +function filterEmpty(ele) { + return !!ele && ele !== '\\'; } - -/***/ }), -/* 453 */ -/***/ (function(module, exports, __webpack_require__) { - /** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. + * Handle patterns with whitespace */ -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __webpack_require__(452); -} else { - module.exports = __webpack_require__(454); -} - +function splitWhitespace(str) { + var segs = str.split(' '); + var len = segs.length; + var res = []; + var i = 0; -/***/ }), -/* 454 */ -/***/ (function(module, exports, __webpack_require__) { + while (len--) { + res.push.apply(res, braces(segs[i++])); + } + return res; +} /** - * Module dependencies. + * Handle escaped braces: `\\{foo,bar}` */ -var tty = __webpack_require__(116); -var util = __webpack_require__(2); +function escapeBraces(str, arr, opts) { + if (!/\{[^{]+\{/.test(str)) { + return arr.concat(str.split('\\').join('')); + } else { + str = str.split('\\{').join('__LT_BRACE__'); + str = str.split('\\}').join('__RT_BRACE__'); + return map(braces(str, arr, opts), function(ele) { + ele = ele.split('__LT_BRACE__').join('{'); + return ele.split('__RT_BRACE__').join('}'); + }); + } +} /** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. + * Handle escaped dots: `{1\\.2}` */ -exports = module.exports = __webpack_require__(227); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +function escapeDots(str, arr, opts) { + if (!/[^\\]\..+\\\./.test(str)) { + return arr.concat(str.split('\\').join('')); + } else { + str = str.split('\\.').join('__ESC_DOT__'); + return map(braces(str, arr, opts), function(ele) { + return ele.split('__ESC_DOT__').join('.'); + }); + } +} /** - * Colors. + * Handle escaped dots: `{1\\.2}` */ -exports.colors = [6, 2, 3, 4, 5, 1]; +function escapePaths(str, arr, opts) { + str = str.split('\/.').join('__ESC_PATH__'); + return map(braces(str, arr, opts), function(ele) { + return ele.split('__ESC_PATH__').join('\/.'); + }); +} /** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * Handle escaped commas: `{a\\,b}` */ -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); +function escapeCommas(str, arr, opts) { + if (!/\w,/.test(str)) { + return arr.concat(str.split('\\').join('')); + } else { + str = str.split('\\,').join('__ESC_COMMA__'); + return map(braces(str, arr, opts), function(ele) { + return ele.split('__ESC_COMMA__').join(','); + }); + } +} /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: - * - * $ DEBUG_FD=3 node script.js 3>debug.log + * Regex for common patterns */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +function patternRegex() { + return /\${|( (?=[{,}])|(?=[{,}]) )|{}|{,}|\\,(?=.*[{}])|\/\.(?=.*[{}])|\\\.(?={)|\\{|\\}/; } -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Braces regex. */ -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); +function braceRegex() { + return /.*(\\?\{([^}]+)\})/; } /** - * Map %o to `util.inspect()`, all on a single line. + * es6 delimiter regex. */ -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .replace(/\s*\n\s*/g, ' '); -}; +function es6Regex() { + return /\$\{([^}]+)\}/; +} + +var braceRe; +var patternRe; /** - * Map %o to `util.inspect()`, allowing multiple lines if needed. + * Faster alternative to `String.replace()` when the + * index of the token to be replaces can't be supplied */ -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +function splice(str, token, replacement) { + var i = str.indexOf(token); + return str.substr(0, i) + replacement + + str.substr(i + token.length); +} /** - * Adds ANSI color escape codes if enabled. - * - * @api public + * Fast array map */ -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; +function map(arr, fn) { + if (arr == null) { + return []; + } - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + var len = arr.length; + var res = new Array(len); + var i = -1; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; + while (++i < len) { + res[i] = fn(arr[i], i, arr); } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); + return res; } /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Fast array filter */ -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; +function filter(arr, cb) { + if (arr == null) return []; + if (typeof cb !== 'function') { + throw new TypeError('braces: filter expects a callback function.'); } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ + var len = arr.length; + var res = arr.slice(); + var i = 0; -function load() { - return process.env.DEBUG; + while (len--) { + if (!cb(arr[len], i++)) { + res.splice(len, 1); + } + } + return res; } -/** - * Copied from `node/src/node.js`. - * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. - */ - -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; +/***/ }), +/* 452 */ +/***/ (function(module, exports, __webpack_require__) { - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; +"use strict"; - case 'FILE': - var fs = __webpack_require__(6); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - case 'PIPE': - case 'TCP': - var net = __webpack_require__(77); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); +var blacklist = [ + 'freelist', + 'sys' +]; - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; +module.exports = Object.keys(process.binding('natives')).filter(function (el) { + return !/^_|^internal|\//.test(el) && blacklist.indexOf(el) === -1; +}).sort(); - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } +/***/ }), +/* 453 */ +/***/ (function(module, exports, __webpack_require__) { - // For supporting legacy API we put the FD here. - stream.fd = fd; +"use strict"; +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ - stream._isStdio = true; - return stream; -} /** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Module exports. + * @public */ -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Module variables. + * @private */ -exports.enable(load()); +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; -/***/ }), -/* 455 */ -/***/ (function(module, exports, __webpack_require__) { +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: ((1 << 30) * 1024) +}; -var Stream = __webpack_require__(20).Stream; -var util = __webpack_require__(2); +// TODO: use is-finite module? +var numberIsFinite = Number.isFinite || function (v) { return typeof v === 'number' && isFinite(v); }; -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb)$/i; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ -DelayedStream.create = function(source, options) { - var delayedStream = new this(); +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); + } - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; + if (typeof value === 'number') { + return format(value, options); } - delayedStream.source = source; + return null; +} - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); +function format(value, options) { + if (!numberIsFinite(value)) { + return null; } - return delayedStream; -}; + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'kB'; + } else { + unit = 'B'; + } } -}); -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); } - this.source.resume(); -}; - -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; - -DelayedStream.prototype.release = function() { - this._released = true; + if (thousandsSeparator) { + str = str.replace(formatThousandsRegExp, thousandsSeparator); + } - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; + return str + unitSeparator + unit; +} -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; } - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); + if (typeof val !== 'string') { + return null; } - this._bufferedEvents.push(args); -}; - -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; - if (this.dataSize <= this.maxDataSize) { - return; + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); } - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + return Math.floor(map[unit] * floatValue); +} /***/ }), -/* 456 */ +/* 454 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +var argv = process.argv; -// detect either spaces or tabs but not both to properly handle tabs -// for indentation and spaces for alignment -const INDENT_RE = /^(?:( )+|\t+)/; - -function getMostUsed(indents) { - let result = 0; - let maxUsed = 0; - let maxWeight = 0; - - for (const entry of indents) { - // TODO: use destructuring when targeting Node.js 6 - const key = entry[0]; - const val = entry[1]; - - const u = val[0]; - const w = val[1]; +var terminator = argv.indexOf('--'); +var hasFlag = function (flag) { + flag = '--' + flag; + var pos = argv.indexOf(flag); + return pos !== -1 && (terminator !== -1 ? pos < terminator : true); +}; - if (u > maxUsed || (u === maxUsed && w > maxWeight)) { - maxUsed = u; - maxWeight = w; - result = Number(key); - } +module.exports = (function () { + if ('FORCE_COLOR' in process.env) { + return true; } - return result; -} - -module.exports = str => { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); + if (hasFlag('no-color') || + hasFlag('no-colors') || + hasFlag('color=false')) { + return false; } - // used to see if tabs or spaces are the most used - let tabs = 0; - let spaces = 0; - - // remember the size of previous line's indentation - let prev = 0; - - // remember how many indents/unindents as occurred for a given size - // and how much lines follow a given indentation - // - // indents = { - // 3: [1, 0], - // 4: [1, 5], - // 5: [1, 0], - // 12: [1, 0], - // } - const indents = new Map(); + if (hasFlag('color') || + hasFlag('colors') || + hasFlag('color=true') || + hasFlag('color=always')) { + return true; + } - // pointer to the array of last used indent - let current; + if (process.stdout && !process.stdout.isTTY) { + return false; + } - // whether the last action was an indent (opposed to an unindent) - let isIndent; + if (process.platform === 'win32') { + return true; + } - for (const line of str.split(/\n/g)) { - if (!line) { - // ignore empty lines - continue; - } + if ('COLORTERM' in process.env) { + return true; + } - let indent; - const matches = line.match(INDENT_RE); + if (process.env.TERM === 'dumb') { + return false; + } - if (matches) { - indent = matches[0].length; + if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { + return true; + } - if (matches[1]) { - spaces++; - } else { - tabs++; - } - } else { - indent = 0; - } + return false; +})(); - const diff = indent - prev; - prev = indent; - if (diff) { - // an indent or unindent has been detected +/***/ }), +/* 455 */ +/***/ (function(module, exports, __webpack_require__) { - isIndent = diff > 0; +module.exports = chownr +chownr.sync = chownrSync - current = indents.get(isIndent ? diff : -diff); +var fs = __webpack_require__(5) +, path = __webpack_require__(0) - if (current) { - current[0]++; - } else { - current = [1, 0]; - indents.set(diff, current); - } - } else if (current) { - // if the last action was an indent, increment the weight - current[1] += Number(isIndent); - } - } +function chownr (p, uid, gid, cb) { + fs.readdir(p, function (er, children) { + // any error other than ENOTDIR means it's not readable, or + // doesn't exist. give up. + if (er && er.code !== "ENOTDIR") return cb(er) + if (er || !children.length) return fs.chown(p, uid, gid, cb) - const amount = getMostUsed(indents); + var len = children.length + , errState = null + children.forEach(function (child) { + var pathChild = path.resolve(p, child); + fs.lstat(pathChild, function(er, stats) { + if (er) + return cb(er) + if (!stats.isSymbolicLink()) + chownr(pathChild, uid, gid, then) + else + then() + }) + }) + function then (er) { + if (errState) return + if (er) return cb(errState = er) + if (-- len === 0) return fs.chown(p, uid, gid, cb) + } + }) +} - let type; - let indent; - if (!amount) { - type = null; - indent = ''; - } else if (spaces >= tabs) { - type = 'space'; - indent = ' '.repeat(amount); - } else { - type = 'tab'; - indent = '\t'.repeat(amount); - } +function chownrSync (p, uid, gid) { + var children + try { + children = fs.readdirSync(p) + } catch (er) { + if (er && er.code === "ENOTDIR") return fs.chownSync(p, uid, gid) + throw er + } + if (!children.length) return fs.chownSync(p, uid, gid) - return { - amount, - type, - indent - }; -}; + children.forEach(function (child) { + var pathChild = path.resolve(p, child) + var stats = fs.lstatSync(pathChild) + if (!stats.isSymbolicLink()) + chownrSync(pathChild, uid, gid) + }) + return fs.chownSync(p, uid, gid) +} /***/ }), -/* 457 */ +/* 456 */ /***/ (function(module, exports, __webpack_require__) { -var once = __webpack_require__(458); +"use strict"; -var noop = function() {}; -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; +var env = process.env -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; +var vendors = [ + // Constant, Name, Envs + ['TRAVIS', 'Travis CI', 'TRAVIS'], + ['CIRCLE', 'CircleCI', 'CIRCLECI'], + ['GITLAB', 'GitLab CI', 'GITLAB_CI'], + ['APPVEYOR', 'AppVeyor', 'APPVEYOR'], + ['CODESHIP', 'Codeship', {CI_NAME: 'codeship'}], + ['DRONE', 'Drone', 'DRONE'], + ['MAGNUM', 'Magnum CI', 'MAGNUM'], + ['SEMAPHORE', 'Semaphore', 'SEMAPHORE'], + ['JENKINS', 'Jenkins', 'JENKINS_URL'], + ['BAMBOO', 'Bamboo', 'bamboo_planKey'], + ['TFS', 'Team Foundation Server', 'TF_BUILD'], + ['TEAMCITY', 'TeamCity', 'TEAMCITY_VERSION'], + ['BUILDKITE', 'Buildkite', 'BUILDKITE'], + ['HUDSON', 'Hudsun', 'HUDSON_URL'], + ['TASKCLUSTER', 'TaskCluster', 'TASK_ID', 'RUN_ID'], + ['GOCD', 'GoCD', 'GO_PIPELINE_LABEL'], + ['BITBUCKET', 'Bitbucket Pipelines', 'BITBUCKET_COMMIT'] +] - callback = once(callback || noop); +exports.name = null - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); +vendors.forEach(function (vendor) { + var constant = vendor.shift() + var name = vendor.shift() + var isCI = vendor.every(function (obj) { + if (typeof obj === 'string') return !!env[obj] + return Object.keys(obj).every(function (k) { + return env[k] === obj[k] + }) + }) + exports[constant] = isCI + if (isCI) exports.name = name +}) - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; +exports.isCI = !!( + env.CI || // Travis CI, CircleCI, Gitlab CI, Appveyor, CodeShip + env.CONTINUOUS_INTEGRATION || // Travis CI + env.BUILD_NUMBER || // Jenkins, TeamCity + exports.name || + false +) - var onfinish = function() { - writable = false; - if (!readable) callback(); - }; - var onend = function() { - readable = false; - if (!writable) callback(); - }; +/***/ }), +/* 457 */ +/***/ (function(module, exports, __webpack_require__) { - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback(new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback(new Error('premature close')); - }; +"use strict"; - var onrequest = function() { - stream.req.on('finish', onfinish); - }; - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } +exports = module.exports = cliWidth; - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', callback); - stream.on('close', onclose); +function normalizeOpts(options) { + var defaultOpts = { + defaultWidth: 0, + output: process.stdout, + tty: __webpack_require__(90) + }; + if (!options) { + return defaultOpts; + } else { + Object.keys(defaultOpts).forEach(function (key) { + if (!options[key]) { + options[key] = defaultOpts[key]; + } + }); + return options; + } +} + +function cliWidth(options) { + var opts = normalizeOpts(options); + if (opts.output.getWindowSize) { + return opts.output.getWindowSize()[0] || opts.defaultWidth; + } + else { + if (opts.tty.getWindowSize) { + return opts.tty.getWindowSize()[1] || opts.defaultWidth; + } + else { + if (opts.output.columns) { + return opts.output.columns; + } + else { + if (process.env.CLI_WIDTH) { + var width = parseInt(process.env.CLI_WIDTH, 10); + + if (!isNaN(width)) { + return width; + } + } + } - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', callback); - stream.removeListener('close', onclose); - }; + return opts.defaultWidth; + } + } }; -module.exports = eos; /***/ }), /* 458 */ /***/ (function(module, exports, __webpack_require__) { -var wrappy = __webpack_require__(167) -module.exports = wrappy(once) +// On windows, create a .cmd file. +// Read the #! in the file to see what it uses. The vast majority +// of the time, this will be either: +// "#!/usr/bin/env <prog> <args...>" +// or: +// "#!<prog> <args...>" +// +// Write a binroot/pkg.bin + ".cmd" file that has this line in it: +// @<prog> <args...> %~dp0<target> %* -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) -}) +module.exports = cmdShim +cmdShim.ifExists = cmdShimIfExists -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} +var fs = __webpack_require__(289) +var mkdir = __webpack_require__(114) + , path = __webpack_require__(0) + , shebangExpr = /^#\!\s*(?:\/usr\/bin\/env)?\s*([^ \t]+)(.*)$/ -/***/ }), -/* 459 */ -/***/ (function(module, exports, __webpack_require__) { +function cmdShimIfExists (from, to, cb) { + fs.stat(from, function (er) { + if (er) return cb() + cmdShim(from, to, cb) + }) +} -// Named EC curves +// Try to unlink, but ignore errors. +// Any problems will surface later. +function rm (path, cb) { + fs.unlink(path, function(er) { + cb() + }) +} -// Requires ec.js, jsbn.js, and jsbn2.js -var BigInteger = __webpack_require__(40).BigInteger -var ECCurveFp = __webpack_require__(93).ECCurveFp +function cmdShim (from, to, cb) { + fs.stat(from, function (er, stat) { + if (er) + return cb(er) + cmdShim_(from, to, cb) + }) +} -// ---------------- -// X9ECParameters +function cmdShim_ (from, to, cb) { + var then = times(2, next, cb) + rm(to, then) + rm(to + ".cmd", then) -// constructor -function X9ECParameters(curve,g,n,h) { - this.curve = curve; - this.g = g; - this.n = n; - this.h = h; + function next(er) { + writeShim(from, to, cb) + } } -function x9getCurve() { - return this.curve; +function writeShim (from, to, cb) { + // make a cmd file and a sh script + // First, check if the bin is a #! of some sort. + // If not, then assume it's something that'll be compiled, or some other + // sort of script, and just call it directly. + mkdir(path.dirname(to), function (er) { + if (er) + return cb(er) + fs.readFile(from, "utf8", function (er, data) { + if (er) return writeShim_(from, to, null, null, cb) + var firstLine = data.trim().split(/\r*\n/)[0] + , shebang = firstLine.match(shebangExpr) + if (!shebang) return writeShim_(from, to, null, null, cb) + var prog = shebang[1] + , args = shebang[2] || "" + return writeShim_(from, to, prog, args, cb) + }) + }) } -function x9getG() { - return this.g; -} +function writeShim_ (from, to, prog, args, cb) { + var shTarget = path.relative(path.dirname(to), from) + , target = shTarget.split("/").join("\\") + , longProg + , shProg = prog && prog.split("\\").join("/") + , shLongProg + shTarget = shTarget.split("\\").join("/") + args = args || "" + if (!prog) { + prog = "\"%~dp0\\" + target + "\"" + shProg = "\"$basedir/" + shTarget + "\"" + args = "" + target = "" + shTarget = "" + } else { + longProg = "\"%~dp0\\" + prog + ".exe\"" + shLongProg = "\"$basedir/" + prog + "\"" + target = "\"%~dp0\\" + target + "\"" + shTarget = "\"$basedir/" + shTarget + "\"" + } -function x9getN() { - return this.n; -} + // @IF EXIST "%~dp0\node.exe" ( + // "%~dp0\node.exe" "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) ELSE ( + // SETLOCAL + // SET PATHEXT=%PATHEXT:;.JS;=;% + // node "%~dp0\.\node_modules\npm\bin\npm-cli.js" %* + // ) + var cmd + if (longProg) { + cmd = "@IF EXIST " + longProg + " (\r\n" + + " " + longProg + " " + args + " " + target + " %*\r\n" + + ") ELSE (\r\n" + + " @SETLOCAL\r\n" + + " @SET PATHEXT=%PATHEXT:;.JS;=;%\r\n" + + " " + prog + " " + args + " " + target + " %*\r\n" + + ")" + } else { + cmd = "@" + prog + " " + args + " " + target + " %*\r\n" + } -function x9getH() { - return this.h; -} + // #!/bin/sh + // basedir=`dirname "$0"` + // + // case `uname` in + // *CYGWIN*) basedir=`cygpath -w "$basedir"`;; + // esac + // + // if [ -x "$basedir/node.exe" ]; then + // "$basedir/node.exe" "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // else + // node "$basedir/node_modules/npm/bin/npm-cli.js" "$@" + // ret=$? + // fi + // exit $ret -X9ECParameters.prototype.getCurve = x9getCurve; -X9ECParameters.prototype.getG = x9getG; -X9ECParameters.prototype.getN = x9getN; -X9ECParameters.prototype.getH = x9getH; + var sh = "#!/bin/sh\n" -// ---------------- -// SECNamedCurves + if (shLongProg) { + sh = sh + + "basedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\,/,g')\")\n" + + "\n" + + "case `uname` in\n" + + " *CYGWIN*) basedir=`cygpath -w \"$basedir\"`;;\n" + + "esac\n" + + "\n" -function fromHex(s) { return new BigInteger(s, 16); } + sh = sh + + "if [ -x "+shLongProg+" ]; then\n" + + " " + shLongProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "else \n" + + " " + shProg + " " + args + " " + shTarget + " \"$@\"\n" + + " ret=$?\n" + + "fi\n" + + "exit $ret\n" + } else { + sh = shProg + " " + args + " " + shTarget + " \"$@\"\n" + + "exit $?\n" + } -function secp128r1() { - // p = 2^128 - 2^97 - 1 - var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); - //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); - var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "161FF7528B899B2D0C28607CA52C5B86" - + "CF5AC8395BAFEB13C02DA292DDED7A83"); - return new X9ECParameters(curve, G, n, h); + var then = times(2, next, cb) + fs.writeFile(to + ".cmd", cmd, "utf8", then) + fs.writeFile(to, sh, "utf8", then) + function next () { + chmodShim(to, cb) + } } -function secp160k1() { - // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); - var a = BigInteger.ZERO; - var b = fromHex("7"); - //byte[] S = null; - var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" - + "938CF935318FDCED6BC28286531733C3F03C4FEE"); - return new X9ECParameters(curve, G, n, h); +function chmodShim (to, cb) { + var then = times(2, cb, cb) + fs.chmod(to, 0755, then) + fs.chmod(to + ".cmd", 0755, then) } -function secp160r1() { - // p = 2^160 - 2^31 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); - var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); - //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); - var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "4A96B5688EF573284664698968C38BB913CBFC82" - + "23A628553168947D59DCC912042351377AC5FB32"); - return new X9ECParameters(curve, G, n, h); +function times(n, ok, cb) { + var errState = null + return function(er) { + if (!errState) { + if (er) + cb(errState = er) + else if (--n === 0) + ok() + } + } } -function secp192k1() { - // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); - var a = BigInteger.ZERO; - var b = fromHex("3"); - //byte[] S = null; - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" - + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); - return new X9ECParameters(curve, G, n, h); -} -function secp192r1() { - // p = 2^192 - 2^64 - 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); - var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); - //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" - + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); - return new X9ECParameters(curve, G, n, h); -} +/***/ }), +/* 459 */ +/***/ (function(module, exports, __webpack_require__) { -function secp224r1() { - // p = 2^224 - 2^96 + 1 - var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); - var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); - var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); - //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); - var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" - + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); - return new X9ECParameters(curve, G, n, h); -} +__webpack_require__(85); +__webpack_require__(469); +module.exports = __webpack_require__(21).Array.from; -function secp256r1() { - // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 - var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); - var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); - var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); - //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); - var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); - var h = BigInteger.ONE; - var curve = new ECCurveFp(p, a, b); - var G = curve.decodePointHex("04" - + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" - + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); - return new X9ECParameters(curve, G, n, h); -} +/***/ }), +/* 460 */ +/***/ (function(module, exports, __webpack_require__) { -// TODO: make this into a proper hashtable -function getSECCurveByName(name) { - if(name == "secp128r1") return secp128r1(); - if(name == "secp160k1") return secp160k1(); - if(name == "secp160r1") return secp160r1(); - if(name == "secp192k1") return secp192k1(); - if(name == "secp192r1") return secp192r1(); - if(name == "secp224r1") return secp224r1(); - if(name == "secp256r1") return secp256r1(); - return null; -} +__webpack_require__(109); +__webpack_require__(85); +module.exports = __webpack_require__(467); -module.exports = { - "secp128r1":secp128r1, - "secp160k1":secp160k1, - "secp160r1":secp160r1, - "secp192k1":secp192k1, - "secp192r1":secp192r1, - "secp224r1":secp224r1, - "secp256r1":secp256r1 -} +/***/ }), +/* 461 */ +/***/ (function(module, exports, __webpack_require__) { +__webpack_require__(109); +__webpack_require__(85); +module.exports = __webpack_require__(468); /***/ }), -/* 460 */ +/* 462 */ +/***/ (function(module, exports, __webpack_require__) { + +__webpack_require__(470); +module.exports = __webpack_require__(21).Object.assign; + +/***/ }), +/* 463 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * expand-brackets <https://github.com/jonschlinkert/expand-brackets> - * - * Copyright (c) 2015 Jon Schlinkert. - * Licensed under the MIT license. - */ +var $defineProperty = __webpack_require__(38) + , createDesc = __webpack_require__(83); +module.exports = function(object, index, value){ + if(index in object)$defineProperty.f(object, index, createDesc(0, value)); + else object[index] = value; +}; -var isPosixBracket = __webpack_require__(540); +/***/ }), +/* 464 */ +/***/ (function(module, exports, __webpack_require__) { -/** - * POSIX character classes - */ +"use strict"; -var POSIX = { - alnum: 'a-zA-Z0-9', - alpha: 'a-zA-Z', - blank: ' \\t', - cntrl: '\\x00-\\x1F\\x7F', - digit: '0-9', - graph: '\\x21-\\x7E', - lower: 'a-z', - print: '\\x20-\\x7E', - punct: '-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', - space: ' \\t\\r\\n\\v\\f', - upper: 'A-Z', - word: 'A-Za-z0-9_', - xdigit: 'A-Fa-f0-9', -}; +// 19.1.2.1 Object.assign(target, source, ...) +var getKeys = __webpack_require__(129) + , gOPS = __webpack_require__(465) + , pIE = __webpack_require__(466) + , toObject = __webpack_require__(106) + , IObject = __webpack_require__(125) + , $assign = Object.assign; -/** - * Expose `brackets` - */ +// should work with symbols and should have deterministic property order (V8 bug) +module.exports = !$assign || __webpack_require__(82)(function(){ + var A = {} + , B = {} + , S = Symbol() + , K = 'abcdefghijklmnopqrst'; + A[S] = 7; + K.split('').forEach(function(k){ B[k] = k; }); + return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; +}) ? function assign(target, source){ // eslint-disable-line no-unused-vars + var T = toObject(target) + , aLen = arguments.length + , index = 1 + , getSymbols = gOPS.f + , isEnum = pIE.f; + while(aLen > index){ + var S = IObject(arguments[index++]) + , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) + , length = keys.length + , j = 0 + , key; + while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; + } return T; +} : $assign; -module.exports = brackets; +/***/ }), +/* 465 */ +/***/ (function(module, exports) { -function brackets(str) { - if (!isPosixBracket(str)) { - return str; - } +exports.f = Object.getOwnPropertySymbols; - var negated = false; - if (str.indexOf('[^') !== -1) { - negated = true; - str = str.split('[^').join('['); - } - if (str.indexOf('[!') !== -1) { - negated = true; - str = str.split('[!').join('['); - } +/***/ }), +/* 466 */ +/***/ (function(module, exports) { - var a = str.split('['); - var b = str.split(']'); - var imbalanced = a.length !== b.length; +exports.f = {}.propertyIsEnumerable; - var parts = str.split(/(?::\]\[:|\[?\[:|:\]\]?)/); - var len = parts.length, i = 0; - var end = '', beg = ''; - var res = []; +/***/ }), +/* 467 */ +/***/ (function(module, exports, __webpack_require__) { - // start at the end (innermost) first - while (len--) { - var inner = parts[i++]; - if (inner === '^[!' || inner === '[!') { - inner = ''; - negated = true; - } +var anObject = __webpack_require__(27) + , get = __webpack_require__(108); +module.exports = __webpack_require__(21).getIterator = function(it){ + var iterFn = get(it); + if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); + return anObject(iterFn.call(it)); +}; - var prefix = negated ? '^' : ''; - var ch = POSIX[inner]; +/***/ }), +/* 468 */ +/***/ (function(module, exports, __webpack_require__) { - if (ch) { - res.push('[' + prefix + ch + ']'); - } else if (inner) { - if (/^\[?\w-\w\]?$/.test(inner)) { - if (i === parts.length) { - res.push('[' + prefix + inner); - } else if (i === 1) { - res.push(prefix + inner + ']'); - } else { - res.push(prefix + inner); - } - } else { - if (i === 1) { - beg += inner; - } else if (i === parts.length) { - end += inner; - } else { - res.push('[' + prefix + inner + ']'); - } - } - } - } +var classof = __webpack_require__(81) + , ITERATOR = __webpack_require__(9)('iterator') + , Iterators = __webpack_require__(32); +module.exports = __webpack_require__(21).isIterable = function(it){ + var O = Object(it); + return O[ITERATOR] !== undefined + || '@@iterator' in O + || Iterators.hasOwnProperty(classof(O)); +}; - var result = res.join('|'); - var rlen = res.length || 1; - if (rlen > 1) { - result = '(?:' + result + ')'; - rlen = 1; - } - if (beg) { - rlen++; - if (beg.charAt(0) === '[') { - if (imbalanced) { - beg = '\\[' + beg.slice(1); - } else { - beg += ']'; +/***/ }), +/* 469 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var ctx = __webpack_require__(37) + , $export = __webpack_require__(66) + , toObject = __webpack_require__(106) + , call = __webpack_require__(127) + , isArrayIter = __webpack_require__(126) + , toLength = __webpack_require__(84) + , createProperty = __webpack_require__(463) + , getIterFn = __webpack_require__(108); + +$export($export.S + $export.F * !__webpack_require__(128)(function(iter){ Array.from(iter); }), 'Array', { + // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) + from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ + var O = toObject(arrayLike) + , C = typeof this == 'function' ? this : Array + , aLen = arguments.length + , mapfn = aLen > 1 ? arguments[1] : undefined + , mapping = mapfn !== undefined + , index = 0 + , iterFn = getIterFn(O) + , length, result, step, iterator; + if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); + // if object isn't iterable or it's array with default iterator - use simple case + if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ + for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ + createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } - } - result = beg + result; - } - if (end) { - rlen++; - if (end.slice(-1) === ']') { - if (imbalanced) { - end = end.slice(0, end.length - 1) + '\\]'; - } else { - end = '[' + end; + } else { + length = toLength(O.length); + for(result = new C(length); length > index; index++){ + createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } - result += end; + result.length = index; + return result; } +}); - if (rlen > 1) { - result = result.split('][').join(']|['); - if (result.indexOf('|') !== -1 && !/\(\?/.test(result)) { - result = '(?:' + result + ')'; - } - } - result = result.replace(/\[+=|=\]+/g, '\\b'); - return result; -} +/***/ }), +/* 470 */ +/***/ (function(module, exports, __webpack_require__) { -brackets.makeRe = function(pattern) { - try { - return new RegExp(brackets(pattern)); - } catch (err) {} -}; +// 19.1.3.1 Object.assign(target, source) +var $export = __webpack_require__(66); -brackets.isMatch = function(str, pattern) { - try { - return brackets.makeRe(pattern).test(str); - } catch (err) { - return false; - } -}; +$export($export.S + $export.F, 'Object', {assign: __webpack_require__(464)}); -brackets.match = function(arr, pattern) { - var len = arr.length, i = 0; - var res = arr.slice(); +/***/ }), +/* 471 */ +/***/ (function(module, exports, __webpack_require__) { - var re = brackets.makeRe(pattern); - while (i < len) { - var ele = arr[i++]; - if (!re.test(ele)) { - continue; - } - res.splice(i, 1); - } - return res; +"use strict"; + +var arrayFindIndex = __webpack_require__(374); + +module.exports = function () { + var unhandledRejections = []; + + function onUnhandledRejection(reason, promise) { + unhandledRejections.push({reason: reason, promise: promise}); + } + + function onRejectionHandled(promise) { + var index = arrayFindIndex(unhandledRejections, function (x) { + return x.promise === promise; + }); + + unhandledRejections.splice(index, 1); + } + + function currentlyUnhandled() { + return unhandledRejections.map(function (entry) { + return { + reason: entry.reason, + promise: entry.promise + }; + }); + } + + return { + onUnhandledRejection: onUnhandledRejection, + onRejectionHandled: onRejectionHandled, + currentlyUnhandled: currentlyUnhandled + }; }; /***/ }), -/* 461 */ +/* 472 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/*! - * expand-range <https://github.com/jonschlinkert/expand-range> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT license. - */ +var core = __webpack_require__(471); +module.exports = function (p) { + p = p || process; + var c = core(); -var fill = __webpack_require__(469); + p.on('unhandledRejection', c.onUnhandledRejection); + p.on('rejectionHandled', c.onRejectionHandled); -module.exports = function expandRange(str, options, fn) { - if (typeof str !== 'string') { - throw new TypeError('expand-range expects a string.'); - } + return c.currentlyUnhandled; +}; - if (typeof options === 'function') { - fn = options; - options = {}; - } - if (typeof options === 'boolean') { - options = {}; - options.makeRe = true; +/***/ }), +/* 473 */ +/***/ (function(module, exports, __webpack_require__) { + +var Stream = __webpack_require__(26).Stream; +var util = __webpack_require__(2); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - // create arguments to pass to fill-range - var opts = options || {}; - var args = str.split('..'); - var len = args.length; - if (len > 3) { return str; } + delayedStream.source = source; - // if only one argument, it can't expand so return it - if (len === 1) { return args; } + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; - // if `true`, tell fill-range to regexify the string - if (typeof fn === 'boolean' && fn === true) { - opts.makeRe = true; + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); } - args.push(opts); - return fill.apply(null, args.concat(fn)); + return delayedStream; }; +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); -/***/ }), -/* 462 */ -/***/ (function(module, exports) { +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; -// Generated by CoffeeScript 1.12.0 +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } -/* - ExternalEditor - Kevin Gravier <kevin@mrkmg.com> - MIT - */ + this.source.resume(); +}; -(function() { - var CreateFileError, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; - CreateFileError = (function(superClass) { - extend(CreateFileError, superClass); +DelayedStream.prototype.release = function() { + this._released = true; - CreateFileError.prototype.message = 'Failed to create temporary file for editor'; + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; - function CreateFileError(original_error) { - this.original_error = original_error; - } +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; - return CreateFileError; +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } - })(Error); + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } - module.exports = CreateFileError; + this._bufferedEvents.push(args); +}; -}).call(this); +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; + } + + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; /***/ }), -/* 463 */ -/***/ (function(module, exports) { +/* 474 */ +/***/ (function(module, exports, __webpack_require__) { -// Generated by CoffeeScript 1.12.0 +"use strict"; -/* - ExternalEditor - Kevin Gravier <kevin@mrkmg.com> - MIT - */ -(function() { - var LaunchEditorError, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; +// detect either spaces or tabs but not both to properly handle tabs +// for indentation and spaces for alignment +const INDENT_RE = /^(?:( )+|\t+)/; - LaunchEditorError = (function(superClass) { - extend(LaunchEditorError, superClass); +function getMostUsed(indents) { + let result = 0; + let maxUsed = 0; + let maxWeight = 0; - LaunchEditorError.prototype.message = 'Failed launch editor'; + for (const entry of indents) { + // TODO: use destructuring when targeting Node.js 6 + const key = entry[0]; + const val = entry[1]; - function LaunchEditorError(original_error) { - this.original_error = original_error; - } + const u = val[0]; + const w = val[1]; - return LaunchEditorError; + if (u > maxUsed || (u === maxUsed && w > maxWeight)) { + maxUsed = u; + maxWeight = w; + result = Number(key); + } + } - })(Error); + return result; +} - module.exports = LaunchEditorError; +module.exports = str => { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } -}).call(this); + // used to see if tabs or spaces are the most used + let tabs = 0; + let spaces = 0; + // remember the size of previous line's indentation + let prev = 0; -/***/ }), -/* 464 */ -/***/ (function(module, exports) { + // remember how many indents/unindents as occurred for a given size + // and how much lines follow a given indentation + // + // indents = { + // 3: [1, 0], + // 4: [1, 5], + // 5: [1, 0], + // 12: [1, 0], + // } + const indents = new Map(); -// Generated by CoffeeScript 1.12.0 + // pointer to the array of last used indent + let current; -/* - ExternalEditor - Kevin Gravier <kevin@mrkmg.com> - MIT - */ + // whether the last action was an indent (opposed to an unindent) + let isIndent; -(function() { - var ReadFileError, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; + for (const line of str.split(/\n/g)) { + if (!line) { + // ignore empty lines + continue; + } - ReadFileError = (function(superClass) { - extend(ReadFileError, superClass); + let indent; + const matches = line.match(INDENT_RE); - ReadFileError.prototype.message = 'Failed to read temporary file'; + if (matches) { + indent = matches[0].length; - function ReadFileError(original_error) { - this.original_error = original_error; - } + if (matches[1]) { + spaces++; + } else { + tabs++; + } + } else { + indent = 0; + } - return ReadFileError; + const diff = indent - prev; + prev = indent; - })(Error); + if (diff) { + // an indent or unindent has been detected - module.exports = ReadFileError; + isIndent = diff > 0; -}).call(this); + current = indents.get(isIndent ? diff : -diff); + if (current) { + current[0]++; + } else { + current = [1, 0]; + indents.set(diff, current); + } + } else if (current) { + // if the last action was an indent, increment the weight + current[1] += Number(isIndent); + } + } -/***/ }), -/* 465 */ -/***/ (function(module, exports) { + const amount = getMostUsed(indents); -// Generated by CoffeeScript 1.12.0 + let type; + let indent; + if (!amount) { + type = null; + indent = ''; + } else if (spaces >= tabs) { + type = 'space'; + indent = ' '.repeat(amount); + } else { + type = 'tab'; + indent = '\t'.repeat(amount); + } -/* - ExternalEditor - Kevin Gravier <kevin@mrkmg.com> - MIT - */ + return { + amount, + type, + indent + }; +}; -(function() { - var RemoveFileError, - extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, - hasProp = {}.hasOwnProperty; - RemoveFileError = (function(superClass) { - extend(RemoveFileError, superClass); +/***/ }), +/* 475 */ +/***/ (function(module, exports, __webpack_require__) { - RemoveFileError.prototype.message = 'Failed to cleanup temporary file'; +var once = __webpack_require__(476); - function RemoveFileError(original_error) { - this.original_error = original_error; - } +var noop = function() {}; - return RemoveFileError; +var isRequest = function(stream) { + return stream.setHeader && typeof stream.abort === 'function'; +}; - })(Error); +var eos = function(stream, opts, callback) { + if (typeof opts === 'function') return eos(stream, null, opts); + if (!opts) opts = {}; - module.exports = RemoveFileError; + callback = once(callback || noop); -}).call(this); + var ws = stream._writableState; + var rs = stream._readableState; + var readable = opts.readable || (opts.readable !== false && stream.readable); + var writable = opts.writable || (opts.writable !== false && stream.writable); + var onlegacyfinish = function() { + if (!stream.writable) onfinish(); + }; -/***/ }), -/* 466 */ -/***/ (function(module, exports, __webpack_require__) { + var onfinish = function() { + writable = false; + if (!readable) callback(); + }; -// Generated by CoffeeScript 1.12.0 + var onend = function() { + readable = false; + if (!writable) callback(); + }; -/* - ExternalEditor - Kevin Gravier <kevin@mrkmg.com> - MIT - */ + var onclose = function() { + if (readable && !(rs && rs.ended)) return callback(new Error('premature close')); + if (writable && !(ws && ws.ended)) return callback(new Error('premature close')); + }; -(function() { - var CreateFileError, ExternalEditor, FS, LaunchEditorError, ReadFileError, RemoveFileError, Spawn, SpawnSync, Temp, - bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; + var onrequest = function() { + stream.req.on('finish', onfinish); + }; - FS = __webpack_require__(6); + if (isRequest(stream)) { + stream.on('complete', onfinish); + stream.on('abort', onclose); + if (stream.req) onrequest(); + else stream.on('request', onrequest); + } else if (writable && !ws) { // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } - Temp = __webpack_require__(626); + stream.on('end', onend); + stream.on('finish', onfinish); + if (opts.error !== false) stream.on('error', callback); + stream.on('close', onclose); - SpawnSync = __webpack_require__(111).spawnSync; + return function() { + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', callback); + stream.removeListener('close', onclose); + }; +}; - Spawn = __webpack_require__(111).spawn; +module.exports = eos; - CreateFileError = __webpack_require__(462); +/***/ }), +/* 476 */ +/***/ (function(module, exports, __webpack_require__) { - ReadFileError = __webpack_require__(464); +var wrappy = __webpack_require__(89) +module.exports = wrappy(once) - RemoveFileError = __webpack_require__(465); +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) +}) - LaunchEditorError = __webpack_require__(463); +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} - ExternalEditor = (function() { - ExternalEditor.edit = function(text) { - var editor; - if (text == null) { - text = ''; - } - editor = new ExternalEditor(text); - editor.run(); - editor.cleanup(); - return editor.text; - }; - ExternalEditor.editAsync = function(text, callback) { - var editor; - if (text == null) { - text = ''; - } - editor = new ExternalEditor(text); - return editor.runAsync(function(error_run, response) { - var error_cleanup; - if (!error_run) { - try { - editor.cleanup(); - } catch (error) { - error_cleanup = error; - if (typeof callback === 'function') { - callback(error_cleanup); - } - } - return callback(null, response); - } else { - return callback(error_run) in typeof callback === 'function'; - } - }); - }; +/***/ }), +/* 477 */ +/***/ (function(module, exports, __webpack_require__) { - ExternalEditor.CreateFileError = CreateFileError; +// Named EC curves - ExternalEditor.ReadFileError = ReadFileError; +// Requires ec.js, jsbn.js, and jsbn2.js +var BigInteger = __webpack_require__(56).BigInteger +var ECCurveFp = __webpack_require__(130).ECCurveFp - ExternalEditor.RemoveFileError = RemoveFileError; - ExternalEditor.LaunchEditorError = LaunchEditorError; +// ---------------- +// X9ECParameters - ExternalEditor.prototype.text = ''; +// constructor +function X9ECParameters(curve,g,n,h) { + this.curve = curve; + this.g = g; + this.n = n; + this.h = h; +} - ExternalEditor.prototype.temp_file = void 0; +function x9getCurve() { + return this.curve; +} - ExternalEditor.prototype.editor = { - bin: void 0, - args: [] - }; +function x9getG() { + return this.g; +} - function ExternalEditor(text1) { - this.text = text1 != null ? text1 : ''; - this.launchEditorAsync = bind(this.launchEditorAsync, this); - this.launchEditor = bind(this.launchEditor, this); - this.removeTemporaryFile = bind(this.removeTemporaryFile, this); - this.readTemporaryFile = bind(this.readTemporaryFile, this); - this.createTemporaryFile = bind(this.createTemporaryFile, this); - this.determineEditor = bind(this.determineEditor, this); - this.cleanup = bind(this.cleanup, this); - this.runAsync = bind(this.runAsync, this); - this.run = bind(this.run, this); - this.determineEditor(); - this.createTemporaryFile(); - } +function x9getN() { + return this.n; +} - ExternalEditor.prototype.run = function() { - this.launchEditor(); - return this.readTemporaryFile(); - }; +function x9getH() { + return this.h; +} - ExternalEditor.prototype.runAsync = function(callback) { - var error_launch; - try { - return this.launchEditorAsync((function(_this) { - return function() { - var error_read; - try { - _this.readTemporaryFile(); - if (typeof callback === 'function') { - return callback(null, _this.text); - } - } catch (error) { - error_read = error; - if (typeof callback === 'function') { - return callback(error_read); - } - } - }; - })(this)); - } catch (error) { - error_launch = error; - if (typeof callback === 'function') { - return callback(error_launch); - } - } - }; +X9ECParameters.prototype.getCurve = x9getCurve; +X9ECParameters.prototype.getG = x9getG; +X9ECParameters.prototype.getN = x9getN; +X9ECParameters.prototype.getH = x9getH; - ExternalEditor.prototype.cleanup = function() { - return this.removeTemporaryFile(); - }; +// ---------------- +// SECNamedCurves - ExternalEditor.prototype.determineEditor = function() { - var args, ed, editor; - ed = /^win/.test(process.platform) ? 'notepad' : 'vim'; - editor = process.env.VISUAL || process.env.EDITOR || ed; - args = editor.split(/\s+/); - this.bin = args.shift(); - return this.args = args; - }; +function fromHex(s) { return new BigInteger(s, 16); } - ExternalEditor.prototype.createTemporaryFile = function() { - var e; - try { - this.temp_file = Temp.tmpNameSync({}); - return FS.writeFileSync(this.temp_file, this.text); - } catch (error) { - e = error; - throw new CreateFileError(e); - } - }; +function secp128r1() { + // p = 2^128 - 2^97 - 1 + var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("E87579C11079F43DD824993C2CEE5ED3"); + //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679"); + var n = fromHex("FFFFFFFE0000000075A30D1B9038A115"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "161FF7528B899B2D0C28607CA52C5B86" + + "CF5AC8395BAFEB13C02DA292DDED7A83"); + return new X9ECParameters(curve, G, n, h); +} - ExternalEditor.prototype.readTemporaryFile = function() { - var e; - try { - return this.text = FS.readFileSync(this.temp_file).toString(); - } catch (error) { - e = error; - throw new ReadFileError(e); - } - }; +function secp160k1() { + // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); + var a = BigInteger.ZERO; + var b = fromHex("7"); + //byte[] S = null; + var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + + "938CF935318FDCED6BC28286531733C3F03C4FEE"); + return new X9ECParameters(curve, G, n, h); +} - ExternalEditor.prototype.removeTemporaryFile = function() { - var e; - try { - return FS.unlinkSync(this.temp_file); - } catch (error) { - e = error; - throw new RemoveFileError(e); - } - }; +function secp160r1() { + // p = 2^160 - 2^31 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); + var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); + //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345"); + var n = fromHex("0100000000000000000001F4C8F927AED3CA752257"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "4A96B5688EF573284664698968C38BB913CBFC82" + + "23A628553168947D59DCC912042351377AC5FB32"); + return new X9ECParameters(curve, G, n, h); +} - ExternalEditor.prototype.launchEditor = function() { - var e; - try { - return SpawnSync(this.bin, this.args.concat([this.temp_file]), { - stdio: 'inherit' - }); - } catch (error) { - e = error; - throw new LaunchEditorError(e); - } - }; +function secp192k1() { + // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); + var a = BigInteger.ZERO; + var b = fromHex("3"); + //byte[] S = null; + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D"); + return new X9ECParameters(curve, G, n, h); +} - ExternalEditor.prototype.launchEditorAsync = function(callback) { - var child_process, e; - try { - child_process = Spawn(this.bin, this.args.concat([this.temp_file]), { - stdio: 'inherit' - }); - return child_process.on('exit', function() { - if (typeof callback === 'function') { - return callback(); - } - }); - } catch (error) { - e = error; - throw new LaunchEditorError(e); - } - }; +function secp192r1() { + // p = 2^192 - 2^64 - 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); + var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); + //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811"); + return new X9ECParameters(curve, G, n, h); +} - return ExternalEditor; +function secp224r1() { + // p = 2^224 - 2^96 + 1 + var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); + var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); + var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); + //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); + var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34"); + return new X9ECParameters(curve, G, n, h); +} - })(); +function secp256r1() { + // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 + var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); + var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); + var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); + //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90"); + var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); + var h = BigInteger.ONE; + var curve = new ECCurveFp(p, a, b); + var G = curve.decodePointHex("04" + + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"); + return new X9ECParameters(curve, G, n, h); +} - module.exports = ExternalEditor; +// TODO: make this into a proper hashtable +function getSECCurveByName(name) { + if(name == "secp128r1") return secp128r1(); + if(name == "secp160k1") return secp160k1(); + if(name == "secp160r1") return secp160r1(); + if(name == "secp192k1") return secp192k1(); + if(name == "secp192r1") return secp192r1(); + if(name == "secp224r1") return secp224r1(); + if(name == "secp256r1") return secp256r1(); + return null; +} -}).call(this); +module.exports = { + "secp128r1":secp128r1, + "secp160k1":secp160k1, + "secp160r1":secp160r1, + "secp192k1":secp192k1, + "secp192r1":secp192r1, + "secp224r1":secp224r1, + "secp256r1":secp256r1 +} /***/ }), -/* 467 */ +/* 478 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * extglob <https://github.com/jonschlinkert/extglob> + * expand-brackets <https://github.com/jonschlinkert/expand-brackets> * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + * Copyright (c) 2015 Jon Schlinkert. + * Licensed under the MIT license. */ +var isPosixBracket = __webpack_require__(555); + /** - * Module dependencies + * POSIX character classes */ -var isExtglob = __webpack_require__(100); -var re, cache = {}; +var POSIX = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E', + punct: '-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9', +}; /** - * Expose `extglob` + * Expose `brackets` */ -module.exports = extglob; +module.exports = brackets; -/** - * Convert the given extglob `string` to a regex-compatible - * string. - * - * ```js - * var extglob = require('extglob'); - * extglob('!(a?(b))'); - * //=> '(?!a(?:b)?)[^/]*?' - * ``` - * - * @param {String} `str` The string to convert. - * @param {Object} `options` - * @option {Boolean} [options] `esc` If `false` special characters will not be escaped. Defaults to `true`. - * @option {Boolean} [options] `regex` If `true` a regular expression is returned instead of a string. - * @return {String} - * @api public - */ +function brackets(str) { + if (!isPosixBracket(str)) { + return str; + } + var negated = false; + if (str.indexOf('[^') !== -1) { + negated = true; + str = str.split('[^').join('['); + } + if (str.indexOf('[!') !== -1) { + negated = true; + str = str.split('[!').join('['); + } -function extglob(str, opts) { - opts = opts || {}; - var o = {}, i = 0; + var a = str.split('['); + var b = str.split(']'); + var imbalanced = a.length !== b.length; - // fix common character reversals - // '*!(.js)' => '*.!(js)' - str = str.replace(/!\(([^\w*()])/g, '$1!('); + var parts = str.split(/(?::\]\[:|\[?\[:|:\]\]?)/); + var len = parts.length, i = 0; + var end = '', beg = ''; + var res = []; - // support file extension negation - str = str.replace(/([*\/])\.!\([*]\)/g, function (m, ch) { - if (ch === '/') { - return escape('\\/[^.]+'); + // start at the end (innermost) first + while (len--) { + var inner = parts[i++]; + if (inner === '^[!' || inner === '[!') { + inner = ''; + negated = true; } - return escape('[^.]+'); - }); - // create a unique key for caching by - // combining the string and options - var key = str - + String(!!opts.regex) - + String(!!opts.contains) - + String(!!opts.escape); + var prefix = negated ? '^' : ''; + var ch = POSIX[inner]; - if (cache.hasOwnProperty(key)) { - return cache[key]; + if (ch) { + res.push('[' + prefix + ch + ']'); + } else if (inner) { + if (/^\[?\w-\w\]?$/.test(inner)) { + if (i === parts.length) { + res.push('[' + prefix + inner); + } else if (i === 1) { + res.push(prefix + inner + ']'); + } else { + res.push(prefix + inner); + } + } else { + if (i === 1) { + beg += inner; + } else if (i === parts.length) { + end += inner; + } else { + res.push('[' + prefix + inner + ']'); + } + } + } } - if (!(re instanceof RegExp)) { - re = regex(); + var result = res.join('|'); + var rlen = res.length || 1; + if (rlen > 1) { + result = '(?:' + result + ')'; + rlen = 1; } - - opts.negate = false; - var m; - - while (m = re.exec(str)) { - var prefix = m[1]; - var inner = m[3]; - if (prefix === '!') { - opts.negate = true; + if (beg) { + rlen++; + if (beg.charAt(0) === '[') { + if (imbalanced) { + beg = '\\[' + beg.slice(1); + } else { + beg += ']'; + } } - - var id = '__EXTGLOB_' + (i++) + '__'; - // use the prefix of the _last_ (outtermost) pattern - o[id] = wrap(inner, prefix, opts.escape); - str = str.split(m[0]).join(id); - } - - var keys = Object.keys(o); - var len = keys.length; - - // we have to loop again to allow us to convert - // patterns in reverse order (starting with the - // innermost/last pattern first) - while (len--) { - var prop = keys[len]; - str = str.split(prop).join(o[prop]); + result = beg + result; } - - var result = opts.regex - ? toRegex(str, opts.contains, opts.negate) - : str; - - result = result.split('.').join('\\.'); - - // cache the result and return it - return (cache[key] = result); -} - -/** - * Convert `string` to a regex string. - * - * @param {String} `str` - * @param {String} `prefix` Character that determines how to wrap the string. - * @param {Boolean} `esc` If `false` special characters will not be escaped. Defaults to `true`. - * @return {String} - */ - -function wrap(inner, prefix, esc) { - if (esc) inner = escape(inner); - - switch (prefix) { - case '!': - return '(?!' + inner + ')[^/]' + (esc ? '%%%~' : '*?'); - case '@': - return '(?:' + inner + ')'; - case '+': - return '(?:' + inner + ')+'; - case '*': - return '(?:' + inner + ')' + (esc ? '%%' : '*') - case '?': - return '(?:' + inner + '|)'; - default: - return inner; + if (end) { + rlen++; + if (end.slice(-1) === ']') { + if (imbalanced) { + end = end.slice(0, end.length - 1) + '\\]'; + } else { + end = '[' + end; + } + } + result += end; } -} - -function escape(str) { - str = str.split('*').join('[^/]%%%~'); - str = str.split('.').join('\\.'); - return str; -} - -/** - * extglob regex. - */ - -function regex() { - return /(\\?[@?!+*$]\\?)(\(([^()]*?)\))/; -} -/** - * Negation regex - */ + if (rlen > 1) { + result = result.split('][').join(']|['); + if (result.indexOf('|') !== -1 && !/\(\?/.test(result)) { + result = '(?:' + result + ')'; + } + } -function negate(str) { - return '(?!^' + str + ').*$'; + result = result.replace(/\[+=|=\]+/g, '\\b'); + return result; } -/** - * Create the regex to do the matching. If - * the leading character in the `pattern` is `!` - * a negation regex is returned. - * - * @param {String} `pattern` - * @param {Boolean} `contains` Allow loose matching. - * @param {Boolean} `isNegated` True if the pattern is a negation pattern. - */ +brackets.makeRe = function(pattern) { + try { + return new RegExp(brackets(pattern)); + } catch (err) {} +}; -function toRegex(pattern, contains, isNegated) { - var prefix = contains ? '^' : ''; - var after = contains ? '$' : ''; - pattern = ('(?:' + pattern + ')' + after); - if (isNegated) { - pattern = prefix + negate(pattern); +brackets.isMatch = function(str, pattern) { + try { + return brackets.makeRe(pattern).test(str); + } catch (err) { + return false; } - return new RegExp(prefix + pattern); -} - - -/***/ }), -/* 468 */ -/***/ (function(module, exports) { +}; -/*! - * filename-regex <https://github.com/regexps/filename-regex> - * - * Copyright (c) 2014-2015, Jon Schlinkert - * Licensed under the MIT license. - */ +brackets.match = function(arr, pattern) { + var len = arr.length, i = 0; + var res = arr.slice(); -module.exports = function filenameRegex() { - return /([^\\\/]+)$/; + var re = brackets.makeRe(pattern); + while (i < len) { + var ele = arr[i++]; + if (!re.test(ele)) { + continue; + } + res.splice(i, 1); + } + return res; }; /***/ }), -/* 469 */ +/* 479 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /*! - * fill-range <https://github.com/jonschlinkert/fill-range> + * expand-range <https://github.com/jonschlinkert/expand-range> * * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT License. - */ - - - -var isObject = __webpack_require__(543); -var isNumber = __webpack_require__(239); -var randomize = __webpack_require__(577); -var repeatStr = __webpack_require__(585); -var repeat = __webpack_require__(257); - -/** - * Expose `fillRange` + * Licensed under the MIT license. */ -module.exports = fillRange; -/** - * Return a range of numbers or letters. - * - * @param {String} `a` Start of the range - * @param {String} `b` End of the range - * @param {String} `step` Increment or decrement to use. - * @param {Function} `fn` Custom function to modify each element in the range. - * @return {Array} - */ -function fillRange(a, b, step, options, fn) { - if (a == null || b == null) { - throw new Error('fill-range expects the first and second args to be strings.'); - } +var fill = __webpack_require__(487); - if (typeof step === 'function') { - fn = step; options = {}; step = null; +module.exports = function expandRange(str, options, fn) { + if (typeof str !== 'string') { + throw new TypeError('expand-range expects a string.'); } if (typeof options === 'function') { - fn = options; options = {}; + fn = options; + options = {}; } - if (isObject(step)) { - options = step; step = ''; + if (typeof options === 'boolean') { + options = {}; + options.makeRe = true; } - var expand, regex = false, sep = ''; + // create arguments to pass to fill-range var opts = options || {}; + var args = str.split('..'); + var len = args.length; + if (len > 3) { return str; } - if (typeof opts.silent === 'undefined') { - opts.silent = true; - } - - step = step || opts.step; - - // store a ref to unmodified arg - var origA = a, origB = b; - - b = (b.toString() === '-0') ? 0 : b; - - if (opts.optimize || opts.makeRe) { - step = step ? (step += '~') : step; - expand = true; - regex = true; - sep = '~'; - } - - // handle special step characters - if (typeof step === 'string') { - var match = stepRe().exec(step); - - if (match) { - var i = match.index; - var m = match[0]; - - // repeat string - if (m === '+') { - return repeat(a, b); - - // randomize a, `b` times - } else if (m === '?') { - return [randomize(a, b)]; - - // expand right, no regex reduction - } else if (m === '>') { - step = step.substr(0, i) + step.substr(i + 1); - expand = true; - - // expand to an array, or if valid create a reduced - // string for a regex logic `or` - } else if (m === '|') { - step = step.substr(0, i) + step.substr(i + 1); - expand = true; - regex = true; - sep = m; - - // expand to an array, or if valid create a reduced - // string for a regex range - } else if (m === '~') { - step = step.substr(0, i) + step.substr(i + 1); - expand = true; - regex = true; - sep = m; - } - } else if (!isNumber(step)) { - if (!opts.silent) { - throw new TypeError('fill-range: invalid step.'); - } - return null; - } - } - - if (/[.&*()[\]^%$#@!]/.test(a) || /[.&*()[\]^%$#@!]/.test(b)) { - if (!opts.silent) { - throw new RangeError('fill-range: invalid range arguments.'); - } - return null; - } + // if only one argument, it can't expand so return it + if (len === 1) { return args; } - // has neither a letter nor number, or has both letters and numbers - // this needs to be after the step logic - if (!noAlphaNum(a) || !noAlphaNum(b) || hasBoth(a) || hasBoth(b)) { - if (!opts.silent) { - throw new RangeError('fill-range: invalid range arguments.'); - } - return null; + // if `true`, tell fill-range to regexify the string + if (typeof fn === 'boolean' && fn === true) { + opts.makeRe = true; } - // validate arguments - var isNumA = isNumber(zeros(a)); - var isNumB = isNumber(zeros(b)); + args.push(opts); + return fill.apply(null, args.concat(fn)); +}; - if ((!isNumA && isNumB) || (isNumA && !isNumB)) { - if (!opts.silent) { - throw new TypeError('fill-range: first range argument is incompatible with second.'); - } - return null; - } - // by this point both are the same, so we - // can use A to check going forward. - var isNum = isNumA; - var num = formatStep(step); +/***/ }), +/* 480 */ +/***/ (function(module, exports) { - // is the range alphabetical? or numeric? - if (isNum) { - // if numeric, coerce to an integer - a = +a; b = +b; - } else { - // otherwise, get the charCode to expand alpha ranges - a = a.charCodeAt(0); - b = b.charCodeAt(0); - } +// Generated by CoffeeScript 1.12.0 - // is the pattern descending? - var isDescending = a > b; +/* + ExternalEditor + Kevin Gravier <kevin@mrkmg.com> + MIT + */ - // don't create a character class if the args are < 0 - if (a < 0 || b < 0) { - expand = false; - regex = false; - } +(function() { + var CreateFileError, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; - // detect padding - var padding = isPadded(origA, origB); - var res, pad, arr = []; - var ii = 0; + CreateFileError = (function(superClass) { + extend(CreateFileError, superClass); - // character classes, ranges and logical `or` - if (regex) { - if (shouldExpand(a, b, num, isNum, padding, opts)) { - // make sure the correct separator is used - if (sep === '|' || sep === '~') { - sep = detectSeparator(a, b, num, isNum, isDescending); - } - return wrap([origA, origB], sep, opts); - } - } + CreateFileError.prototype.message = 'Failed to create temporary file for editor'; - while (isDescending ? (a >= b) : (a <= b)) { - if (padding && isNum) { - pad = padding(a); + function CreateFileError(original_error) { + this.original_error = original_error; } - // custom function - if (typeof fn === 'function') { - res = fn(a, isNum, pad, ii++); + return CreateFileError; - // letters - } else if (!isNum) { - if (regex && isInvalidChar(a)) { - res = null; - } else { - res = String.fromCharCode(a); - } + })(Error); - // numbers - } else { - res = formatPadding(a, pad); - } + module.exports = CreateFileError; - // add result to the array, filtering any nulled values - if (res !== null) arr.push(res); +}).call(this); - // increment or decrement - if (isDescending) { - a -= num; - } else { - a += num; - } - } - // now that the array is expanded, we need to handle regex - // character classes, ranges or logical `or` that wasn't - // already handled before the loop - if ((regex || expand) && !opts.noexpand) { - // make sure the correct separator is used - if (sep === '|' || sep === '~') { - sep = detectSeparator(a, b, num, isNum, isDescending); - } - if (arr.length === 1 || a < 0 || b < 0) { return arr; } - return wrap(arr, sep, opts); - } +/***/ }), +/* 481 */ +/***/ (function(module, exports) { - return arr; -} +// Generated by CoffeeScript 1.12.0 -/** - * Wrap the string with the correct regex - * syntax. +/* + ExternalEditor + Kevin Gravier <kevin@mrkmg.com> + MIT */ -function wrap(arr, sep, opts) { - if (sep === '~') { sep = '-'; } - var str = arr.join(sep); - var pre = opts && opts.regexPrefix; +(function() { + var LaunchEditorError, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; - // regex logical `or` - if (sep === '|') { - str = pre ? pre + str : str; - str = '(' + str + ')'; - } + LaunchEditorError = (function(superClass) { + extend(LaunchEditorError, superClass); - // regex character class - if (sep === '-') { - str = (pre && pre === '^') - ? pre + str - : str; - str = '[' + str + ']'; - } - return [str]; -} + LaunchEditorError.prototype.message = 'Failed launch editor'; -/** - * Check for invalid characters - */ + function LaunchEditorError(original_error) { + this.original_error = original_error; + } -function isCharClass(a, b, step, isNum, isDescending) { - if (isDescending) { return false; } - if (isNum) { return a <= 9 && b <= 9; } - if (a < b) { return step === 1; } - return false; -} + return LaunchEditorError; -/** - * Detect the correct separator to use - */ + })(Error); -function shouldExpand(a, b, num, isNum, padding, opts) { - if (isNum && (a > 9 || b > 9)) { return false; } - return !padding && num === 1 && a < b; -} + module.exports = LaunchEditorError; -/** - * Detect the correct separator to use - */ +}).call(this); -function detectSeparator(a, b, step, isNum, isDescending) { - var isChar = isCharClass(a, b, step, isNum, isDescending); - if (!isChar) { - return '|'; - } - return '~'; -} -/** - * Correctly format the step based on type - */ +/***/ }), +/* 482 */ +/***/ (function(module, exports) { -function formatStep(step) { - return Math.abs(step >> 0) || 1; -} +// Generated by CoffeeScript 1.12.0 -/** - * Format padding, taking leading `-` into account +/* + ExternalEditor + Kevin Gravier <kevin@mrkmg.com> + MIT */ -function formatPadding(ch, pad) { - var res = pad ? pad + ch : ch; - if (pad && ch.toString().charAt(0) === '-') { - res = '-' + pad + ch.toString().substr(1); - } - return res.toString(); -} - -/** - * Check for invalid characters - */ +(function() { + var ReadFileError, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; -function isInvalidChar(str) { - var ch = toStr(str); - return ch === '\\' - || ch === '[' - || ch === ']' - || ch === '^' - || ch === '(' - || ch === ')' - || ch === '`'; -} + ReadFileError = (function(superClass) { + extend(ReadFileError, superClass); -/** - * Convert to a string from a charCode - */ + ReadFileError.prototype.message = 'Failed to read temporary file'; -function toStr(ch) { - return String.fromCharCode(ch); -} + function ReadFileError(original_error) { + this.original_error = original_error; + } + return ReadFileError; -/** - * Step regex - */ + })(Error); -function stepRe() { - return /\?|>|\||\+|\~/g; -} + module.exports = ReadFileError; -/** - * Return true if `val` has either a letter - * or a number - */ +}).call(this); -function noAlphaNum(val) { - return /[a-z0-9]/i.test(val); -} -/** - * Return true if `val` has both a letter and - * a number (invalid) - */ +/***/ }), +/* 483 */ +/***/ (function(module, exports) { -function hasBoth(val) { - return /[a-z][0-9]|[0-9][a-z]/i.test(val); -} +// Generated by CoffeeScript 1.12.0 -/** - * Normalize zeros for checks +/* + ExternalEditor + Kevin Gravier <kevin@mrkmg.com> + MIT */ -function zeros(val) { - if (/^-*0+$/.test(val.toString())) { - return '0'; - } - return val; -} - -/** - * Return true if `val` has leading zeros, - * or a similar valid pattern. - */ +(function() { + var RemoveFileError, + extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + hasProp = {}.hasOwnProperty; -function hasZeros(val) { - return /[^.]\.|^-*0+[0-9]/.test(val); -} + RemoveFileError = (function(superClass) { + extend(RemoveFileError, superClass); -/** - * If the string is padded, returns a curried function with - * the a cached padding string, or `false` if no padding. - * - * @param {*} `origA` String or number. - * @return {String|Boolean} - */ + RemoveFileError.prototype.message = 'Failed to cleanup temporary file'; -function isPadded(origA, origB) { - if (hasZeros(origA) || hasZeros(origB)) { - var alen = length(origA); - var blen = length(origB); + function RemoveFileError(original_error) { + this.original_error = original_error; + } - var len = alen >= blen - ? alen - : blen; + return RemoveFileError; - return function (a) { - return repeatStr('0', len - length(a)); - }; - } - return false; -} + })(Error); -/** - * Get the string length of `val` - */ + module.exports = RemoveFileError; -function length(val) { - return val.toString().length; -} +}).call(this); /***/ }), -/* 470 */ +/* 484 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; -/*! - * for-in <https://github.com/jonschlinkert/for-in> - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. +// Generated by CoffeeScript 1.12.0 + +/* + ExternalEditor + Kevin Gravier <kevin@mrkmg.com> + MIT */ +(function() { + var CreateFileError, ExternalEditor, FS, LaunchEditorError, ReadFileError, RemoveFileError, Spawn, SpawnSync, Temp, + bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; + FS = __webpack_require__(5); -module.exports = function forIn(obj, fn, thisArg) { - for (var key in obj) { - if (fn.call(thisArg, obj[key], key, obj) === false) { - break; - } - } -}; + Temp = __webpack_require__(642); + SpawnSync = __webpack_require__(148).spawnSync; -/***/ }), -/* 471 */ -/***/ (function(module, exports, __webpack_require__) { + Spawn = __webpack_require__(148).spawn; -"use strict"; -/*! - * for-own <https://github.com/jonschlinkert/for-own> - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + CreateFileError = __webpack_require__(480); + ReadFileError = __webpack_require__(482); + RemoveFileError = __webpack_require__(483); -var forIn = __webpack_require__(470); -var hasOwn = Object.prototype.hasOwnProperty; + LaunchEditorError = __webpack_require__(481); -module.exports = function forOwn(obj, fn, thisArg) { - forIn(obj, function(val, key) { - if (hasOwn.call(obj, key)) { - return fn.call(thisArg, obj[key], key, obj); - } - }); -}; + ExternalEditor = (function() { + ExternalEditor.edit = function(text) { + var editor; + if (text == null) { + text = ''; + } + editor = new ExternalEditor(text); + editor.run(); + editor.cleanup(); + return editor.text; + }; + ExternalEditor.editAsync = function(text, callback) { + var editor; + if (text == null) { + text = ''; + } + editor = new ExternalEditor(text); + return editor.runAsync(function(error_run, response) { + var error_cleanup; + if (!error_run) { + try { + editor.cleanup(); + } catch (error) { + error_cleanup = error; + if (typeof callback === 'function') { + callback(error_cleanup); + } + } + return callback(null, response); + } else { + return callback(error_run) in typeof callback === 'function'; + } + }); + }; -/***/ }), -/* 472 */ -/***/ (function(module, exports, __webpack_require__) { + ExternalEditor.CreateFileError = CreateFileError; -module.exports = ForeverAgent -ForeverAgent.SSL = ForeverAgentSSL + ExternalEditor.ReadFileError = ReadFileError; -var util = __webpack_require__(2) - , Agent = __webpack_require__(50).Agent - , net = __webpack_require__(77) - , tls = __webpack_require__(282) - , AgentSSL = __webpack_require__(112).Agent - -function getConnectionName(host, port) { - var name = '' - if (typeof host === 'string') { - name = host + ':' + port - } else { - // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. - name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') - } - return name -} + ExternalEditor.RemoveFileError = RemoveFileError; -function ForeverAgent(options) { - var self = this - self.options = options || {} - self.requests = {} - self.sockets = {} - self.freeSockets = {} - self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets - self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets - self.on('free', function(socket, host, port) { - var name = getConnectionName(host, port) + ExternalEditor.LaunchEditorError = LaunchEditorError; - if (self.requests[name] && self.requests[name].length) { - self.requests[name].shift().onSocket(socket) - } else if (self.sockets[name].length < self.minSockets) { - if (!self.freeSockets[name]) self.freeSockets[name] = [] - self.freeSockets[name].push(socket) - - // if an error happens while we don't use the socket anyway, meh, throw the socket away - var onIdleError = function() { - socket.destroy() - } - socket._onIdleError = onIdleError - socket.on('error', onIdleError) - } else { - // If there are no pending requests just destroy the - // socket and it will get removed from the pool. This - // gets us out of timeout issues and allows us to - // default to Connection:keep-alive. - socket.destroy() + ExternalEditor.prototype.text = ''; + + ExternalEditor.prototype.temp_file = void 0; + + ExternalEditor.prototype.editor = { + bin: void 0, + args: [] + }; + + function ExternalEditor(text1) { + this.text = text1 != null ? text1 : ''; + this.launchEditorAsync = bind(this.launchEditorAsync, this); + this.launchEditor = bind(this.launchEditor, this); + this.removeTemporaryFile = bind(this.removeTemporaryFile, this); + this.readTemporaryFile = bind(this.readTemporaryFile, this); + this.createTemporaryFile = bind(this.createTemporaryFile, this); + this.determineEditor = bind(this.determineEditor, this); + this.cleanup = bind(this.cleanup, this); + this.runAsync = bind(this.runAsync, this); + this.run = bind(this.run, this); + this.determineEditor(); + this.createTemporaryFile(); } - }) -} -util.inherits(ForeverAgent, Agent) + ExternalEditor.prototype.run = function() { + this.launchEditor(); + return this.readTemporaryFile(); + }; -ForeverAgent.defaultMinSockets = 5 + ExternalEditor.prototype.runAsync = function(callback) { + var error_launch; + try { + return this.launchEditorAsync((function(_this) { + return function() { + var error_read; + try { + _this.readTemporaryFile(); + if (typeof callback === 'function') { + return callback(null, _this.text); + } + } catch (error) { + error_read = error; + if (typeof callback === 'function') { + return callback(error_read); + } + } + }; + })(this)); + } catch (error) { + error_launch = error; + if (typeof callback === 'function') { + return callback(error_launch); + } + } + }; + ExternalEditor.prototype.cleanup = function() { + return this.removeTemporaryFile(); + }; -ForeverAgent.prototype.createConnection = net.createConnection -ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest -ForeverAgent.prototype.addRequest = function(req, host, port) { - var name = getConnectionName(host, port) - - if (typeof host !== 'string') { - var options = host - port = options.port - host = options.host - } + ExternalEditor.prototype.determineEditor = function() { + var args, ed, editor; + ed = /^win/.test(process.platform) ? 'notepad' : 'vim'; + editor = process.env.VISUAL || process.env.EDITOR || ed; + args = editor.split(/\s+/); + this.bin = args.shift(); + return this.args = args; + }; - if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { - var idleSocket = this.freeSockets[name].pop() - idleSocket.removeListener('error', idleSocket._onIdleError) - delete idleSocket._onIdleError - req._reusedSocket = true - req.onSocket(idleSocket) - } else { - this.addRequestNoreuse(req, host, port) - } -} + ExternalEditor.prototype.createTemporaryFile = function() { + var e; + try { + this.temp_file = Temp.tmpNameSync({}); + return FS.writeFileSync(this.temp_file, this.text); + } catch (error) { + e = error; + throw new CreateFileError(e); + } + }; -ForeverAgent.prototype.removeSocket = function(s, name, host, port) { - if (this.sockets[name]) { - var index = this.sockets[name].indexOf(s) - if (index !== -1) { - this.sockets[name].splice(index, 1) - } - } else if (this.sockets[name] && this.sockets[name].length === 0) { - // don't leak - delete this.sockets[name] - delete this.requests[name] - } - - if (this.freeSockets[name]) { - var index = this.freeSockets[name].indexOf(s) - if (index !== -1) { - this.freeSockets[name].splice(index, 1) - if (this.freeSockets[name].length === 0) { - delete this.freeSockets[name] + ExternalEditor.prototype.readTemporaryFile = function() { + var e; + try { + return this.text = FS.readFileSync(this.temp_file).toString(); + } catch (error) { + e = error; + throw new ReadFileError(e); } - } - } + }; - if (this.requests[name] && this.requests[name].length) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(name, host, port).emit('free') - } -} + ExternalEditor.prototype.removeTemporaryFile = function() { + var e; + try { + return FS.unlinkSync(this.temp_file); + } catch (error) { + e = error; + throw new RemoveFileError(e); + } + }; -function ForeverAgentSSL (options) { - ForeverAgent.call(this, options) -} -util.inherits(ForeverAgentSSL, ForeverAgent) + ExternalEditor.prototype.launchEditor = function() { + var e; + try { + return SpawnSync(this.bin, this.args.concat([this.temp_file]), { + stdio: 'inherit' + }); + } catch (error) { + e = error; + throw new LaunchEditorError(e); + } + }; -ForeverAgentSSL.prototype.createConnection = createConnectionSSL -ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest + ExternalEditor.prototype.launchEditorAsync = function(callback) { + var child_process, e; + try { + child_process = Spawn(this.bin, this.args.concat([this.temp_file]), { + stdio: 'inherit' + }); + return child_process.on('exit', function() { + if (typeof callback === 'function') { + return callback(); + } + }); + } catch (error) { + e = error; + throw new LaunchEditorError(e); + } + }; -function createConnectionSSL (port, host, options) { - if (typeof port === 'object') { - options = port; - } else if (typeof host === 'object') { - options = host; - } else if (typeof options === 'object') { - options = options; - } else { - options = {}; - } + return ExternalEditor; - if (typeof port === 'number') { - options.port = port; - } + })(); - if (typeof host === 'string') { - options.host = host; - } + module.exports = ExternalEditor; - return tls.connect(options); -} +}).call(this); /***/ }), -/* 473 */ +/* 485 */ /***/ (function(module, exports, __webpack_require__) { -var CombinedStream = __webpack_require__(213); -var util = __webpack_require__(2); -var path = __webpack_require__(1); -var http = __webpack_require__(50); -var https = __webpack_require__(112); -var parseUrl = __webpack_require__(11).parse; -var fs = __webpack_require__(6); -var mime = __webpack_require__(244); -var asynckit = __webpack_require__(324); -var populate = __webpack_require__(474); +"use strict"; +/*! + * extglob <https://github.com/jonschlinkert/extglob> + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ -// Public API -module.exports = FormData; -// make it a Stream -util.inherits(FormData, CombinedStream); /** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor + * Module dependencies */ -function FormData() { - if (!(this instanceof FormData)) { - return new FormData(); - } - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; +var isExtglob = __webpack_require__(137); +var re, cache = {}; - CombinedStream.call(this); -} +/** + * Expose `extglob` + */ -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; +module.exports = extglob; -FormData.prototype.append = function(field, value, options) { +/** + * Convert the given extglob `string` to a regex-compatible + * string. + * + * ```js + * var extglob = require('extglob'); + * extglob('!(a?(b))'); + * //=> '(?!a(?:b)?)[^/]*?' + * ``` + * + * @param {String} `str` The string to convert. + * @param {Object} `options` + * @option {Boolean} [options] `esc` If `false` special characters will not be escaped. Defaults to `true`. + * @option {Boolean} [options] `regex` If `true` a regular expression is returned instead of a string. + * @return {String} + * @api public + */ - options = options || {}; - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } +function extglob(str, opts) { + opts = opts || {}; + var o = {}, i = 0; - var append = CombinedStream.prototype.append.bind(this); + // fix common character reversals + // '*!(.js)' => '*.!(js)' + str = str.replace(/!\(([^\w*()])/g, '$1!('); - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; + // support file extension negation + str = str.replace(/([*\/])\.!\([*]\)/g, function (m, ch) { + if (ch === '/') { + return escape('\\/[^.]+'); + } + return escape('[^.]+'); + }); + + // create a unique key for caching by + // combining the string and options + var key = str + + String(!!opts.regex) + + String(!!opts.contains) + + String(!!opts.escape); + + if (cache.hasOwnProperty(key)) { + return cache[key]; } - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; + if (!(re instanceof RegExp)) { + re = regex(); } - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); + opts.negate = false; + var m; - append(header); - append(value); - append(footer); + while (m = re.exec(str)) { + var prefix = m[1]; + var inner = m[3]; + if (prefix === '!') { + opts.negate = true; + } - // pass along options.knownLength - this._trackLength(header, value, options); -}; + var id = '__EXTGLOB_' + (i++) + '__'; + // use the prefix of the _last_ (outtermost) pattern + o[id] = wrap(inner, prefix, opts.escape); + str = str.split(m[0]).join(id); + } -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; + var keys = Object.keys(o); + var len = keys.length; - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); + // we have to loop again to allow us to convert + // patterns in reverse order (starting with the + // innermost/last pattern first) + while (len--) { + var prop = keys[len]; + str = str.split(prop).join(o[prop]); } - this._valueLength += valueLength; + var result = opts.regex + ? toRegex(str, opts.contains, opts.negate) + : str; - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; + result = result.split('.').join('\\.'); - // empty or either doesn't have path or not an http response - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { - return; - } + // cache the result and return it + return (cache[key] = result); +} - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); +/** + * Convert `string` to a regex string. + * + * @param {String} `str` + * @param {String} `prefix` Character that determines how to wrap the string. + * @param {Boolean} `esc` If `false` special characters will not be escaped. Defaults to `true`. + * @return {String} + */ + +function wrap(inner, prefix, esc) { + if (esc) inner = escape(inner); + + switch (prefix) { + case '!': + return '(?!' + inner + ')[^/]' + (esc ? '%%%~' : '*?'); + case '@': + return '(?:' + inner + ')'; + case '+': + return '(?:' + inner + ')+'; + case '*': + return '(?:' + inner + ')' + (esc ? '%%' : '*') + case '?': + return '(?:' + inner + '|)'; + default: + return inner; } -}; +} -FormData.prototype._lengthRetriever = function(value, callback) { +function escape(str) { + str = str.split('*').join('[^/]%%%~'); + str = str.split('.').join('\\.'); + return str; +} - if (value.hasOwnProperty('fd')) { +/** + * extglob regex. + */ - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { +function regex() { + return /(\\?[@?!+*$]\\?)(\(([^()]*?)\))/; +} - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); +/** + * Negation regex + */ - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { +function negate(str) { + return '(?!^' + str + ').*$'; +} - var fileSize; +/** + * Create the regex to do the matching. If + * the leading character in the `pattern` is `!` + * a negation regex is returned. + * + * @param {String} `pattern` + * @param {Boolean} `contains` Allow loose matching. + * @param {Boolean} `isNegated` True if the pattern is a negation pattern. + */ - if (err) { - callback(err); - return; - } +function toRegex(pattern, contains, isNegated) { + var prefix = contains ? '^' : ''; + var after = contains ? '$' : ''; + pattern = ('(?:' + pattern + ')' + after); + if (isNegated) { + pattern = prefix + negate(pattern); + } + return new RegExp(prefix + pattern); +} - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); +/***/ }), +/* 486 */ +/***/ (function(module, exports) { - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); +/*! + * filename-regex <https://github.com/regexps/filename-regex> + * + * Copyright (c) 2014-2015, Jon Schlinkert + * Licensed under the MIT license. + */ - // something else - } else { - callback('Unknown stream'); - } +module.exports = function filenameRegex() { + return /([^\\\/]+)$/; }; -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } - - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; - - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } - var header; - for (var prop in headers) { - header = headers[prop]; +/***/ }), +/* 487 */ +/***/ (function(module, exports, __webpack_require__) { - // skip nullish headers. - if (header == null) { - continue; - } +"use strict"; +/*! + * fill-range <https://github.com/jonschlinkert/fill-range> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } - } - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; +var isObject = __webpack_require__(558); +var isNumber = __webpack_require__(292); +var randomize = __webpack_require__(592); +var repeatStr = __webpack_require__(600); +var repeat = __webpack_require__(310); -FormData.prototype._getContentDisposition = function(value, options) { +/** + * Expose `fillRange` + */ - var contentDisposition; +module.exports = fillRange; - // custom filename takes precedence - // fs- and request- streams have path property - // formidable and the browser add a name property. - var filename = options.filename || value.name || value.path; +/** + * Return a range of numbers or letters. + * + * @param {String} `a` Start of the range + * @param {String} `b` End of the range + * @param {String} `step` Increment or decrement to use. + * @param {Function} `fn` Custom function to modify each element in the range. + * @return {Array} + */ - // or try http response - if (!filename && value.readable && value.hasOwnProperty('httpVersion')) { - filename = value.client._httpMessage.path; +function fillRange(a, b, step, options, fn) { + if (a == null || b == null) { + throw new Error('fill-range expects the first and second args to be strings.'); } - if (filename) { - contentDisposition = 'filename="' + path.basename(filename) + '"'; + if (typeof step === 'function') { + fn = step; options = {}; step = null; } - return contentDisposition; -}; + if (typeof options === 'function') { + fn = options; options = {}; + } -FormData.prototype._getContentType = function(value, options) { + if (isObject(step)) { + options = step; step = ''; + } - // use custom content-type above all - var contentType = options.contentType; + var expand, regex = false, sep = ''; + var opts = options || {}; - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); + if (typeof opts.silent === 'undefined') { + opts.silent = true; } - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } + step = step || opts.step; - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } + // store a ref to unmodified arg + var origA = a, origB = b; - // or guess it from the filename - if (!contentType && options.filename) { - contentType = mime.lookup(options.filename); - } + b = (b.toString() === '-0') ? 0 : b; - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; + if (opts.optimize || opts.makeRe) { + step = step ? (step += '~') : step; + expand = true; + regex = true; + sep = '~'; } - return contentType; -}; + // handle special step characters + if (typeof step === 'string') { + var match = stepRe().exec(step); -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; + if (match) { + var i = match.index; + var m = match[0]; - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } + // repeat string + if (m === '+') { + return repeat(a, b); - next(footer); - }.bind(this); -}; + // randomize a, `b` times + } else if (m === '?') { + return [randomize(a, b)]; -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; + // expand right, no regex reduction + } else if (m === '>') { + step = step.substr(0, i) + step.substr(i + 1); + expand = true; -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; + // expand to an array, or if valid create a reduced + // string for a regex logic `or` + } else if (m === '|') { + step = step.substr(0, i) + step.substr(i + 1); + expand = true; + regex = true; + sep = m; - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; + // expand to an array, or if valid create a reduced + // string for a regex range + } else if (m === '~') { + step = step.substr(0, i) + step.substr(i + 1); + expand = true; + regex = true; + sep = m; + } + } else if (!isNumber(step)) { + if (!opts.silent) { + throw new TypeError('fill-range: invalid step.'); + } + return null; } } - return formHeaders; -}; + if (/[.&*()[\]^%$#@!]/.test(a) || /[.&*()[\]^%$#@!]/.test(b)) { + if (!opts.silent) { + throw new RangeError('fill-range: invalid range arguments.'); + } + return null; + } -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); + // has neither a letter nor number, or has both letters and numbers + // this needs to be after the step logic + if (!noAlphaNum(a) || !noAlphaNum(b) || hasBoth(a) || hasBoth(b)) { + if (!opts.silent) { + throw new RangeError('fill-range: invalid range arguments.'); + } + return null; } - return this._boundary; -}; + // validate arguments + var isNumA = isNumber(zeros(a)); + var isNumB = isNumber(zeros(b)); -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); + if ((!isNumA && isNumB) || (isNumA && !isNumB)) { + if (!opts.silent) { + throw new TypeError('fill-range: first range argument is incompatible with second.'); + } + return null; } - this._boundary = boundary; -}; - -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; + // by this point both are the same, so we + // can use A to check going forward. + var isNum = isNumA; + var num = formatStep(step); - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; + // is the range alphabetical? or numeric? + if (isNum) { + // if numeric, coerce to an integer + a = +a; b = +b; + } else { + // otherwise, get the charCode to expand alpha ranges + a = a.charCodeAt(0); + b = b.charCodeAt(0); } - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } + // is the pattern descending? + var isDescending = a > b; - return knownLength; -}; + // don't create a character class if the args are < 0 + if (a < 0 || b < 0) { + expand = false; + regex = false; + } -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; + // detect padding + var padding = isPadded(origA, origB); + var res, pad, arr = []; + var ii = 0; - if (this._valuesToMeasure.length) { - hasKnownLength = false; + // character classes, ranges and logical `or` + if (regex) { + if (shouldExpand(a, b, num, isNum, padding, opts)) { + // make sure the correct separator is used + if (sep === '|' || sep === '~') { + sep = detectSeparator(a, b, num, isNum, isDescending); + } + return wrap([origA, origB], sep, opts); + } } - return hasKnownLength; -}; - -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; + while (isDescending ? (a >= b) : (a <= b)) { + if (padding && isNum) { + pad = padding(a); + } - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } + // custom function + if (typeof fn === 'function') { + res = fn(a, isNum, pad, ii++); - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } + // letters + } else if (!isNum) { + if (regex && isInvalidChar(a)) { + res = null; + } else { + res = String.fromCharCode(a); + } - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; + // numbers + } else { + res = formatPadding(a, pad); } - values.forEach(function(length) { - knownLength += length; - }); + // add result to the array, filtering any nulled values + if (res !== null) arr.push(res); - cb(null, knownLength); - }); -}; + // increment or decrement + if (isDescending) { + a -= num; + } else { + a += num; + } + } -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; + // now that the array is expanded, we need to handle regex + // character classes, ranges or logical `or` that wasn't + // already handled before the loop + if ((regex || expand) && !opts.noexpand) { + // make sure the correct separator is used + if (sep === '|' || sep === '~') { + sep = detectSeparator(a, b, num, isNum, isDescending); + } + if (arr.length === 1 || a < 0 || b < 0) { return arr; } + return wrap(arr, sep, opts); + } - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { + return arr; +} - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname - }, defaults); +/** + * Wrap the string with the correct regex + * syntax. + */ - // use custom params - } else { +function wrap(arr, sep, opts) { + if (sep === '~') { sep = '-'; } + var str = arr.join(sep); + var pre = opts && opts.regexPrefix; - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; - } + // regex logical `or` + if (sep === '|') { + str = pre ? pre + str : str; + str = '(' + str + ')'; } - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); - - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); + // regex character class + if (sep === '-') { + str = (pre && pre === '^') + ? pre + str + : str; + str = '[' + str + ']'; } + return [str]; +} - // get content length and fire away - this.getLength(function(err, length) { - if (err) { - this._error(err); - return; - } +/** + * Check for invalid characters + */ - // add content length - request.setHeader('Content-Length', length); +function isCharClass(a, b, step, isNum, isDescending) { + if (isDescending) { return false; } + if (isNum) { return a <= 9 && b <= 9; } + if (a < b) { return step === 1; } + return false; +} - this.pipe(request); - if (cb) { - request.on('error', cb); - request.on('response', cb.bind(this, null)); - } - }.bind(this)); +/** + * Detect the correct separator to use + */ - return request; -}; +function shouldExpand(a, b, num, isNum, padding, opts) { + if (isNum && (a > 9 || b > 9)) { return false; } + return !padding && num === 1 && a < b; +} + +/** + * Detect the correct separator to use + */ -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); +function detectSeparator(a, b, step, isNum, isDescending) { + var isChar = isCharClass(a, b, step, isNum, isDescending); + if (!isChar) { + return '|'; } -}; + return '~'; +} -FormData.prototype.toString = function () { - return '[object FormData]'; -}; +/** + * Correctly format the step based on type + */ +function formatStep(step) { + return Math.abs(step >> 0) || 1; +} -/***/ }), -/* 474 */ -/***/ (function(module, exports) { +/** + * Format padding, taking leading `-` into account + */ -// populates missing values -module.exports = function(dst, src) { +function formatPadding(ch, pad) { + var res = pad ? pad + ch : ch; + if (pad && ch.toString().charAt(0) === '-') { + res = '-' + pad + ch.toString().substr(1); + } + return res.toString(); +} - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); +/** + * Check for invalid characters + */ - return dst; -}; +function isInvalidChar(str) { + var ch = toStr(str); + return ch === '\\' + || ch === '[' + || ch === ']' + || ch === '^' + || ch === '(' + || ch === ')' + || ch === '`'; +} +/** + * Convert to a string from a charCode + */ -/***/ }), -/* 475 */ -/***/ (function(module, exports, __webpack_require__) { +function toStr(ch) { + return String.fromCharCode(ch); +} -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -var pathModule = __webpack_require__(1); -var isWindows = process.platform === 'win32'; -var fs = __webpack_require__(6); +/** + * Step regex + */ -// JavaScript implementation of realpath, ported from node pre-v6 +function stepRe() { + return /\?|>|\||\+|\~/g; +} -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); +/** + * Return true if `val` has either a letter + * or a number + */ -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; +function noAlphaNum(val) { + return /[a-z0-9]/i.test(val); +} - return callback; +/** + * Return true if `val` has both a letter and + * a number (invalid) + */ - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } - } +function hasBoth(val) { + return /[a-z][0-9]|[0-9][a-z]/i.test(val); +} - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } - } +/** + * Normalize zeros for checks + */ + +function zeros(val) { + if (/^-*0+$/.test(val.toString())) { + return '0'; } + return val; } -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); +/** + * Return true if `val` has leading zeros, + * or a similar valid pattern. + */ + +function hasZeros(val) { + return /[^.]\.|^-*0+[0-9]/.test(val); } -var normalize = pathModule.normalize; +/** + * If the string is padded, returns a curried function with + * the a cached padding string, or `false` if no padding. + * + * @param {*} `origA` String or number. + * @return {String|Boolean} + */ -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} +function isPadded(origA, origB) { + if (hasZeros(origA) || hasZeros(origB)) { + var alen = length(origA); + var blen = length(origB); -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; + var len = alen >= blen + ? alen + : blen; + + return function (a) { + return repeatStr('0', len - length(a)); + }; + } + return false; } -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +/** + * Get the string length of `val` + */ - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } +function length(val) { + return val.toString().length; +} - var original = p, - seenLinks = {}, - knownHard = {}; - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; +/***/ }), +/* 488 */ +/***/ (function(module, exports, __webpack_require__) { - start(); +"use strict"; +/*! + * for-in <https://github.com/jonschlinkert/for-in> + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; + +module.exports = function forIn(obj, fn, thisArg) { + for (var key in obj) { + if (fn.call(thisArg, obj[key], key, obj) === false) { + break; } } +}; - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } +/***/ }), +/* 489 */ +/***/ (function(module, exports, __webpack_require__) { - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } +"use strict"; +/*! + * for-own <https://github.com/jonschlinkert/for-own> + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; - } - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); - } - if (cache) cache[original] = p; +var forIn = __webpack_require__(488); +var hasOwn = Object.prototype.hasOwnProperty; - return p; +module.exports = function forOwn(obj, fn, thisArg) { + forIn(obj, function(val, key) { + if (hasOwn.call(obj, key)) { + return fn.call(thisArg, obj[key], key, obj); + } + }); }; -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } +/***/ }), +/* 490 */ +/***/ (function(module, exports, __webpack_require__) { - // make p is absolute - p = pathModule.resolve(p); +module.exports = ForeverAgent +ForeverAgent.SSL = ForeverAgentSSL - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); +var util = __webpack_require__(2) + , Agent = __webpack_require__(49).Agent + , net = __webpack_require__(59) + , tls = __webpack_require__(332) + , AgentSSL = __webpack_require__(149).Agent + +function getConnectionName(host, port) { + var name = '' + if (typeof host === 'string') { + name = host + ':' + port + } else { + // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name. + name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':') } + return name +} - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +function ForeverAgent(options) { + var self = this + self.options = options || {} + self.requests = {} + self.sockets = {} + self.freeSockets = {} + self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets + self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets + self.on('free', function(socket, host, port) { + var name = getConnectionName(host, port) - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); + if (self.requests[name] && self.requests[name].length) { + self.requests[name].shift().onSocket(socket) + } else if (self.sockets[name].length < self.minSockets) { + if (!self.freeSockets[name]) self.freeSockets[name] = [] + self.freeSockets[name].push(socket) + + // if an error happens while we don't use the socket anyway, meh, throw the socket away + var onIdleError = function() { + socket.destroy() + } + socket._onIdleError = onIdleError + socket.on('error', onIdleError) } else { - process.nextTick(LOOP); - } - } - - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); + // If there are no pending requests just destroy the + // socket and it will get removed from the pool. This + // gets us out of timeout issues and allows us to + // default to Connection:keep-alive. + socket.destroy() } + }) - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +} +util.inherits(ForeverAgent, Agent) - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } +ForeverAgent.defaultMinSockets = 5 - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } - return fs.lstat(base, gotStat); +ForeverAgent.prototype.createConnection = net.createConnection +ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest +ForeverAgent.prototype.addRequest = function(req, host, port) { + var name = getConnectionName(host, port) + + if (typeof host !== 'string') { + var options = host + port = options.port + host = options.host } - function gotStat(err, stat) { - if (err) return cb(err); + if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) { + var idleSocket = this.freeSockets[name].pop() + idleSocket.removeListener('error', idleSocket._onIdleError) + delete idleSocket._onIdleError + req._reusedSocket = true + req.onSocket(idleSocket) + } else { + this.addRequestNoreuse(req, host, port) + } +} - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); +ForeverAgent.prototype.removeSocket = function(s, name, host, port) { + if (this.sockets[name]) { + var index = this.sockets[name].indexOf(s) + if (index !== -1) { + this.sockets[name].splice(index, 1) } - - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); + } else if (this.sockets[name] && this.sockets[name].length === 0) { + // don't leak + delete this.sockets[name] + delete this.requests[name] + } + + if (this.freeSockets[name]) { + var index = this.freeSockets[name].indexOf(s) + if (index !== -1) { + this.freeSockets[name].splice(index, 1) + if (this.freeSockets[name].length === 0) { + delete this.freeSockets[name] } } - fs.stat(base, function(err) { - if (err) return cb(err); + } - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); + if (this.requests[name] && this.requests[name].length) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(name, host, port).emit('free') } +} - function gotTarget(err, target, base) { - if (err) return cb(err); +function ForeverAgentSSL (options) { + ForeverAgent.call(this, options) +} +util.inherits(ForeverAgentSSL, ForeverAgent) - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); +ForeverAgentSSL.prototype.createConnection = createConnectionSSL +ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest + +function createConnectionSSL (port, host, options) { + if (typeof port === 'object') { + options = port; + } else if (typeof host === 'object') { + options = host; + } else if (typeof options === 'object') { + options = options; + } else { + options = {}; } - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + if (typeof port === 'number') { + options.port = port; + } + + if (typeof host === 'string') { + options.host = host; } -}; + + return tls.connect(options); +} /***/ }), -/* 476 */ +/* 491 */ /***/ (function(module, exports, __webpack_require__) { -"use strict"; -/*! - * glob-base <https://github.com/jonschlinkert/glob-base> +var CombinedStream = __webpack_require__(281); +var util = __webpack_require__(2); +var path = __webpack_require__(0); +var http = __webpack_require__(49); +var https = __webpack_require__(149); +var parseUrl = __webpack_require__(14).parse; +var fs = __webpack_require__(5); +var mime = __webpack_require__(296); +var asynckit = __webpack_require__(379); +var populate = __webpack_require__(492); + +// Public API +module.exports = FormData; + +// make it a Stream +util.inherits(FormData, CombinedStream); + +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. * - * Copyright (c) 2015, Jon Schlinkert. - * Licensed under the MIT License. + * @constructor */ +function FormData() { + if (!(this instanceof FormData)) { + return new FormData(); + } + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + CombinedStream.call(this); +} -var path = __webpack_require__(1); -var parent = __webpack_require__(477); -var isGlob = __webpack_require__(101); +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; -module.exports = function globBase(pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('glob-base expects a string.'); - } +FormData.prototype.append = function(field, value, options) { - var res = {}; - res.base = parent(pattern); - res.isGlob = isGlob(pattern); + options = options || {}; - if (res.base !== '.') { - res.glob = pattern.substr(res.base.length); - if (res.glob.charAt(0) === '/') { - res.glob = res.glob.substr(1); - } - } else { - res.glob = pattern; + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; } - if (!res.isGlob) { - res.base = dirname(pattern); - res.glob = res.base !== '.' - ? pattern.substr(res.base.length) - : pattern; - } + var append = CombinedStream.prototype.append.bind(this); - if (res.glob.substr(0, 2) === './') { - res.glob = res.glob.substr(2); + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; } - if (res.glob.charAt(0) === '/') { - res.glob = res.glob.substr(1); + + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; } - return res; -}; -function dirname(glob) { - if (glob.slice(-1) === '/') return glob; - return path.dirname(glob); -} + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + append(header); + append(value); + append(footer); -/***/ }), -/* 477 */ -/***/ (function(module, exports, __webpack_require__) { + // pass along options.knownLength + this._trackLength(header, value, options); +}; -"use strict"; +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } -var path = __webpack_require__(1); -var isglob = __webpack_require__(101); + this._valueLength += valueLength; -module.exports = function globParent(str) { - str += 'a'; // preserves full path in case of trailing path separator - do {str = path.dirname(str)} while (isglob(str)); - return str; -}; + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; + // empty or either doesn't have path or not an http response + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { + return; + } -/***/ }), -/* 478 */ -/***/ (function(module, exports, __webpack_require__) { + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; -module.exports = globSync -globSync.GlobSync = GlobSync +FormData.prototype._lengthRetriever = function(value, callback) { -var fs = __webpack_require__(6) -var rp = __webpack_require__(233) -var minimatch = __webpack_require__(159) -var Minimatch = minimatch.Minimatch -var Glob = __webpack_require__(150).Glob -var util = __webpack_require__(2) -var path = __webpack_require__(1) -var assert = __webpack_require__(22) -var isAbsolute = __webpack_require__(161) -var common = __webpack_require__(234) -var alphasort = common.alphasort -var alphasorti = common.alphasorti -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + if (value.hasOwnProperty('fd')) { -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - return new GlobSync(pattern, options).found -} + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + var fileSize; - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) + if (err) { + callback(err); + return; + } - setopts(this, pattern, options) + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } - if (this.noprocess) - return this + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); + + // something else + } else { + callback('Unknown stream'); } - this._finish() -} +}; -GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; } - common.finish(this) -} + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); } - // now n is the index of the first one that is *not* a string. - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return + var header; + for (var prop in headers) { + header = headers[prop]; - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + // skip nullish headers. + if (header == null) { + continue; + } - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } + + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } } - var remain = pattern.slice(n) + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix +FormData.prototype._getContentDisposition = function(value, options) { - var abs = this._makeAbs(read) + var contentDisposition; - //if ignored, skip processing - if (childrenIgnored(this, read)) - return + // custom filename takes precedence + // fs- and request- streams have path property + // formidable and the browser add a name property. + var filename = options.filename || value.name || value.path; - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} + // or try http response + if (!filename && value.readable && value.hasOwnProperty('httpVersion')) { + filename = value.client._httpMessage.path; + } + if (filename) { + contentDisposition = 'filename="' + path.basename(filename) + '"'; + } -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) + return contentDisposition; +}; - // if the abs isn't a dir, then nothing can match! - if (!entries) - return +FormData.prototype._getContentType = function(value, options) { - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' + // use custom content-type above all + var contentType = options.contentType; - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. - - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return + // or guess it from the filename + if (!contentType && options.filename) { + contentType = mime.lookup(options.filename); } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; } -} + return contentType; +}; -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; - var abs = this._makeAbs(e) + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } - if (this.mark) - e = this._mark(e) + next(footer); + }.bind(this); +}; - if (this.absolute) { - e = abs +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; + +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; + + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } } - if (this.matches[index][e]) - return + return formHeaders; +}; - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); } - this.matches[index][e] = true + return this._boundary; +}; - if (this.stat) - this._stat(e) -} +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } + this._boundary = boundary; +}; -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; - var entries - var lstat - var stat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) + return knownLength; +}; - return entries -} +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) + return hasKnownLength; +}; - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - if (Array.isArray(c)) - return c + if (this._streams.length) { + knownLength += this._lastBoundary().length; } - try { - return this._readdirEntries(abs, fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; } -} -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; } - } - - this.cache[abs] = entries - // mark and cache dir-ness - return entries -} + values.forEach(function(length) { + knownLength += length; + }); -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break + cb(null, knownLength); + }); +}; - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname + }, defaults); - var entries = this._readdir(abs, inGlobStar) + // use custom params + } else { - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } - var len = entries.length - var isSym = this.symlinks[abs] + // get content length and fire away + this.getLength(function(err, length) { + if (err) { + this._error(err); + return; + } - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return + // add content length + request.setHeader('Content-Length', length); - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + this.pipe(request); + if (cb) { + request.on('error', cb); + request.on('response', cb.bind(this, null)); + } + }.bind(this)); - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) + return request; +}; - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); } -} +}; -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) +FormData.prototype.toString = function () { + return '[object FormData]'; +}; - if (!this.matches[index]) - this.matches[index] = Object.create(null) - // If it doesn't exist, then just mark the lack of results - if (!exists) - return +/***/ }), +/* 492 */ +/***/ (function(module, exports) { - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } - } +// populates missing values +module.exports = function(dst, src) { - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); - // Mark this as a match - this._emitMatch(index, prefix) -} + return dst; +}; -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' - if (f.length > this.maxLength) - return false +/***/ }), +/* 493 */ +/***/ (function(module, exports, __webpack_require__) { - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] +"use strict"; +/*! + * glob-base <https://github.com/jonschlinkert/glob-base> + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + */ - if (Array.isArray(c)) - c = 'DIR' - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c - if (needDir && c === 'FILE') - return false +var path = __webpack_require__(0); +var parent = __webpack_require__(494); +var isGlob = __webpack_require__(138); - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. +module.exports = function globBase(pattern) { + if (typeof pattern !== 'string') { + throw new TypeError('glob-base expects a string.'); } - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } - } + var res = {}; + res.base = parent(pattern); + res.isGlob = isGlob(pattern); - if (lstat && lstat.isSymbolicLink()) { - try { - stat = fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat + if (res.base !== '.') { + res.glob = pattern.substr(res.base.length); + if (res.glob.charAt(0) === '/') { + res.glob = res.glob.substr(1); } + } else { + res.glob = pattern; } - this.statCache[abs] = stat + if (!res.isGlob) { + res.base = dirname(pattern); + res.glob = res.base !== '.' + ? pattern.substr(res.base.length) + : pattern; + } - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' + if (res.glob.substr(0, 2) === './') { + res.glob = res.glob.substr(2); + } + if (res.glob.charAt(0) === '/') { + res.glob = res.glob.substr(1); + } + return res; +}; - this.cache[abs] = this.cache[abs] || c +function dirname(glob) { + if (glob.slice(-1) === '/') return glob; + return path.dirname(glob); +} - if (needDir && c === 'FILE') - return false - return c -} +/***/ }), +/* 494 */ +/***/ (function(module, exports, __webpack_require__) { -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} +"use strict"; -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + +var path = __webpack_require__(0); +var isglob = __webpack_require__(138); + +module.exports = function globParent(str) { + str += 'a'; // preserves full path in case of trailing path separator + do {str = path.dirname(str)} while (isglob(str)); + return str; +}; /***/ }), -/* 479 */ +/* 495 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(20).Stream +var Stream = __webpack_require__(26).Stream module.exports = legacy @@ -89894,11 +93493,11 @@ function legacy (fs) { /***/ }), -/* 480 */ +/* 496 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(235) -var constants = __webpack_require__(280) +var fs = __webpack_require__(288) +var constants = __webpack_require__(331) var origCwd = process.cwd var cwd = null @@ -90230,10 +93829,10 @@ function chownErOk (er) { /***/ }), -/* 481 */ +/* 497 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(6) +var fs = __webpack_require__(5) , lstat = fs.lstatSync; exports.readlinkSync = function (p) { @@ -90248,15 +93847,15 @@ exports.readlinkSync = function (p) { /***/ }), -/* 482 */ +/* 498 */ /***/ (function(module, exports, __webpack_require__) { -var zlib = __webpack_require__(169) -var peek = __webpack_require__(569) -var through = __webpack_require__(271) -var pumpify = __webpack_require__(574) -var isGzip = __webpack_require__(539) -var isDeflate = __webpack_require__(535) +var zlib = __webpack_require__(230) +var peek = __webpack_require__(583) +var through = __webpack_require__(323) +var pumpify = __webpack_require__(588) +var isGzip = __webpack_require__(553) +var isDeflate = __webpack_require__(549) var isCompressed = function (data) { if (isGzip(data)) return 1 @@ -90283,7 +93882,7 @@ module.exports = gunzip /***/ }), -/* 483 */ +/* 499 */ /***/ (function(module, exports) { module.exports = { @@ -90317,7 +93916,7 @@ module.exports = { }; /***/ }), -/* 484 */ +/* 500 */ /***/ (function(module, exports) { module.exports = { @@ -90351,7 +93950,7 @@ module.exports = { }; /***/ }), -/* 485 */ +/* 501 */ /***/ (function(module, exports) { module.exports = { @@ -90375,7 +93974,7 @@ module.exports = { }; /***/ }), -/* 486 */ +/* 502 */ /***/ (function(module, exports) { module.exports = { @@ -90408,7 +94007,7 @@ module.exports = { }; /***/ }), -/* 487 */ +/* 503 */ /***/ (function(module, exports) { module.exports = { @@ -90441,7 +94040,7 @@ module.exports = { }; /***/ }), -/* 488 */ +/* 504 */ /***/ (function(module, exports) { module.exports = { @@ -90484,7 +94083,7 @@ module.exports = { }; /***/ }), -/* 489 */ +/* 505 */ /***/ (function(module, exports) { module.exports = { @@ -90508,7 +94107,7 @@ module.exports = { }; /***/ }), -/* 490 */ +/* 506 */ /***/ (function(module, exports) { module.exports = { @@ -90569,7 +94168,7 @@ module.exports = { }; /***/ }), -/* 491 */ +/* 507 */ /***/ (function(module, exports) { module.exports = { @@ -90586,7 +94185,7 @@ module.exports = { }; /***/ }), -/* 492 */ +/* 508 */ /***/ (function(module, exports) { module.exports = { @@ -90610,36 +94209,36 @@ module.exports = { }; /***/ }), -/* 493 */ +/* 509 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = { - afterRequest: __webpack_require__(483), - beforeRequest: __webpack_require__(484), - browser: __webpack_require__(485), - cache: __webpack_require__(486), - content: __webpack_require__(487), - cookie: __webpack_require__(488), - creator: __webpack_require__(489), - entry: __webpack_require__(490), - har: __webpack_require__(491), - header: __webpack_require__(492), - log: __webpack_require__(494), - page: __webpack_require__(495), - pageTimings: __webpack_require__(496), - postData: __webpack_require__(497), - query: __webpack_require__(498), - request: __webpack_require__(499), - response: __webpack_require__(500), - timings: __webpack_require__(501) + afterRequest: __webpack_require__(499), + beforeRequest: __webpack_require__(500), + browser: __webpack_require__(501), + cache: __webpack_require__(502), + content: __webpack_require__(503), + cookie: __webpack_require__(504), + creator: __webpack_require__(505), + entry: __webpack_require__(506), + har: __webpack_require__(507), + header: __webpack_require__(508), + log: __webpack_require__(510), + page: __webpack_require__(511), + pageTimings: __webpack_require__(512), + postData: __webpack_require__(513), + query: __webpack_require__(514), + request: __webpack_require__(515), + response: __webpack_require__(516), + timings: __webpack_require__(517) } /***/ }), -/* 494 */ +/* 510 */ /***/ (function(module, exports) { module.exports = { @@ -90679,7 +94278,7 @@ module.exports = { }; /***/ }), -/* 495 */ +/* 511 */ /***/ (function(module, exports) { module.exports = { @@ -90715,7 +94314,7 @@ module.exports = { }; /***/ }), -/* 496 */ +/* 512 */ /***/ (function(module, exports) { module.exports = { @@ -90737,7 +94336,7 @@ module.exports = { }; /***/ }), -/* 497 */ +/* 513 */ /***/ (function(module, exports) { module.exports = { @@ -90784,7 +94383,7 @@ module.exports = { }; /***/ }), -/* 498 */ +/* 514 */ /***/ (function(module, exports) { module.exports = { @@ -90808,7 +94407,7 @@ module.exports = { }; /***/ }), -/* 499 */ +/* 515 */ /***/ (function(module, exports) { module.exports = { @@ -90869,7 +94468,7 @@ module.exports = { }; /***/ }), -/* 500 */ +/* 516 */ /***/ (function(module, exports) { module.exports = { @@ -90927,7 +94526,7 @@ module.exports = { }; /***/ }), -/* 501 */ +/* 517 */ /***/ (function(module, exports) { module.exports = { @@ -90973,7 +94572,7 @@ module.exports = { }; /***/ }), -/* 502 */ +/* 518 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91001,7 +94600,7 @@ HARError.prototype = Error.prototype; module.exports = exports['default']; /***/ }), -/* 503 */ +/* 519 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -91030,15 +94629,15 @@ exports.request = request; exports.response = response; exports.timings = timings; -var _harSchema = __webpack_require__(493); +var _harSchema = __webpack_require__(509); var schemas = _interopRequireWildcard(_harSchema); -var _ajv = __webpack_require__(284); +var _ajv = __webpack_require__(339); var _ajv2 = _interopRequireDefault(_ajv); -var _error = __webpack_require__(502); +var _error = __webpack_require__(518); var _error2 = _interopRequireDefault(_error); @@ -91139,27 +94738,27 @@ function timings(data) { } /***/ }), -/* 504 */ +/* 520 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var ansiRegex = __webpack_require__(181); +var ansiRegex = __webpack_require__(245); var re = new RegExp(ansiRegex().source); // remove the `g` flag module.exports = re.test.bind(re); /***/ }), -/* 505 */ +/* 521 */ /***/ (function(module, exports, __webpack_require__) { // Load modules -var Url = __webpack_require__(11); -var Hoek = __webpack_require__(95); -var Cryptiles = __webpack_require__(226); -var Crypto = __webpack_require__(151); -var Utils = __webpack_require__(94); +var Url = __webpack_require__(14); +var Hoek = __webpack_require__(132); +var Cryptiles = __webpack_require__(282); +var Crypto = __webpack_require__(209); +var Utils = __webpack_require__(131); // Declare internals @@ -91525,18 +95124,18 @@ exports.message = function (host, port, message, options) { /***/ }), -/* 506 */ +/* 522 */ /***/ (function(module, exports, __webpack_require__) { // Export sub-modules -exports.error = exports.Error = __webpack_require__(87); -exports.sntp = __webpack_require__(262); +exports.error = exports.Error = __webpack_require__(124); +exports.sntp = __webpack_require__(315); -exports.server = __webpack_require__(507); -exports.client = __webpack_require__(505); -exports.crypto = __webpack_require__(151); -exports.utils = __webpack_require__(94); +exports.server = __webpack_require__(523); +exports.client = __webpack_require__(521); +exports.crypto = __webpack_require__(209); +exports.utils = __webpack_require__(131); exports.uri = { authenticate: exports.server.authenticateBewit, @@ -91546,16 +95145,16 @@ exports.uri = { /***/ }), -/* 507 */ +/* 523 */ /***/ (function(module, exports, __webpack_require__) { // Load modules -var Boom = __webpack_require__(87); -var Hoek = __webpack_require__(95); -var Cryptiles = __webpack_require__(226); -var Crypto = __webpack_require__(151); -var Utils = __webpack_require__(94); +var Boom = __webpack_require__(124); +var Hoek = __webpack_require__(132); +var Cryptiles = __webpack_require__(282); +var Crypto = __webpack_require__(209); +var Utils = __webpack_require__(131); // Declare internals @@ -92100,7 +95699,7 @@ internals.nonceFunc = function (key, nonce, ts, nonceCallback) { /***/ }), -/* 508 */ +/* 524 */ /***/ (function(module, exports) { module.exports = { @@ -92139,7 +95738,7 @@ module.exports = { }; /***/ }), -/* 509 */ +/* 525 */ /***/ (function(module, exports) { // Declare internals @@ -92277,15 +95876,15 @@ internals.safeCharCodes = (function () { /***/ }), -/* 510 */ +/* 526 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2015 Joyent, Inc. -var parser = __webpack_require__(511); -var signer = __webpack_require__(512); -var verify = __webpack_require__(513); -var utils = __webpack_require__(96); +var parser = __webpack_require__(527); +var signer = __webpack_require__(528); +var verify = __webpack_require__(529); +var utils = __webpack_require__(133); @@ -92312,14 +95911,14 @@ module.exports = { /***/ }), -/* 511 */ +/* 527 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2012 Joyent, Inc. All rights reserved. -var assert = __webpack_require__(97); +var assert = __webpack_require__(134); var util = __webpack_require__(2); -var utils = __webpack_require__(96); +var utils = __webpack_require__(133); @@ -92636,18 +96235,18 @@ module.exports = { /***/ }), -/* 512 */ +/* 528 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2012 Joyent, Inc. All rights reserved. -var assert = __webpack_require__(97); -var crypto = __webpack_require__(7); -var http = __webpack_require__(50); +var assert = __webpack_require__(134); +var crypto = __webpack_require__(8); +var http = __webpack_require__(49); var util = __webpack_require__(2); -var sshpk = __webpack_require__(165); -var jsprim = __webpack_require__(551); -var utils = __webpack_require__(96); +var sshpk = __webpack_require__(226); +var jsprim = __webpack_require__(566); +var utils = __webpack_require__(133); var sprintf = __webpack_require__(2).format; @@ -93041,15 +96640,15 @@ module.exports = { /***/ }), -/* 513 */ +/* 529 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2015 Joyent, Inc. -var assert = __webpack_require__(97); -var crypto = __webpack_require__(7); -var sshpk = __webpack_require__(165); -var utils = __webpack_require__(96); +var assert = __webpack_require__(134); +var crypto = __webpack_require__(8); +var sshpk = __webpack_require__(226); +var utils = __webpack_require__(133); var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; @@ -93135,96 +96734,7 @@ module.exports = { /***/ }), -/* 514 */ -/***/ (function(module, exports, __webpack_require__) { - -var wrappy = __webpack_require__(167) -var reqs = Object.create(null) -var once = __webpack_require__(104) - -module.exports = wrappy(inflight) - -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} - -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) - - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) -} - -function slice (args) { - var length = args.length - var array = [] - - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} - - -/***/ }), -/* 515 */ -/***/ (function(module, exports) { - -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - - -/***/ }), -/* 516 */ +/* 530 */ /***/ (function(module, exports) { @@ -93420,12 +96930,12 @@ function unsafe (val, doUnesc) { /***/ }), -/* 517 */ +/* 531 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _ = __webpack_require__(21); +var _ = __webpack_require__(28); /** * Choice object @@ -93462,15 +96972,15 @@ var Choice = module.exports = function (val, answers) { /***/ }), -/* 518 */ +/* 532 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var assert = __webpack_require__(22); -var _ = __webpack_require__(21); -var Separator = __webpack_require__(98); -var Choice = __webpack_require__(517); +var assert = __webpack_require__(18); +var _ = __webpack_require__(28); +var Separator = __webpack_require__(135); +var Choice = __webpack_require__(531); /** * Choices collection @@ -93581,21 +97091,21 @@ Choices.prototype.push = function () { /***/ }), -/* 519 */ +/* 533 */ /***/ (function(module, exports, __webpack_require__) { /** * `list` type prompt */ -var _ = __webpack_require__(21); +var _ = __webpack_require__(28); var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var cliCursor = __webpack_require__(211); -var figures = __webpack_require__(149); -var Base = __webpack_require__(38); -var observe = __webpack_require__(39); -var Paginator = __webpack_require__(99); +var chalk = __webpack_require__(20); +var cliCursor = __webpack_require__(279); +var figures = __webpack_require__(206); +var Base = __webpack_require__(54); +var observe = __webpack_require__(55); +var Paginator = __webpack_require__(136); /** * Module exports @@ -93823,18 +97333,18 @@ function getCheckbox(checked) { /***/ }), -/* 520 */ +/* 534 */ /***/ (function(module, exports, __webpack_require__) { /** * `confirm` type prompt */ -var _ = __webpack_require__(21); +var _ = __webpack_require__(28); var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var Base = __webpack_require__(38); -var observe = __webpack_require__(39); +var chalk = __webpack_require__(20); +var Base = __webpack_require__(54); +var observe = __webpack_require__(55); /** * Module exports @@ -93935,7 +97445,7 @@ Prompt.prototype.onKeypress = function () { /***/ }), -/* 521 */ +/* 535 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -93943,11 +97453,11 @@ Prompt.prototype.onKeypress = function () { */ var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var ExternalEditor = __webpack_require__(466); -var Base = __webpack_require__(38); -var observe = __webpack_require__(39); -var rx = __webpack_require__(106); +var chalk = __webpack_require__(20); +var ExternalEditor = __webpack_require__(484); +var Base = __webpack_require__(54); +var observe = __webpack_require__(55); +var rx = __webpack_require__(142); /** * Module exports @@ -94052,20 +97562,20 @@ Prompt.prototype.onError = function (state) { /***/ }), -/* 522 */ +/* 536 */ /***/ (function(module, exports, __webpack_require__) { /** * `rawlist` type prompt */ -var _ = __webpack_require__(21); +var _ = __webpack_require__(28); var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var Base = __webpack_require__(38); -var Separator = __webpack_require__(98); -var observe = __webpack_require__(39); -var Paginator = __webpack_require__(99); +var chalk = __webpack_require__(20); +var Base = __webpack_require__(54); +var Separator = __webpack_require__(135); +var observe = __webpack_require__(55); +var Paginator = __webpack_require__(136); /** * Module exports @@ -94318,7 +97828,7 @@ function renderChoices(choices, pointer) { /***/ }), -/* 523 */ +/* 537 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94326,9 +97836,9 @@ function renderChoices(choices, pointer) { */ var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var Base = __webpack_require__(38); -var observe = __webpack_require__(39); +var chalk = __webpack_require__(20); +var Base = __webpack_require__(54); +var observe = __webpack_require__(55); /** * Module exports @@ -94428,22 +97938,22 @@ Prompt.prototype.onKeypress = function () { /***/ }), -/* 524 */ +/* 538 */ /***/ (function(module, exports, __webpack_require__) { /** * `list` type prompt */ -var _ = __webpack_require__(21); +var _ = __webpack_require__(28); var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var figures = __webpack_require__(149); -var cliCursor = __webpack_require__(211); -var runAsync = __webpack_require__(105); -var Base = __webpack_require__(38); -var observe = __webpack_require__(39); -var Paginator = __webpack_require__(99); +var chalk = __webpack_require__(20); +var figures = __webpack_require__(206); +var cliCursor = __webpack_require__(279); +var runAsync = __webpack_require__(141); +var Base = __webpack_require__(54); +var observe = __webpack_require__(55); +var Paginator = __webpack_require__(136); /** * Module exports @@ -94621,7 +98131,7 @@ function listRender(choices, pointer) { /***/ }), -/* 525 */ +/* 539 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94629,9 +98139,9 @@ function listRender(choices, pointer) { */ var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var Base = __webpack_require__(38); -var observe = __webpack_require__(39); +var chalk = __webpack_require__(20); +var Base = __webpack_require__(54); +var observe = __webpack_require__(55); function mask(input) { input = String(input); @@ -94742,20 +98252,20 @@ Prompt.prototype.onKeypress = function () { /***/ }), -/* 526 */ +/* 540 */ /***/ (function(module, exports, __webpack_require__) { /** * `rawlist` type prompt */ -var _ = __webpack_require__(21); +var _ = __webpack_require__(28); var util = __webpack_require__(2); -var chalk = __webpack_require__(15); -var Base = __webpack_require__(38); -var Separator = __webpack_require__(98); -var observe = __webpack_require__(39); -var Paginator = __webpack_require__(99); +var chalk = __webpack_require__(20); +var Base = __webpack_require__(54); +var Separator = __webpack_require__(135); +var observe = __webpack_require__(55); +var Paginator = __webpack_require__(136); /** * Module exports @@ -94927,7 +98437,7 @@ function renderChoices(choices, pointer) { /***/ }), -/* 527 */ +/* 541 */ /***/ (function(module, exports, __webpack_require__) { /** @@ -94935,10 +98445,10 @@ function renderChoices(choices, pointer) { */ var util = __webpack_require__(2); -var through = __webpack_require__(625); -var Base = __webpack_require__(237); -var rlUtils = __webpack_require__(238); -var _ = __webpack_require__(21); +var through = __webpack_require__(641); +var Base = __webpack_require__(290); +var rlUtils = __webpack_require__(291); +var _ = __webpack_require__(28); /** * Module exports @@ -95038,17 +98548,17 @@ Prompt.prototype.write = function (message) { /***/ }), -/* 528 */ +/* 542 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _ = __webpack_require__(21); -var rx = __webpack_require__(106); +var _ = __webpack_require__(28); +var rx = __webpack_require__(142); var util = __webpack_require__(2); -var runAsync = __webpack_require__(105); -var utils = __webpack_require__(530); -var Base = __webpack_require__(237); +var runAsync = __webpack_require__(141); +var utils = __webpack_require__(544); +var Base = __webpack_require__(290); /** * Base interface class other can inherits from @@ -95160,16 +98670,16 @@ PromptUI.prototype.filterIfRunnable = function (question) { /***/ }), -/* 529 */ +/* 543 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _ = __webpack_require__(21); -var util = __webpack_require__(238); -var cliWidth = __webpack_require__(409); -var stripAnsi = __webpack_require__(166); -var stringWidth = __webpack_require__(532); +var _ = __webpack_require__(28); +var util = __webpack_require__(291); +var cliWidth = __webpack_require__(457); +var stripAnsi = __webpack_require__(227); +var stringWidth = __webpack_require__(546); function height(content) { return content.split('\n').length; @@ -95302,14 +98812,14 @@ function forceLineReturn(content, width) { /***/ }), -/* 530 */ +/* 544 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var _ = __webpack_require__(21); -var rx = __webpack_require__(106); -var runAsync = __webpack_require__(105); +var _ = __webpack_require__(28); +var rx = __webpack_require__(142); +var runAsync = __webpack_require__(141); /** * Resolve a question property value if it is passed as a function. @@ -95335,7 +98845,7 @@ exports.fetchAsyncQuestionProperty = function (question, prop, answers) { /***/ }), -/* 531 */ +/* 545 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95388,13 +98898,13 @@ module.exports = x => { /***/ }), -/* 532 */ +/* 546 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const stripAnsi = __webpack_require__(166); -const isFullwidthCodePoint = __webpack_require__(531); +const stripAnsi = __webpack_require__(227); +const isFullwidthCodePoint = __webpack_require__(545); module.exports = str => { if (typeof str !== 'string' || str.length === 0) { @@ -95430,7 +98940,7 @@ module.exports = str => { /***/ }), -/* 533 */ +/* 547 */ /***/ (function(module, exports) { /*! @@ -95457,12 +98967,12 @@ function isSlowBuffer (obj) { /***/ }), -/* 534 */ +/* 548 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var builtinModules = __webpack_require__(403); +var builtinModules = __webpack_require__(452); module.exports = function (str) { if (typeof str !== 'string') { @@ -95474,7 +98984,7 @@ module.exports = function (str) { /***/ }), -/* 535 */ +/* 549 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95487,7 +98997,7 @@ module.exports = function (buf) { /***/ }), -/* 536 */ +/* 550 */ /***/ (function(module, exports) { /*! @@ -95508,7 +99018,7 @@ module.exports = function(str) { /***/ }), -/* 537 */ +/* 551 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95521,7 +99031,7 @@ module.exports = function(str) { -var isPrimitive = __webpack_require__(240); +var isPrimitive = __webpack_require__(293); module.exports = function isEqual(a, b) { if (!a && !b) { return true; } @@ -95542,7 +99052,7 @@ module.exports = function isEqual(a, b) { /***/ }), -/* 538 */ +/* 552 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95562,7 +99072,7 @@ module.exports = function isExtendable(val) { /***/ }), -/* 539 */ +/* 553 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95585,7 +99095,21 @@ module.exports = function (buf) { /***/ }), -/* 540 */ +/* 554 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var toString = Object.prototype.toString; + +module.exports = function (x) { + var prototype; + return toString.call(x) === '[object Object]' && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); +}; + + +/***/ }), +/* 555 */ /***/ (function(module, exports) { /*! @@ -95601,7 +99125,7 @@ module.exports = function isPosixBracket(str) { /***/ }), -/* 541 */ +/* 556 */ /***/ (function(module, exports) { module.exports = isPromise; @@ -95612,7 +99136,7 @@ function isPromise(obj) { /***/ }), -/* 542 */ +/* 557 */ /***/ (function(module, exports) { module.exports = isTypedArray @@ -95659,7 +99183,7 @@ function isLooseTypedArray(arr) { /***/ }), -/* 543 */ +/* 558 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95672,7 +99196,7 @@ function isLooseTypedArray(arr) { -var isArray = __webpack_require__(241); +var isArray = __webpack_require__(294); module.exports = function isObject(val) { return val != null && typeof val === 'object' && isArray(val) === false; @@ -95680,7 +99204,7 @@ module.exports = function isObject(val) { /***/ }), -/* 544 */ +/* 559 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95699,9 +99223,9 @@ module.exports = function isObject(val) { * You should have received a copy of the license along with this program. */ -var core = __webpack_require__(102); -var utils = __webpack_require__(103); -var curve255 = __webpack_require__(155); +var core = __webpack_require__(139); +var utils = __webpack_require__(140); +var curve255 = __webpack_require__(216); /** @@ -95798,7 +99322,7 @@ module.exports = ns; /***/ }), -/* 545 */ +/* 560 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -95818,11 +99342,11 @@ module.exports = ns; * You should have received a copy of the license along with this program. */ -var core = __webpack_require__(102); -var curve255 = __webpack_require__(155); -var utils = __webpack_require__(103); -var BigInteger = __webpack_require__(40).BigInteger; -var crypto = __webpack_require__(7); +var core = __webpack_require__(139); +var curve255 = __webpack_require__(216); +var utils = __webpack_require__(140); +var BigInteger = __webpack_require__(56).BigInteger; +var crypto = __webpack_require__(8); /** * @exports jodid25519/eddsa @@ -96378,7 +99902,7 @@ module.exports = ns; /***/ }), -/* 546 */ +/* 561 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/** @@ -96658,7 +100182,7 @@ return exports; /***/ }), -/* 547 */ +/* 562 */ /***/ (function(module, exports) { exports = module.exports = stringify @@ -96691,15 +100215,15 @@ function serializer(replacer, cycleReplacer) { /***/ }), -/* 548 */ +/* 563 */ /***/ (function(module, exports, __webpack_require__) { -exports.parse = __webpack_require__(549); -exports.stringify = __webpack_require__(550); +exports.parse = __webpack_require__(564); +exports.stringify = __webpack_require__(565); /***/ }), -/* 549 */ +/* 564 */ /***/ (function(module, exports) { var at, // The index of the current character @@ -96978,7 +100502,7 @@ module.exports = function (source, reviver) { /***/ }), -/* 550 */ +/* 565 */ /***/ (function(module, exports) { var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, @@ -97138,19 +100662,19 @@ module.exports = function (value, replacer, space) { /***/ }), -/* 551 */ +/* 566 */ /***/ (function(module, exports, __webpack_require__) { /* * lib/jsprim.js: utilities for primitive JavaScript types */ -var mod_assert = __webpack_require__(9); +var mod_assert = __webpack_require__(11); var mod_util = __webpack_require__(2); -var mod_extsprintf = __webpack_require__(232); -var mod_verror = __webpack_require__(635); -var mod_jsonschema = __webpack_require__(546); +var mod_extsprintf = __webpack_require__(287); +var mod_verror = __webpack_require__(651); +var mod_jsonschema = __webpack_require__(561); /* * Public interface @@ -97879,7 +101403,7 @@ function mergeObjects(provided, overrides, defaults) /***/ }), -/* 552 */ +/* 567 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -97971,50 +101495,7 @@ module.exports = function (a, b) { /***/ }), -/* 553 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -var util = __webpack_require__(2); -var onExit = __webpack_require__(261); -var currentlyUnhandled = __webpack_require__(450); - -var installed = false; - -module.exports = function (log) { - if (installed) { - return; - } - - installed = true; - - log = log || console.error; - - var listUnhandled = currentlyUnhandled(); - - onExit(function () { - var unhandledRejections = listUnhandled(); - - if (unhandledRejections.length > 0) { - unhandledRejections.forEach(function (x) { - var err = x.reason; - - if (!(err instanceof Error)) { - err = new Error('Promise rejected with value: ' + util.inspect(err)); - } - - log(err.stack); - }); - - process.exitCode = 1; - } - }); -}; - - -/***/ }), -/* 554 */ +/* 568 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -98088,7 +101569,7 @@ module.exports = chars; /***/ }), -/* 555 */ +/* 569 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -98101,8 +101582,8 @@ module.exports = chars; -var utils = __webpack_require__(158); -var Glob = __webpack_require__(556); +var utils = __webpack_require__(220); +var Glob = __webpack_require__(570); /** * Expose `expand` @@ -98399,14 +101880,14 @@ function globstar(dotfile) { /***/ }), -/* 556 */ +/* 570 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var chars = __webpack_require__(554); -var utils = __webpack_require__(158); +var chars = __webpack_require__(568); +var utils = __webpack_require__(220); /** * Expose `Glob` @@ -98599,7 +102080,7 @@ function unesc(str) { /***/ }), -/* 557 */ +/* 571 */ /***/ (function(module, exports) { module.exports = { @@ -107300,7 +110781,7 @@ module.exports = { }; /***/ }), -/* 558 */ +/* 572 */ /***/ (function(module, exports, __webpack_require__) { /*! @@ -107313,11 +110794,11 @@ module.exports = { * Module exports. */ -module.exports = __webpack_require__(557) +module.exports = __webpack_require__(571) /***/ }), -/* 559 */ +/* 573 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -107331,169 +110812,11 @@ module.exports = (to, from) => { /***/ }), -/* 560 */ -/***/ (function(module, exports) { - -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - - -/***/ }), -/* 561 */ +/* 574 */ /***/ (function(module, exports, __webpack_require__) { /*jslint node: true*/ -__webpack_require__(621); +__webpack_require__(637); "use strict"; @@ -107526,7 +110849,7 @@ var trim = function(str) { * Emoji namespace */ var Emoji = module.exports = { - emoji: __webpack_require__(562) + emoji: __webpack_require__(575) }; /** @@ -107623,7 +110946,7 @@ Emoji.search = function search(str) { /***/ }), -/* 562 */ +/* 575 */ /***/ (function(module, exports) { module.exports = { @@ -108971,7 +112294,7 @@ module.exports = { }; /***/ }), -/* 563 */ +/* 576 */ /***/ (function(module, exports, __webpack_require__) { /*! @@ -108981,7 +112304,7 @@ module.exports = { * Released under the MIT License. */ -var removeTrailingSeparator = __webpack_require__(584); +var removeTrailingSeparator = __webpack_require__(599); module.exports = function normalizePath(str, stripTrailing) { if (typeof str !== 'string') { @@ -108996,11 +112319,179 @@ module.exports = function normalizePath(str, stripTrailing) { /***/ }), -/* 564 */ +/* 577 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var url = __webpack_require__(14); +var punycode = __webpack_require__(228); +var queryString = __webpack_require__(591); +var prependHttp = __webpack_require__(585); +var sortKeys = __webpack_require__(628); +var objectAssign = __webpack_require__(299); + +var DEFAULT_PORTS = { + 'http:': 80, + 'https:': 443, + 'ftp:': 21 +}; + +// protocols that always contain a `//`` bit +var slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true +}; + +function testParameter(name, filters) { + return filters.some(function (filter) { + return filter instanceof RegExp ? filter.test(name) : filter === name; + }); +} + +module.exports = function (str, opts) { + opts = objectAssign({ + normalizeProtocol: true, + normalizeHttps: false, + stripFragment: true, + stripWWW: true, + removeQueryParameters: [/^utm_\w+/i], + removeTrailingSlash: true, + removeDirectoryIndex: false + }, opts); + + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + var hasRelativeProtocol = str.indexOf('//') === 0; + + // prepend protocol + str = prependHttp(str.trim()).replace(/^\/\//, 'http://'); + + var urlObj = url.parse(str); + + if (opts.normalizeHttps && urlObj.protocol === 'https:') { + urlObj.protocol = 'http:'; + } + + if (!urlObj.hostname && !urlObj.pathname) { + throw new Error('Invalid URL'); + } + + // prevent these from being used by `url.format` + delete urlObj.host; + delete urlObj.query; + + // remove fragment + if (opts.stripFragment) { + delete urlObj.hash; + } + + // remove default port + var port = DEFAULT_PORTS[urlObj.protocol]; + if (Number(urlObj.port) === port) { + delete urlObj.port; + } + + // remove duplicate slashes + if (urlObj.pathname) { + urlObj.pathname = urlObj.pathname.replace(/\/{2,}/g, '/'); + } + + // decode URI octets + if (urlObj.pathname) { + urlObj.pathname = decodeURI(urlObj.pathname); + } + + // remove directory index + if (opts.removeDirectoryIndex === true) { + opts.removeDirectoryIndex = [/^index\.[a-z]+$/]; + } + + if (Array.isArray(opts.removeDirectoryIndex) && opts.removeDirectoryIndex.length) { + var pathComponents = urlObj.pathname.split('/'); + var lastComponent = pathComponents[pathComponents.length - 1]; + + if (testParameter(lastComponent, opts.removeDirectoryIndex)) { + pathComponents = pathComponents.slice(0, pathComponents.length - 1); + urlObj.pathname = pathComponents.slice(1).join('/') + '/'; + } + } + + // resolve relative paths, but only for slashed protocols + if (slashedProtocol[urlObj.protocol]) { + var domain = urlObj.protocol + '//' + urlObj.hostname; + var relative = url.resolve(domain, urlObj.pathname); + urlObj.pathname = relative.replace(domain, ''); + } + + if (urlObj.hostname) { + // IDN to Unicode + urlObj.hostname = punycode.toUnicode(urlObj.hostname).toLowerCase(); + + // remove trailing dot + urlObj.hostname = urlObj.hostname.replace(/\.$/, ''); + + // remove `www.` + if (opts.stripWWW) { + urlObj.hostname = urlObj.hostname.replace(/^www\./, ''); + } + } + + // remove URL with empty query string + if (urlObj.search === '?') { + delete urlObj.search; + } + + var queryParameters = queryString.parse(urlObj.search); + + // remove query unwanted parameters + if (Array.isArray(opts.removeQueryParameters)) { + for (var key in queryParameters) { + if (testParameter(key, opts.removeQueryParameters)) { + delete queryParameters[key]; + } + } + } + + // sort query parameters + urlObj.search = queryString.stringify(sortKeys(queryParameters)); + + // decode query parameters + urlObj.search = decodeURIComponent(urlObj.search); + + // take advantage of many of the Node `url` normalizations + str = url.format(urlObj); + + // remove ending `/` + if (opts.removeTrailingSlash || urlObj.pathname === '/') { + str = str.replace(/\/$/, ''); + } + + // restore relative protocol, if applicable + if (hasRelativeProtocol && !opts.normalizeProtocol) { + str = str.replace(/^http:\/\//, '//'); + } + + return str; +}; + + +/***/ }), +/* 578 */ /***/ (function(module, exports, __webpack_require__) { -var crypto = __webpack_require__(7) - , qs = __webpack_require__(114) +var crypto = __webpack_require__(8) + , qs = __webpack_require__(150) ; function sha1 (key, body) { @@ -109138,7 +112629,7 @@ exports.generateBase = generateBase /***/ }), -/* 565 */ +/* 579 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -109151,8 +112642,8 @@ exports.generateBase = generateBase -var isObject = __webpack_require__(538); -var forOwn = __webpack_require__(471); +var isObject = __webpack_require__(552); +var forOwn = __webpack_require__(489); module.exports = function omit(obj, keys) { if (!isObject(obj)) return {}; @@ -109185,12 +112676,12 @@ module.exports = function omit(obj, keys) { /***/ }), -/* 566 */ +/* 580 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const mimicFn = __webpack_require__(559); +const mimicFn = __webpack_require__(573); module.exports = (fn, opts) => { // TODO: Remove this in v3 @@ -109231,7 +112722,7 @@ module.exports = (fn, opts) => { /***/ }), -/* 567 */ +/* 581 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -109263,7 +112754,7 @@ module.exports = function () { /***/ }), -/* 568 */ +/* 582 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -109276,10 +112767,10 @@ module.exports = function () { -var isGlob = __webpack_require__(101); -var findBase = __webpack_require__(476); -var extglob = __webpack_require__(100); -var dotfile = __webpack_require__(536); +var isGlob = __webpack_require__(138); +var findBase = __webpack_require__(493); +var extglob = __webpack_require__(137); +var dotfile = __webpack_require__(550); /** * Expose `cache` @@ -109380,619 +112871,253 @@ module.exports = function parseGlob(glob) { function dotdir(base) { if (base.indexOf('/.') !== -1) { return true; - } - if (base.charAt(0) === '.' && base.charAt(1) !== '/') { - return true; - } - return false; -} - -/** - * Returns true if the pattern has the given `ch`aracter(s) - * - * @param {Object} `glob` The glob pattern. - * @param {Object} `ch` The character to test for - * @return {Object} - */ - -function has(is, glob, ch) { - return is && glob.indexOf(ch) !== -1; -} - -/** - * Escape/unescape utils - */ - -function escape(str) { - var re = /\{([^{}]*?)}|\(([^()]*?)\)|\[([^\[\]]*?)\]/g; - return str.replace(re, function (outter, braces, parens, brackets) { - var inner = braces || parens || brackets; - if (!inner) { return outter; } - return outter.split(inner).join(esc(inner)); - }); -} - -function esc(str) { - str = str.split('/').join('__SLASH__'); - str = str.split('.').join('__DOT__'); - return str; -} - -function unescape(str) { - str = str.split('__SLASH__').join('/'); - str = str.split('__DOT__').join('.'); - return str; -} - - -/***/ }), -/* 569 */ -/***/ (function(module, exports, __webpack_require__) { - -var duplexify = __webpack_require__(228) -var through = __webpack_require__(271) - -var noop = function() {} - -var isObject = function(data) { - return !Buffer.isBuffer(data) && typeof data !== 'string' -} - -var peek = function(opts, onpeek) { - if (typeof opts === 'number') opts = {maxBuffer:opts} - if (typeof opts === 'function') return peek(null, opts) - if (!opts) opts = {} - - var maxBuffer = typeof opts.maxBuffer === 'number' ? opts.maxBuffer : 65535 - var strict = opts.strict - var newline = opts.newline !== false - - var buffer = [] - var bufferSize = 0 - var dup = duplexify.obj() - - var peeker = through.obj({highWaterMark:1}, function(data, enc, cb) { - if (isObject(data)) return ready(data, null, cb) - if (!Buffer.isBuffer(data)) data = new Buffer(data) - - if (newline) { - var nl = Array.prototype.indexOf.call(data, 10) - if (nl > 0 && data[nl-1] === 13) nl-- - - if (nl > -1) { - buffer.push(data.slice(0, nl)) - return ready(Buffer.concat(buffer), data.slice(nl), cb) - } - } - - buffer.push(data) - bufferSize += data.length - - if (bufferSize < maxBuffer) return cb() - if (strict) return cb(new Error('No newline found')) - ready(Buffer.concat(buffer), null, cb) - }) - - var onpreend = function() { - if (strict) return dup.destroy(new Error('No newline found')) - dup.cork() - ready(Buffer.concat(buffer), null, function(err) { - if (err) return dup.destroy(err) - dup.uncork() - }) - } - - var ready = function(data, overflow, cb) { - dup.removeListener('preend', onpreend) - onpeek(data, function(err, parser) { - if (err) return cb(err) - - dup.setWritable(parser) - dup.setReadable(parser) - - if (data) parser.write(data) - if (overflow) parser.write(overflow) - - overflow = buffer = peeker = null // free the data - cb() - }) - } - - dup.on('preend', onpreend) - dup.setWritable(peeker) - - return dup -} - -module.exports = peek - -/***/ }), -/* 570 */ -/***/ (function(module, exports) { - -// Generated by CoffeeScript 1.7.1 -(function() { - var getNanoSeconds, hrtime, loadTime; - - if ((typeof performance !== "undefined" && performance !== null) && performance.now) { - module.exports = function() { - return performance.now(); - }; - } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { - module.exports = function() { - return (getNanoSeconds() - loadTime) / 1e6; - }; - hrtime = process.hrtime; - getNanoSeconds = function() { - var hr; - hr = hrtime(); - return hr[0] * 1e9 + hr[1]; - }; - loadTime = getNanoSeconds(); - } else if (Date.now) { - module.exports = function() { - return Date.now() - loadTime; - }; - loadTime = Date.now(); - } else { - module.exports = function() { - return new Date().getTime() - loadTime; - }; - loadTime = new Date().getTime(); - } - -}).call(this); - - -/***/ }), -/* 571 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/*! - * preserve <https://github.com/jonschlinkert/preserve> - * - * Copyright (c) 2014-2015, Jon Schlinkert. - * Licensed under the MIT license. - */ - - - -/** - * Replace tokens in `str` with a temporary, heuristic placeholder. - * - * ```js - * tokens.before('{a\\,b}'); - * //=> '{__ID1__}' - * ``` - * - * @param {String} `str` - * @return {String} String with placeholders. - * @api public - */ - -exports.before = function before(str, re) { - return str.replace(re, function (match) { - var id = randomize(); - cache[id] = match; - return '__ID' + id + '__'; - }); -}; - -/** - * Replace placeholders in `str` with original tokens. - * - * ```js - * tokens.after('{__ID1__}'); - * //=> '{a\\,b}' - * ``` - * - * @param {String} `str` String with placeholders - * @return {String} `str` String with original tokens. - * @api public - */ - -exports.after = function after(str) { - return str.replace(/__ID(.{5})__/g, function (_, id) { - return cache[id]; - }); -}; - -function randomize() { - return Math.random().toString().slice(2, 7); -} - -var cache = {}; - -/***/ }), -/* 572 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -const fs = __webpack_require__(236); -const path = __webpack_require__(1); -const retry = __webpack_require__(599); -const syncFs = __webpack_require__(573); - -const locks = {}; - -function getLockFile(file) { - return `${file}.lock`; -} - -function canonicalPath(file, options, callback) { - if (!options.realpath) { - return callback(null, path.resolve(file)); - } - - // Use realpath to resolve symlinks - // It also resolves relative paths - options.fs.realpath(file, callback); -} - -function acquireLock(file, options, callback) { - // Use mkdir to create the lockfile (atomic operation) - options.fs.mkdir(getLockFile(file), (err) => { - // If successful, we are done - if (!err) { - return callback(); - } - - // If error is not EEXIST then some other error occurred while locking - if (err.code !== 'EEXIST') { - return callback(err); - } - - // Otherwise, check if lock is stale by analyzing the file mtime - if (options.stale <= 0) { - return callback(Object.assign(new Error('Lock file is already being hold'), { code: 'ELOCKED', file })); - } - - options.fs.stat(getLockFile(file), (err, stat) => { - if (err) { - // Retry if the lockfile has been removed (meanwhile) - // Skip stale check to avoid recursiveness - if (err.code === 'ENOENT') { - return acquireLock(file, Object.assign({}, options, { stale: 0 }), callback); - } - - return callback(err); - } - - if (!isLockStale(stat, options)) { - return callback(Object.assign(new Error('Lock file is already being hold'), { code: 'ELOCKED', file })); - } - - // If it's stale, remove it and try again! - // Skip stale check to avoid recursiveness - removeLock(file, options, (err) => { - if (err) { - return callback(err); - } - - acquireLock(file, Object.assign({}, options, { stale: 0 }), callback); - }); - }); - }); -} - -function isLockStale(stat, options) { - return stat.mtime.getTime() < Date.now() - options.stale; -} - -function removeLock(file, options, callback) { - // Remove lockfile, ignoring ENOENT errors - options.fs.rmdir(getLockFile(file), (err) => { - if (err && err.code !== 'ENOENT') { - return callback(err); - } - - callback(); - }); -} - -function updateLock(file, options) { - const lock = locks[file]; - - /* istanbul ignore next */ - if (lock.updateTimeout) { - return; - } - - lock.updateDelay = lock.updateDelay || options.update; - lock.updateTimeout = setTimeout(() => { - const mtime = Date.now() / 1000; - - lock.updateTimeout = null; - - options.fs.utimes(getLockFile(file), mtime, mtime, (err) => { - // Ignore if the lock was released - if (lock.released) { - return; - } - - // Verify if we are within the stale threshold - if (lock.lastUpdate <= Date.now() - options.stale && - lock.lastUpdate > Date.now() - options.stale * 2) { - return compromisedLock(file, lock, Object.assign(new Error(lock.updateError || 'Unable to update lock within the stale \ -threshold'), { code: 'ECOMPROMISED' })); - } - - // If the file is older than (stale * 2), we assume the clock is moved manually, - // which we consider a valid case - - // If it failed to update the lockfile, keep trying unless - // the lockfile was deleted! - if (err) { - if (err.code === 'ENOENT') { - return compromisedLock(file, lock, Object.assign(err, { code: 'ECOMPROMISED' })); - } - - lock.updateError = err; - lock.updateDelay = 1000; - return updateLock(file, options); - } - - // All ok, keep updating.. - lock.lastUpdate = Date.now(); - lock.updateError = null; - lock.updateDelay = null; - updateLock(file, options); - }); - }, lock.updateDelay); + } + if (base.charAt(0) === '.' && base.charAt(1) !== '/') { + return true; + } + return false; +} - // Unref the timer so that the nodejs process can exit freely - // This is safe because all acquired locks will be automatically released - // on process exit +/** + * Returns true if the pattern has the given `ch`aracter(s) + * + * @param {Object} `glob` The glob pattern. + * @param {Object} `ch` The character to test for + * @return {Object} + */ - // We first check that `lock.updateTimeout.unref` exists because some users - // may be using this module outside of NodeJS (e.g., in an electron app), - // and in those cases `setTimeout` return an integer. - if (lock.updateTimeout.unref) { - lock.updateTimeout.unref(); - } +function has(is, glob, ch) { + return is && glob.indexOf(ch) !== -1; } -function compromisedLock(file, lock, err) { - lock.released = true; // Signal the lock has been released - /* istanbul ignore next */ - lock.updateTimeout && clearTimeout(lock.updateTimeout); // Cancel lock mtime update +/** + * Escape/unescape utils + */ - if (locks[file] === lock) { - delete locks[file]; - } +function escape(str) { + var re = /\{([^{}]*?)}|\(([^()]*?)\)|\[([^\[\]]*?)\]/g; + return str.replace(re, function (outter, braces, parens, brackets) { + var inner = braces || parens || brackets; + if (!inner) { return outter; } + return outter.split(inner).join(esc(inner)); + }); +} - lock.compromised(err); +function esc(str) { + str = str.split('/').join('__SLASH__'); + str = str.split('.').join('__DOT__'); + return str; } -// ----------------------------------------- +function unescape(str) { + str = str.split('__SLASH__').join('/'); + str = str.split('__DOT__').join('.'); + return str; +} -function lock(file, options, compromised, callback) { - if (typeof options === 'function') { - callback = compromised; - compromised = options; - options = null; - } - if (!callback) { - callback = compromised; - compromised = null; - } +/***/ }), +/* 583 */ +/***/ (function(module, exports, __webpack_require__) { - options = Object.assign({ - stale: 10000, - update: null, - realpath: true, - retries: 0, - fs, - }, options); +var duplexify = __webpack_require__(283) +var through = __webpack_require__(323) - options.retries = options.retries || 0; - options.retries = typeof options.retries === 'number' ? { retries: options.retries } : options.retries; - options.stale = Math.max(options.stale || 0, 2000); - options.update = options.update == null ? options.stale / 2 : options.update || 0; - options.update = Math.max(Math.min(options.update, options.stale / 2), 1000); - compromised = compromised || function (err) { throw err; }; +var noop = function() {} - // Resolve to a canonical file path - canonicalPath(file, options, (err, file) => { - if (err) { - return callback(err); - } +var isObject = function(data) { + return !Buffer.isBuffer(data) && typeof data !== 'string' +} - // Attempt to acquire the lock - const operation = retry.operation(options.retries); +var peek = function(opts, onpeek) { + if (typeof opts === 'number') opts = {maxBuffer:opts} + if (typeof opts === 'function') return peek(null, opts) + if (!opts) opts = {} - operation.attempt(() => { - acquireLock(file, options, (err) => { - if (operation.retry(err)) { - return; - } + var maxBuffer = typeof opts.maxBuffer === 'number' ? opts.maxBuffer : 65535 + var strict = opts.strict + var newline = opts.newline !== false - if (err) { - return callback(operation.mainError()); - } + var buffer = [] + var bufferSize = 0 + var dup = duplexify.obj() - // We now own the lock - const lock = locks[file] = { - options, - compromised, - lastUpdate: Date.now(), - }; + var peeker = through.obj({highWaterMark:1}, function(data, enc, cb) { + if (isObject(data)) return ready(data, null, cb) + if (!Buffer.isBuffer(data)) data = new Buffer(data) - // We must keep the lock fresh to avoid staleness - updateLock(file, options); + if (newline) { + var nl = Array.prototype.indexOf.call(data, 10) + if (nl > 0 && data[nl-1] === 13) nl-- - callback(null, (releasedCallback) => { - if (lock.released) { - return releasedCallback && - releasedCallback(Object.assign(new Error('Lock is already released'), { code: 'ERELEASED' })); - } + if (nl > -1) { + buffer.push(data.slice(0, nl)) + return ready(Buffer.concat(buffer), data.slice(nl), cb) + } + } - // Not necessary to use realpath twice when unlocking - unlock(file, Object.assign({}, options, { realpath: false }), releasedCallback); - }); - }); - }); - }); -} + buffer.push(data) + bufferSize += data.length -function unlock(file, options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } + if (bufferSize < maxBuffer) return cb() + if (strict) return cb(new Error('No newline found')) + ready(Buffer.concat(buffer), null, cb) + }) - options = Object.assign({ - fs, - realpath: true, - }, options); + var onpreend = function() { + if (strict) return dup.destroy(new Error('No newline found')) + dup.cork() + ready(Buffer.concat(buffer), null, function(err) { + if (err) return dup.destroy(err) + dup.uncork() + }) + } - callback = callback || function () {}; + var ready = function(data, overflow, cb) { + dup.removeListener('preend', onpreend) + onpeek(data, function(err, parser) { + if (err) return cb(err) - // Resolve to a canonical file path - canonicalPath(file, options, (err, file) => { - if (err) { - return callback(err); - } + dup.setWritable(parser) + dup.setReadable(parser) - // Skip if the lock is not acquired - const lock = locks[file]; + if (data) parser.write(data) + if (overflow) parser.write(overflow) - if (!lock) { - return callback(Object.assign(new Error('Lock is not acquired/owned by you'), { code: 'ENOTACQUIRED' })); - } + overflow = buffer = peeker = null // free the data + cb() + }) + } - lock.updateTimeout && clearTimeout(lock.updateTimeout); // Cancel lock mtime update - lock.released = true; // Signal the lock has been released - delete locks[file]; // Delete from locks + dup.on('preend', onpreend) + dup.setWritable(peeker) - removeLock(file, options, callback); - }); + return dup } -function lockSync(file, options, compromised) { - if (typeof options === 'function') { - compromised = options; - options = null; - } - - options = options || {}; - options.fs = syncFs(options.fs || fs); - options.retries = options.retries || 0; - options.retries = typeof options.retries === 'number' ? { retries: options.retries } : options.retries; +module.exports = peek - // Retries are not allowed because it requires the flow to be sync - if (options.retries.retries) { - throw Object.assign(new Error('Cannot use retries with the sync api'), { code: 'ESYNC' }); - } +/***/ }), +/* 584 */ +/***/ (function(module, exports) { - let err; - let release; +// Generated by CoffeeScript 1.7.1 +(function() { + var getNanoSeconds, hrtime, loadTime; - lock(file, options, compromised, (_err, _release) => { - err = _err; - release = _release; - }); + if ((typeof performance !== "undefined" && performance !== null) && performance.now) { + module.exports = function() { + return performance.now(); + }; + } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) { + module.exports = function() { + return (getNanoSeconds() - loadTime) / 1e6; + }; + hrtime = process.hrtime; + getNanoSeconds = function() { + var hr; + hr = hrtime(); + return hr[0] * 1e9 + hr[1]; + }; + loadTime = getNanoSeconds(); + } else if (Date.now) { + module.exports = function() { + return Date.now() - loadTime; + }; + loadTime = Date.now(); + } else { + module.exports = function() { + return new Date().getTime() - loadTime; + }; + loadTime = new Date().getTime(); + } - if (err) { - throw err; - } +}).call(this); - return release; -} -function unlockSync(file, options) { - options = options || {}; - options.fs = syncFs(options.fs || fs); +/***/ }), +/* 585 */ +/***/ (function(module, exports, __webpack_require__) { - let err; +"use strict"; - unlock(file, options, (_err) => { - err = _err; - }); +module.exports = function (url) { + if (typeof url !== 'string') { + throw new TypeError('Expected a string, got ' + typeof url); + } - if (err) { - throw err; - } -} + url = url.trim(); -function check(file, options, callback) { - if (typeof options === 'function') { - callback = options; - options = null; - } + if (/^\.*\/|^(?!localhost)\w+:/.test(url)) { + return url; + } - options = Object.assign({ - stale: 10000, - realpath: true, - fs, - }, options); + return url.replace(/^(?!(?:\w+:)?\/\/)/, 'http://'); +}; - options.stale = Math.max(options.stale || 0, 2000); - // Resolve to a canonical file path - canonicalPath(file, options, (err, file) => { - if (err) { - return callback(err); - } +/***/ }), +/* 586 */ +/***/ (function(module, exports, __webpack_require__) { - // Check if lockfile exists - options.fs.stat(getLockFile(file), (err, stat) => { - if (err) { - // if does not exist, file is not locked. Otherwise, callback with error - return (err.code === 'ENOENT') ? callback(null, false) : callback(err); - } +"use strict"; +/*! + * preserve <https://github.com/jonschlinkert/preserve> + * + * Copyright (c) 2014-2015, Jon Schlinkert. + * Licensed under the MIT license. + */ - if (options.stale <= 0) { return callback(null, true); } - // Otherwise, check if lock is stale by analyzing the file mtime - return callback(null, !isLockStale(stat, options)); - }); - }); -} -function checkSync(file, options) { - options = options || {}; - options.fs = syncFs(options.fs || fs); +/** + * Replace tokens in `str` with a temporary, heuristic placeholder. + * + * ```js + * tokens.before('{a\\,b}'); + * //=> '{__ID1__}' + * ``` + * + * @param {String} `str` + * @return {String} String with placeholders. + * @api public + */ - let err; - let locked; +exports.before = function before(str, re) { + return str.replace(re, function (match) { + var id = randomize(); + cache[id] = match; + return '__ID' + id + '__'; + }); +}; - check(file, options, (_err, _locked) => { - err = _err; - locked = _locked; - }); +/** + * Replace placeholders in `str` with original tokens. + * + * ```js + * tokens.after('{__ID1__}'); + * //=> '{a\\,b}' + * ``` + * + * @param {String} `str` String with placeholders + * @return {String} `str` String with original tokens. + * @api public + */ - if (err) { - throw err; - } +exports.after = function after(str) { + return str.replace(/__ID(.{5})__/g, function (_, id) { + return cache[id]; + }); +}; - return locked; +function randomize() { + return Math.random().toString().slice(2, 7); } - -// Remove acquired locks on exit -/* istanbul ignore next */ -process.on('exit', () => { - Object.keys(locks).forEach((file) => { - try { locks[file].options.fs.rmdirSync(getLockFile(file)); } catch (e) { /* empty */ } - }); -}); - -module.exports = lock; -module.exports.lock = lock; -module.exports.unlock = unlock; -module.exports.lockSync = lockSync; -module.exports.unlockSync = unlockSync; -module.exports.check = check; -module.exports.checkSync = checkSync; - +var cache = {}; /***/ }), -/* 573 */ +/* 587 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -110039,12 +113164,12 @@ module.exports = syncFs; /***/ }), -/* 574 */ +/* 588 */ /***/ (function(module, exports, __webpack_require__) { -var pump = __webpack_require__(248) -var inherits = __webpack_require__(37) -var Duplexify = __webpack_require__(228) +var pump = __webpack_require__(301) +var inherits = __webpack_require__(39) +var Duplexify = __webpack_require__(283) var toArray = function(args) { if (!args.length) return [] @@ -110100,13 +113225,13 @@ module.exports.obj = define({destroy:false, objectMode:true, highWaterMark:16}) /***/ }), -/* 575 */ +/* 589 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(251); +var utils = __webpack_require__(304); var has = Object.prototype.hasOwnProperty; @@ -110274,14 +113399,14 @@ module.exports = function (str, opts) { /***/ }), -/* 576 */ +/* 590 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var utils = __webpack_require__(251); -var formats = __webpack_require__(249); +var utils = __webpack_require__(304); +var formats = __webpack_require__(302); var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching @@ -110488,7 +113613,219 @@ module.exports = function (object, opts) { /***/ }), -/* 577 */ +/* 591 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var strictUriEncode = __webpack_require__(636); +var objectAssign = __webpack_require__(299); + +function encoderForArrayFormat(opts) { + switch (opts.arrayFormat) { + case 'index': + return function (key, value, index) { + return value === null ? [ + encode(key, opts), + '[', + index, + ']' + ].join('') : [ + encode(key, opts), + '[', + encode(index, opts), + ']=', + encode(value, opts) + ].join(''); + }; + + case 'bracket': + return function (key, value) { + return value === null ? encode(key, opts) : [ + encode(key, opts), + '[]=', + encode(value, opts) + ].join(''); + }; + + default: + return function (key, value) { + return value === null ? encode(key, opts) : [ + encode(key, opts), + '=', + encode(value, opts) + ].join(''); + }; + } +} + +function parserForArrayFormat(opts) { + var result; + + switch (opts.arrayFormat) { + case 'index': + return function (key, value, accumulator) { + result = /\[(\d*)\]$/.exec(key); + + key = key.replace(/\[\d*\]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } + + if (accumulator[key] === undefined) { + accumulator[key] = {}; + } + + accumulator[key][result[1]] = value; + }; + + case 'bracket': + return function (key, value, accumulator) { + result = /(\[\])$/.exec(key); + key = key.replace(/\[\]$/, ''); + + if (!result) { + accumulator[key] = value; + return; + } else if (accumulator[key] === undefined) { + accumulator[key] = [value]; + return; + } + + accumulator[key] = [].concat(accumulator[key], value); + }; + + default: + return function (key, value, accumulator) { + if (accumulator[key] === undefined) { + accumulator[key] = value; + return; + } + + accumulator[key] = [].concat(accumulator[key], value); + }; + } +} + +function encode(value, opts) { + if (opts.encode) { + return opts.strict ? strictUriEncode(value) : encodeURIComponent(value); + } + + return value; +} + +function keysSorter(input) { + if (Array.isArray(input)) { + return input.sort(); + } else if (typeof input === 'object') { + return keysSorter(Object.keys(input)).sort(function (a, b) { + return Number(a) - Number(b); + }).map(function (key) { + return input[key]; + }); + } + + return input; +} + +exports.extract = function (str) { + return str.split('?')[1] || ''; +}; + +exports.parse = function (str, opts) { + opts = objectAssign({arrayFormat: 'none'}, opts); + + var formatter = parserForArrayFormat(opts); + + // Create an object with no prototype + // https://github.com/sindresorhus/query-string/issues/47 + var ret = Object.create(null); + + if (typeof str !== 'string') { + return ret; + } + + str = str.trim().replace(/^(\?|#|&)/, ''); + + if (!str) { + return ret; + } + + str.split('&').forEach(function (param) { + var parts = param.replace(/\+/g, ' ').split('='); + // Firefox (pre 40) decodes `%3D` to `=` + // https://github.com/sindresorhus/query-string/pull/37 + var key = parts.shift(); + var val = parts.length > 0 ? parts.join('=') : undefined; + + // missing `=` should be `null`: + // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters + val = val === undefined ? null : decodeURIComponent(val); + + formatter(decodeURIComponent(key), val, ret); + }); + + return Object.keys(ret).sort().reduce(function (result, key) { + var val = ret[key]; + if (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) { + // Sort object keys, not values + result[key] = keysSorter(val); + } else { + result[key] = val; + } + + return result; + }, Object.create(null)); +}; + +exports.stringify = function (obj, opts) { + var defaults = { + encode: true, + strict: true, + arrayFormat: 'none' + }; + + opts = objectAssign(defaults, opts); + + var formatter = encoderForArrayFormat(opts); + + return obj ? Object.keys(obj).sort().map(function (key) { + var val = obj[key]; + + if (val === undefined) { + return ''; + } + + if (val === null) { + return encode(key, opts); + } + + if (Array.isArray(val)) { + var result = []; + + val.slice().forEach(function (val2) { + if (val2 === undefined) { + return; + } + + result.push(formatter(key, val2, result.length)); + }); + + return result.join('&'); + } + + return encode(key, opts) + '=' + encode(val, opts); + }).filter(function (x) { + return x.length > 0; + }).join('&') : ''; +}; + + +/***/ }), +/* 592 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -110502,8 +113839,8 @@ module.exports = function (object, opts) { -var isNumber = __webpack_require__(239); -var typeOf = __webpack_require__(157); +var isNumber = __webpack_require__(292); +var typeOf = __webpack_require__(218); /** * Expose `randomatic` @@ -110578,14 +113915,14 @@ function randomatic(pattern, length, options) { /***/ }), -/* 578 */ +/* 593 */ /***/ (function(module, exports, __webpack_require__) { module.exports = read -var readline = __webpack_require__(115) -var Mute = __webpack_require__(245) +var readline = __webpack_require__(151) +var Mute = __webpack_require__(297) function read (opts, cb) { if (opts.num) { @@ -110697,14 +114034,14 @@ function read (opts, cb) { /***/ }), -/* 579 */ +/* 594 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(47).Duplex +module.exports = __webpack_require__(74).Duplex /***/ }), -/* 580 */ +/* 595 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -110716,11 +114053,11 @@ module.exports = __webpack_require__(47).Duplex module.exports = PassThrough; -var Transform = __webpack_require__(253); +var Transform = __webpack_require__(306); /*<replacement>*/ -var util = __webpack_require__(71); -util.inherits = __webpack_require__(37); +var util = __webpack_require__(110); +util.inherits = __webpack_require__(39); /*</replacement>*/ util.inherits(PassThrough, Transform); @@ -110736,15 +114073,15 @@ PassThrough.prototype._transform = function (chunk, encoding, cb) { }; /***/ }), -/* 581 */ +/* 596 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var Buffer = __webpack_require__(76).Buffer; +var Buffer = __webpack_require__(120).Buffer; /*<replacement>*/ -var bufferShim = __webpack_require__(132); +var bufferShim = __webpack_require__(174); /*</replacement>*/ module.exports = BufferList; @@ -110806,14 +114143,14 @@ BufferList.prototype.concat = function (n) { }; /***/ }), -/* 582 */ +/* 597 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(47).Transform +module.exports = __webpack_require__(74).Transform /***/ }), -/* 583 */ +/* 598 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -110826,8 +114163,8 @@ module.exports = __webpack_require__(47).Transform -var isPrimitive = __webpack_require__(240); -var equal = __webpack_require__(537); +var isPrimitive = __webpack_require__(293); +var equal = __webpack_require__(551); var basic = {}; var cache = {}; @@ -110889,7 +114226,7 @@ module.exports.basic = basic; /***/ }), -/* 584 */ +/* 599 */ /***/ (function(module, exports) { const isWin = process.platform === 'win32'; @@ -110908,7 +114245,7 @@ function endsInSeparator(str) { /***/ }), -/* 585 */ +/* 600 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -110985,7 +114322,7 @@ function repeat(str, num) { /***/ }), -/* 586 */ +/* 601 */ /***/ (function(module, exports) { module.exports = { @@ -111021,11 +114358,11 @@ module.exports = { }; /***/ }), -/* 587 */ +/* 602 */ /***/ (function(module, exports, __webpack_require__) { -var fs = __webpack_require__(6); -var pkg = __webpack_require__(586); +var fs = __webpack_require__(5); +var pkg = __webpack_require__(601); function buildHarHeaders (headers) { return headers ? Object.keys(headers).map(function (key) { @@ -111169,7 +114506,7 @@ module.exports = HarWrapper; /***/ }), -/* 588 */ +/* 603 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -111189,9 +114526,9 @@ module.exports = HarWrapper; -var extend = __webpack_require__(148) - , cookies = __webpack_require__(258) - , helpers = __webpack_require__(163) +var extend = __webpack_require__(205) + , cookies = __webpack_require__(311) + , helpers = __webpack_require__(223) var paramsHaveRequestBody = helpers.paramsHaveRequestBody @@ -111316,7 +114653,7 @@ request.forever = function (agentOptions, optionsArg) { // Exports module.exports = request -request.Request = __webpack_require__(597) +request.Request = __webpack_require__(612) request.initParams = initParams // Backwards compatibility for request.debug @@ -111332,15 +114669,15 @@ Object.defineProperty(request, 'debug', { /***/ }), -/* 589 */ +/* 604 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var caseless = __webpack_require__(133) - , uuid = __webpack_require__(58) - , helpers = __webpack_require__(163) +var caseless = __webpack_require__(176) + , uuid = __webpack_require__(88) + , helpers = __webpack_require__(223) var md5 = helpers.md5 , toBase64 = helpers.toBase64 @@ -111507,7 +114844,7 @@ exports.Auth = Auth /***/ }), -/* 590 */ +/* 605 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -111593,16 +114930,16 @@ module.exports = getProxyFromURI /***/ }), -/* 591 */ +/* 606 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var fs = __webpack_require__(6) -var qs = __webpack_require__(114) -var validate = __webpack_require__(503) -var extend = __webpack_require__(148) +var fs = __webpack_require__(5) +var qs = __webpack_require__(150) +var validate = __webpack_require__(519) +var extend = __webpack_require__(205) function Har (request) { this.request = request @@ -111815,16 +115152,16 @@ exports.Har = Har /***/ }), -/* 592 */ +/* 607 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var uuid = __webpack_require__(58) - , CombinedStream = __webpack_require__(213) - , isstream = __webpack_require__(242) - , Buffer = __webpack_require__(57).Buffer +var uuid = __webpack_require__(88) + , CombinedStream = __webpack_require__(281) + , isstream = __webpack_require__(295) + , Buffer = __webpack_require__(87).Buffer function Multipart (request) { @@ -111935,19 +115272,19 @@ exports.Multipart = Multipart /***/ }), -/* 593 */ +/* 608 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var url = __webpack_require__(11) - , qs = __webpack_require__(250) - , caseless = __webpack_require__(133) - , uuid = __webpack_require__(58) - , oauth = __webpack_require__(564) - , crypto = __webpack_require__(7) - , Buffer = __webpack_require__(57).Buffer +var url = __webpack_require__(14) + , qs = __webpack_require__(303) + , caseless = __webpack_require__(176) + , uuid = __webpack_require__(88) + , oauth = __webpack_require__(578) + , crypto = __webpack_require__(8) + , Buffer = __webpack_require__(87).Buffer function OAuth (request) { @@ -112090,14 +115427,14 @@ exports.OAuth = OAuth /***/ }), -/* 594 */ +/* 609 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var qs = __webpack_require__(250) - , querystring = __webpack_require__(114) +var qs = __webpack_require__(303) + , querystring = __webpack_require__(150) function Querystring (request) { @@ -112148,13 +115485,13 @@ exports.Querystring = Querystring /***/ }), -/* 595 */ +/* 610 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var url = __webpack_require__(11) +var url = __webpack_require__(14) var isUrl = /^https?:/ function Redirect (request) { @@ -112312,14 +115649,14 @@ exports.Redirect = Redirect /***/ }), -/* 596 */ +/* 611 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var url = __webpack_require__(11) - , tunnel = __webpack_require__(630) +var url = __webpack_require__(14) + , tunnel = __webpack_require__(646) var defaultProxyHeaderWhiteList = [ 'accept', @@ -112495,42 +115832,42 @@ exports.Tunnel = Tunnel /***/ }), -/* 597 */ +/* 612 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var http = __webpack_require__(50) - , https = __webpack_require__(112) - , url = __webpack_require__(11) +var http = __webpack_require__(49) + , https = __webpack_require__(149) + , url = __webpack_require__(14) , util = __webpack_require__(2) - , stream = __webpack_require__(20) - , zlib = __webpack_require__(169) - , hawk = __webpack_require__(506) - , aws2 = __webpack_require__(328) - , aws4 = __webpack_require__(329) - , httpSignature = __webpack_require__(510) - , mime = __webpack_require__(244) - , stringstream = __webpack_require__(622) - , caseless = __webpack_require__(133) - , ForeverAgent = __webpack_require__(472) - , FormData = __webpack_require__(473) - , extend = __webpack_require__(148) - , isstream = __webpack_require__(242) - , isTypedArray = __webpack_require__(542).strict - , helpers = __webpack_require__(163) - , cookies = __webpack_require__(258) - , getProxyFromURI = __webpack_require__(590) - , Querystring = __webpack_require__(594).Querystring - , Har = __webpack_require__(591).Har - , Auth = __webpack_require__(589).Auth - , OAuth = __webpack_require__(593).OAuth - , Multipart = __webpack_require__(592).Multipart - , Redirect = __webpack_require__(595).Redirect - , Tunnel = __webpack_require__(596).Tunnel - , now = __webpack_require__(570) - , Buffer = __webpack_require__(57).Buffer + , stream = __webpack_require__(26) + , zlib = __webpack_require__(230) + , hawk = __webpack_require__(522) + , aws2 = __webpack_require__(383) + , aws4 = __webpack_require__(384) + , httpSignature = __webpack_require__(526) + , mime = __webpack_require__(296) + , stringstream = __webpack_require__(638) + , caseless = __webpack_require__(176) + , ForeverAgent = __webpack_require__(490) + , FormData = __webpack_require__(491) + , extend = __webpack_require__(205) + , isstream = __webpack_require__(295) + , isTypedArray = __webpack_require__(557).strict + , helpers = __webpack_require__(223) + , cookies = __webpack_require__(311) + , getProxyFromURI = __webpack_require__(605) + , Querystring = __webpack_require__(609).Querystring + , Har = __webpack_require__(606).Har + , Auth = __webpack_require__(604).Auth + , OAuth = __webpack_require__(608).OAuth + , Multipart = __webpack_require__(607).Multipart + , Redirect = __webpack_require__(610).Redirect + , Tunnel = __webpack_require__(611).Tunnel + , now = __webpack_require__(584) + , Buffer = __webpack_require__(87).Buffer var safeStringify = helpers.safeStringify , isReadStream = helpers.isReadStream @@ -114067,13 +117404,13 @@ module.exports = Request /***/ }), -/* 598 */ +/* 613 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -const onetime = __webpack_require__(566); -const signalExit = __webpack_require__(261); +const onetime = __webpack_require__(580); +const signalExit = __webpack_require__(314); module.exports = onetime(() => { signalExit(() => { @@ -114083,16 +117420,16 @@ module.exports = onetime(() => { /***/ }), -/* 599 */ +/* 614 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(600); +module.exports = __webpack_require__(615); /***/ }), -/* 600 */ +/* 615 */ /***/ (function(module, exports, __webpack_require__) { -var RetryOperation = __webpack_require__(601); +var RetryOperation = __webpack_require__(616); exports.operation = function(options) { var timeouts = exports.timeouts(options); @@ -114174,545 +117511,176 @@ exports.wrap = function(obj, options, methods) { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); - args.push(function(err) { - if (op.retry(err)) { - return; - } - if (err) { - arguments[0] = op.mainError(); - } - callback.apply(this, arguments); - }); - - op.attempt(function() { - original.apply(obj, args); - }); - }; - obj[method].options = options; - } -}; - - -/***/ }), -/* 601 */ -/***/ (function(module, exports) { - -function RetryOperation(timeouts, options) { - // Compatibility for the old (timeouts, retryForever) signature - if (typeof options === 'boolean') { - options = { forever: options }; - } - - this._timeouts = timeouts; - this._options = options || {}; - this._fn = null; - this._errors = []; - this._attempts = 1; - this._operationTimeout = null; - this._operationTimeoutCb = null; - this._timeout = null; - - if (this._options.forever) { - this._cachedTimeouts = this._timeouts.slice(0); - } -} -module.exports = RetryOperation; - -RetryOperation.prototype.stop = function() { - if (this._timeout) { - clearTimeout(this._timeout); - } - - this._timeouts = []; - this._cachedTimeouts = null; -}; - -RetryOperation.prototype.retry = function(err) { - if (this._timeout) { - clearTimeout(this._timeout); - } - - if (!err) { - return false; - } - - this._errors.push(err); - - var timeout = this._timeouts.shift(); - if (timeout === undefined) { - if (this._cachedTimeouts) { - // retry forever, only keep last error - this._errors.splice(this._errors.length - 1, this._errors.length); - this._timeouts = this._cachedTimeouts.slice(0); - timeout = this._timeouts.shift(); - } else { - return false; - } - } - - var self = this; - var timer = setTimeout(function() { - self._attempts++; - - if (self._operationTimeoutCb) { - self._timeout = setTimeout(function() { - self._operationTimeoutCb(self._attempts); - }, self._operationTimeout); - - if (this._options.unref) { - self._timeout.unref(); - } - } - - self._fn(self._attempts); - }, timeout); - - if (this._options.unref) { - timer.unref(); - } - - return true; -}; - -RetryOperation.prototype.attempt = function(fn, timeoutOps) { - this._fn = fn; - - if (timeoutOps) { - if (timeoutOps.timeout) { - this._operationTimeout = timeoutOps.timeout; - } - if (timeoutOps.cb) { - this._operationTimeoutCb = timeoutOps.cb; - } - } - - var self = this; - if (this._operationTimeoutCb) { - this._timeout = setTimeout(function() { - self._operationTimeoutCb(); - }, self._operationTimeout); - } - - this._fn(this._attempts); -}; - -RetryOperation.prototype.try = function(fn) { - console.log('Using RetryOperation.try() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = function(fn) { - console.log('Using RetryOperation.start() is deprecated'); - this.attempt(fn); -}; - -RetryOperation.prototype.start = RetryOperation.prototype.try; - -RetryOperation.prototype.errors = function() { - return this._errors; -}; - -RetryOperation.prototype.attempts = function() { - return this._attempts; -}; - -RetryOperation.prototype.mainError = function() { - if (this._errors.length === 0) { - return null; - } - - var counts = {}; - var mainError = null; - var mainErrorCount = 0; - - for (var i = 0; i < this._errors.length; i++) { - var error = this._errors[i]; - var message = error.message; - var count = (counts[message] || 0) + 1; - - counts[message] = count; - - if (count >= mainErrorCount) { - mainError = error; - mainErrorCount = count; - } - } - - return mainError; -}; - - -/***/ }), -/* 602 */ -/***/ (function(module, exports, __webpack_require__) { - -module.exports = rimraf -rimraf.sync = rimrafSync - -var assert = __webpack_require__(22) -var path = __webpack_require__(1) -var fs = __webpack_require__(6) -var glob = __webpack_require__(150) - -var defaultGlobOpts = { - nosort: true, - silent: true -} - -// for EMFILE handling -var timeout = 0 - -var isWindows = (process.platform === "win32") - -function defaults (options) { - var methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(function(m) { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - - options.maxBusyTries = options.maxBusyTries || 3 - options.emfileWait = options.emfileWait || 1000 - if (options.glob === false) { - options.disableGlob = true - } - options.disableGlob = options.disableGlob || false - options.glob = options.glob || defaultGlobOpts -} - -function rimraf (p, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert.equal(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.equal(typeof options, 'object', 'rimraf: options should be object') - - defaults(options) - - var busyTries = 0 - var errState = null - var n = 0 - - if (options.disableGlob || !glob.hasMagic(p)) - return afterGlob(null, [p]) - - options.lstat(p, function (er, stat) { - if (!er) - return afterGlob(null, [p]) - - glob(p, options.glob, afterGlob) - }) - - function next (er) { - errState = errState || er - if (--n === 0) - cb(errState) - } - - function afterGlob (er, results) { - if (er) - return cb(er) - - n = results.length - if (n === 0) - return cb() - - results.forEach(function (p) { - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === "EBUSY" || er.code === "ENOTEMPTY" || er.code === "EPERM") && - busyTries < options.maxBusyTries) { - busyTries ++ - var time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(function () { - rimraf_(p, options, CB) - }, time) - } - - // this one won't happen if graceful-fs is used. - if (er.code === "EMFILE" && timeout < options.emfileWait) { - return setTimeout(function () { - rimraf_(p, options, CB) - }, timeout ++) - } - - // already gone - if (er.code === "ENOENT") er = null + args.push(function(err) { + if (op.retry(err)) { + return; + } + if (err) { + arguments[0] = op.mainError(); } + callback.apply(this, arguments); + }); - timeout = 0 - next(er) - }) - }) + op.attempt(function() { + original.apply(obj, args); + }); + }; + obj[method].options = options; } -} +}; -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, function (er, st) { - if (er && er.code === "ENOENT") - return cb(null) +/***/ }), +/* 616 */ +/***/ (function(module, exports) { - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === "EPERM" && isWindows) - fixWinEPERM(p, options, er, cb) +function RetryOperation(timeouts, options) { + // Compatibility for the old (timeouts, retryForever) signature + if (typeof options === 'boolean') { + options = { forever: options }; + } - if (st && st.isDirectory()) - return rmdir(p, options, er, cb) + this._timeouts = timeouts; + this._options = options || {}; + this._fn = null; + this._errors = []; + this._attempts = 1; + this._operationTimeout = null; + this._operationTimeoutCb = null; + this._timeout = null; - options.unlink(p, function (er) { - if (er) { - if (er.code === "ENOENT") - return cb(null) - if (er.code === "EPERM") - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - if (er.code === "EISDIR") - return rmdir(p, options, er, cb) - } - return cb(er) - }) - }) + if (this._options.forever) { + this._cachedTimeouts = this._timeouts.slice(0); + } } +module.exports = RetryOperation; -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - if (er) - assert(er instanceof Error) - - options.chmod(p, 666, function (er2) { - if (er2) - cb(er2.code === "ENOENT" ? null : er) - else - options.stat(p, function(er3, stats) { - if (er3) - cb(er3.code === "ENOENT" ? null : er) - else if (stats.isDirectory()) - rmdir(p, options, er, cb) - else - options.unlink(p, cb) - }) - }) -} +RetryOperation.prototype.stop = function() { + if (this._timeout) { + clearTimeout(this._timeout); + } -function fixWinEPERMSync (p, options, er) { - assert(p) - assert(options) - if (er) - assert(er instanceof Error) + this._timeouts = []; + this._cachedTimeouts = null; +}; - try { - options.chmodSync(p, 666) - } catch (er2) { - if (er2.code === "ENOENT") - return - else - throw er +RetryOperation.prototype.retry = function(err) { + if (this._timeout) { + clearTimeout(this._timeout); } - try { - var stats = options.statSync(p) - } catch (er3) { - if (er3.code === "ENOENT") - return - else - throw er + if (!err) { + return false; } - if (stats.isDirectory()) - rmdirSync(p, options, er) - else - options.unlinkSync(p) -} + this._errors.push(err); -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) - assert(typeof cb === 'function') + var timeout = this._timeouts.shift(); + if (timeout === undefined) { + if (this._cachedTimeouts) { + // retry forever, only keep last error + this._errors.splice(this._errors.length - 1, this._errors.length); + this._timeouts = this._cachedTimeouts.slice(0); + timeout = this._timeouts.shift(); + } else { + return false; + } + } - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, function (er) { - if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM")) - rmkids(p, options, cb) - else if (er && er.code === "ENOTDIR") - cb(originalEr) - else - cb(er) - }) -} + var self = this; + var timer = setTimeout(function() { + self._attempts++; -function rmkids(p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') + if (self._operationTimeoutCb) { + self._timeout = setTimeout(function() { + self._operationTimeoutCb(self._attempts); + }, self._operationTimeout); - options.readdir(p, function (er, files) { - if (er) - return cb(er) - var n = files.length - if (n === 0) - return options.rmdir(p, cb) - var errState - files.forEach(function (f) { - rimraf(path.join(p, f), options, function (er) { - if (errState) - return - if (er) - return cb(errState = er) - if (--n === 0) - options.rmdir(p, cb) - }) - }) - }) -} + if (this._options.unref) { + self._timeout.unref(); + } + } -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - options = options || {} - defaults(options) + self._fn(self._attempts); + }, timeout); - assert(p, 'rimraf: missing path') - assert.equal(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.equal(typeof options, 'object', 'rimraf: options should be object') + if (this._options.unref) { + timer.unref(); + } - var results + return true; +}; - if (options.disableGlob || !glob.hasMagic(p)) { - results = [p] - } else { - try { - options.lstatSync(p) - results = [p] - } catch (er) { - results = glob.sync(p, options.glob) +RetryOperation.prototype.attempt = function(fn, timeoutOps) { + this._fn = fn; + + if (timeoutOps) { + if (timeoutOps.timeout) { + this._operationTimeout = timeoutOps.timeout; + } + if (timeoutOps.cb) { + this._operationTimeoutCb = timeoutOps.cb; } } - if (!results.length) - return + var self = this; + if (this._operationTimeoutCb) { + this._timeout = setTimeout(function() { + self._operationTimeoutCb(); + }, self._operationTimeout); + } - for (var i = 0; i < results.length; i++) { - var p = results[i] + this._fn(this._attempts); +}; - try { - var st = options.lstatSync(p) - } catch (er) { - if (er.code === "ENOENT") - return +RetryOperation.prototype.try = function(fn) { + console.log('Using RetryOperation.try() is deprecated'); + this.attempt(fn); +}; - // Windows can EPERM on stat. Life is suffering. - if (er.code === "EPERM" && isWindows) - fixWinEPERMSync(p, options, er) - } +RetryOperation.prototype.start = function(fn) { + console.log('Using RetryOperation.start() is deprecated'); + this.attempt(fn); +}; - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) - rmdirSync(p, options, null) - else - options.unlinkSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "EPERM") - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - if (er.code !== "EISDIR") - throw er +RetryOperation.prototype.start = RetryOperation.prototype.try; - rmdirSync(p, options, er) - } - } -} +RetryOperation.prototype.errors = function() { + return this._errors; +}; -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - if (originalEr) - assert(originalEr instanceof Error) +RetryOperation.prototype.attempts = function() { + return this._attempts; +}; - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === "ENOENT") - return - if (er.code === "ENOTDIR") - throw originalEr - if (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM") - rmkidsSync(p, options) +RetryOperation.prototype.mainError = function() { + if (this._errors.length === 0) { + return null; } -} -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(function (f) { - rimrafSync(path.join(p, f), options) - }) + var counts = {}; + var mainError = null; + var mainErrorCount = 0; - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - var retries = isWindows ? 100 : 1 - var i = 0 - do { - var threw = true - try { - var ret = options.rmdirSync(p, options) - threw = false - return ret - } finally { - if (++i < retries && threw) - continue + for (var i = 0; i < this._errors.length; i++) { + var error = this._errors[i]; + var message = error.message; + var count = (counts[message] || 0) + 1; + + counts[message] = count; + + if (count >= mainErrorCount) { + mainError = error; + mainErrorCount = count; } - } while (true) -} + } + + return mainError; +}; /***/ }), -/* 603 */ +/* 617 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -114738,7 +117706,7 @@ function rmkidsSync (p, options) { // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { return factory(root, exports, Rx); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -116085,7 +119053,7 @@ function rmkidsSync (p, options) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 604 */ +/* 618 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -116111,7 +119079,7 @@ function rmkidsSync (p, options) { // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(259), exports], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(312), exports], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), @@ -116625,7 +119593,7 @@ Observable.fromNodeCallback = function (fn, ctx, selector) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 605 */ +/* 619 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -116651,7 +119619,7 @@ Observable.fromNodeCallback = function (fn, ctx, selector) { // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { return factory(root, exports, Rx); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -117249,7 +120217,7 @@ Observable.fromNodeCallback = function (fn, ctx, selector) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 606 */ +/* 620 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -117275,7 +120243,7 @@ Observable.fromNodeCallback = function (fn, ctx, selector) { // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { return factory(root, exports, Rx); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -117880,7 +120848,7 @@ Observable.fromNodeCallback = function (fn, ctx, selector) { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 607 */ +/* 621 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -117906,7 +120874,7 @@ Observable.fromNodeCallback = function (fn, ctx, selector) { // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { return factory(root, exports, Rx); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -118478,7 +121446,7 @@ observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 608 */ +/* 622 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -118504,7 +121472,7 @@ observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { return factory(root, exports, Rx); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -118829,7 +121797,7 @@ observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 609 */ +/* 623 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -118855,7 +121823,7 @@ observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { return factory(root, exports, Rx); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -118908,7 +121876,7 @@ observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 610 */ +/* 624 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -118934,7 +121902,7 @@ observableProto.flatMapWithMaxConcurrent = observableProto.flatMapMaxConcurrent // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(260), exports], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(313), exports], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { root.Rx = factory(root, exports, Rx); return root.Rx; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), @@ -119425,7 +122393,7 @@ var ReactiveTest = Rx.ReactiveTest = { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 611 */ +/* 625 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information. @@ -119451,7 +122419,7 @@ var ReactiveTest = Rx.ReactiveTest = { // Because of build optimizers if (true) { - !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(30)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { + !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(40)], __WEBPACK_AMD_DEFINE_RESULT__ = function (Rx, exports) { return factory(root, exports, Rx); }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); @@ -120905,7 +123873,7 @@ var ReactiveTest = Rx.ReactiveTest = { /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 612 */ +/* 626 */ /***/ (function(module, exports) { // This is not the set of all possible signals. @@ -120964,14 +123932,14 @@ if (process.platform === 'linux') { /***/ }), -/* 613 */ +/* 627 */ /***/ (function(module, exports, __webpack_require__) { // Load modules -var Dgram = __webpack_require__(636); -var Dns = __webpack_require__(637); -var Hoek = __webpack_require__(95); +var Dgram = __webpack_require__(654); +var Dns = __webpack_require__(655); +var Hoek = __webpack_require__(132); // Declare internals @@ -121382,10 +124350,61 @@ internals.ignore = function () { /***/ }), -/* 614 */ +/* 628 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +var isPlainObj = __webpack_require__(554); + +module.exports = function (obj, opts) { + if (!isPlainObj(obj)) { + throw new TypeError('Expected a plain object'); + } + + opts = opts || {}; + + // DEPRECATED + if (typeof opts === 'function') { + opts = {compare: opts}; + } + + var deep = opts.deep; + var seenInput = []; + var seenOutput = []; + + var sortKeys = function (x) { + var seenIndex = seenInput.indexOf(x); + + if (seenIndex !== -1) { + return seenOutput[seenIndex]; + } + + var ret = {}; + var keys = Object.keys(x).sort(opts.compare); + + seenInput.push(x); + seenOutput.push(ret); + + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var val = x[key]; + + ret[key] = deep && isPlainObj(val) ? sortKeys(val) : val; + } + + return ret; + }; + + return sortKeys(obj); +}; + + +/***/ }), +/* 629 */ /***/ (function(module, exports, __webpack_require__) { -var licenseIDs = __webpack_require__(617); +var licenseIDs = __webpack_require__(632); function valid(string) { return licenseIDs.indexOf(string) > -1; @@ -121625,10 +124644,10 @@ module.exports = function(identifier) { /***/ }), -/* 615 */ +/* 630 */ /***/ (function(module, exports, __webpack_require__) { -var parser = __webpack_require__(616).parser +var parser = __webpack_require__(631).parser module.exports = function (argument) { return parser.parse(argument) @@ -121636,7 +124655,7 @@ module.exports = function (argument) { /***/ }), -/* 616 */ +/* 631 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {/* parser generated by jison 0.4.17 */ @@ -122989,7 +126008,7 @@ exports.main = function commonjsMain(args) { console.log('Usage: '+args[0]+' FILE'); process.exit(1); } - var source = __webpack_require__(6).readFileSync(__webpack_require__(1).normalize(args[1]), "utf8"); + var source = __webpack_require__(5).readFileSync(__webpack_require__(0).normalize(args[1]), "utf8"); return exports.parser.parse(source); }; if (typeof module !== 'undefined' && __webpack_require__.c[__webpack_require__.s] === module) { @@ -123000,7 +126019,7 @@ if (typeof module !== 'undefined' && __webpack_require__.c[__webpack_require__.s /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)(module))) /***/ }), -/* 617 */ +/* 632 */ /***/ (function(module, exports) { module.exports = [ @@ -123339,7 +126358,7 @@ module.exports = [ ]; /***/ }), -/* 618 */ +/* 633 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2017 Joyent, Inc. @@ -123356,17 +126375,17 @@ module.exports = { toBuffer: toBuffer }; -var assert = __webpack_require__(9); -var SSHBuffer = __webpack_require__(108); -var crypto = __webpack_require__(7); -var algs = __webpack_require__(16); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var Identity = __webpack_require__(75); -var rfc4253 = __webpack_require__(48); -var Signature = __webpack_require__(33); -var utils = __webpack_require__(13); -var Certificate = __webpack_require__(72); +var assert = __webpack_require__(11); +var SSHBuffer = __webpack_require__(144); +var crypto = __webpack_require__(8); +var algs = __webpack_require__(23); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var Identity = __webpack_require__(118); +var rfc4253 = __webpack_require__(75); +var Signature = __webpack_require__(45); +var utils = __webpack_require__(17); +var Certificate = __webpack_require__(115); function verify(cert, key) { /* @@ -123667,12 +126686,12 @@ function getCertType(key) { /***/ }), -/* 619 */ +/* 634 */ /***/ (function(module, exports, __webpack_require__) { // Copyright 2016 Joyent, Inc. -var x509 = __webpack_require__(267); +var x509 = __webpack_require__(320); module.exports = { read: read, @@ -123681,16 +126700,16 @@ module.exports = { write: write }; -var assert = __webpack_require__(9); -var asn1 = __webpack_require__(34); -var algs = __webpack_require__(16); -var utils = __webpack_require__(13); -var Key = __webpack_require__(17); -var PrivateKey = __webpack_require__(18); -var pem = __webpack_require__(41); -var Identity = __webpack_require__(75); -var Signature = __webpack_require__(33); -var Certificate = __webpack_require__(72); +var assert = __webpack_require__(11); +var asn1 = __webpack_require__(50); +var algs = __webpack_require__(23); +var utils = __webpack_require__(17); +var Key = __webpack_require__(24); +var PrivateKey = __webpack_require__(25); +var pem = __webpack_require__(58); +var Identity = __webpack_require__(118); +var Signature = __webpack_require__(45); +var Certificate = __webpack_require__(115); function read(buf, options) { if (typeof (buf) !== 'string') { @@ -123750,7 +126769,7 @@ function write(cert, options) { /***/ }), -/* 620 */ +/* 635 */ /***/ (function(module, exports) { module.exports = shift @@ -123776,7 +126795,20 @@ function getStateLength (state) { /***/ }), -/* 621 */ +/* 636 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + +module.exports = function (str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return '%' + c.charCodeAt(0).toString(16).toUpperCase(); + }); +}; + + +/***/ }), +/* 637 */ /***/ (function(module, exports) { /*! http://mths.be/codepointat v0.2.0 by @mathias */ @@ -123836,12 +126868,12 @@ if (!String.prototype.codePointAt) { /***/ }), -/* 622 */ +/* 638 */ /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__(2) -var Stream = __webpack_require__(20) -var StringDecoder = __webpack_require__(168).StringDecoder +var Stream = __webpack_require__(26) +var StringDecoder = __webpack_require__(229).StringDecoder module.exports = StringStream module.exports.AlignedStringDecoder = AlignedStringDecoder @@ -123944,16 +126976,16 @@ function alignedWrite(buffer) { /***/ }), -/* 623 */ +/* 639 */ /***/ (function(module, exports, __webpack_require__) { var util = __webpack_require__(2) -var bl = __webpack_require__(400) -var xtend = __webpack_require__(278) -var headers = __webpack_require__(269) +var bl = __webpack_require__(450) +var xtend = __webpack_require__(330) +var headers = __webpack_require__(321) -var Writable = __webpack_require__(47).Writable -var PassThrough = __webpack_require__(47).PassThrough +var Writable = __webpack_require__(74).Writable +var PassThrough = __webpack_require__(74).PassThrough var noop = function () {} @@ -124196,18 +127228,18 @@ module.exports = Extract /***/ }), -/* 624 */ +/* 640 */ /***/ (function(module, exports, __webpack_require__) { -var constants = __webpack_require__(280) -var eos = __webpack_require__(230) +var constants = __webpack_require__(331) +var eos = __webpack_require__(285) var util = __webpack_require__(2) -var Readable = __webpack_require__(47).Readable -var Writable = __webpack_require__(47).Writable -var StringDecoder = __webpack_require__(168).StringDecoder +var Readable = __webpack_require__(74).Readable +var Writable = __webpack_require__(74).Writable +var StringDecoder = __webpack_require__(229).StringDecoder -var headers = __webpack_require__(269) +var headers = __webpack_require__(321) var DMODE = parseInt('755', 8) var FMODE = parseInt('644', 8) @@ -124456,10 +127488,10 @@ module.exports = Pack /***/ }), -/* 625 */ +/* 641 */ /***/ (function(module, exports, __webpack_require__) { -var Stream = __webpack_require__(20) +var Stream = __webpack_require__(26) // through // @@ -124570,7 +127602,7 @@ function through (write, end, opts) { /***/ }), -/* 626 */ +/* 642 */ /***/ (function(module, exports, __webpack_require__) { /*! @@ -124585,10 +127617,10 @@ function through (write, end, opts) { * Module dependencies. */ var - fs = __webpack_require__(6), - path = __webpack_require__(1), - crypto = __webpack_require__(7), - tmpDir = __webpack_require__(567), + fs = __webpack_require__(5), + path = __webpack_require__(0), + crypto = __webpack_require__(8), + tmpDir = __webpack_require__(581), _c = process.binding('constants'); @@ -125065,7 +128097,7 @@ module.exports.setGracefulCleanup = _setGracefulCleanup; /***/ }), -/* 627 */ +/* 643 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -125100,17 +128132,17 @@ module.exports.setGracefulCleanup = _setGracefulCleanup; * POSSIBILITY OF SUCH DAMAGE. */ -var net = __webpack_require__(77); -var urlParse = __webpack_require__(11).parse; -var pubsuffix = __webpack_require__(274); -var Store = __webpack_require__(275).Store; -var MemoryCookieStore = __webpack_require__(628).MemoryCookieStore; -var pathMatch = __webpack_require__(272).pathMatch; -var VERSION = __webpack_require__(629).version; +var net = __webpack_require__(59); +var urlParse = __webpack_require__(14).parse; +var pubsuffix = __webpack_require__(326); +var Store = __webpack_require__(327).Store; +var MemoryCookieStore = __webpack_require__(644).MemoryCookieStore; +var pathMatch = __webpack_require__(324).pathMatch; +var VERSION = __webpack_require__(645).version; var punycode; try { - punycode = __webpack_require__(281); + punycode = __webpack_require__(228); } catch(e) { console.warn("cookie: can't load punycode; won't use punycode for domain normalization"); } @@ -126401,14 +129433,14 @@ module.exports = { pathMatch: pathMatch, getPublicSuffix: pubsuffix.getPublicSuffix, cookieCompare: cookieCompare, - permuteDomain: __webpack_require__(273).permuteDomain, + permuteDomain: __webpack_require__(325).permuteDomain, permutePath: permutePath, canonicalDomain: canonicalDomain }; /***/ }), -/* 628 */ +/* 644 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; @@ -126443,9 +129475,9 @@ module.exports = { * POSSIBILITY OF SUCH DAMAGE. */ -var Store = __webpack_require__(275).Store; -var permuteDomain = __webpack_require__(273).permuteDomain; -var pathMatch = __webpack_require__(272).pathMatch; +var Store = __webpack_require__(327).Store; +var permuteDomain = __webpack_require__(325).permuteDomain; +var pathMatch = __webpack_require__(324).pathMatch; var util = __webpack_require__(2); function MemoryCookieStore() { @@ -126585,7 +129617,7 @@ MemoryCookieStore.prototype.getAllCookies = function(cb) { /***/ }), -/* 629 */ +/* 645 */ /***/ (function(module, exports) { module.exports = { @@ -126664,20 +129696,20 @@ module.exports = { }; /***/ }), -/* 630 */ +/* 646 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var net = __webpack_require__(77) - , tls = __webpack_require__(282) - , http = __webpack_require__(50) - , https = __webpack_require__(112) - , events = __webpack_require__(49) - , assert = __webpack_require__(22) +var net = __webpack_require__(59) + , tls = __webpack_require__(332) + , http = __webpack_require__(49) + , https = __webpack_require__(149) + , events = __webpack_require__(46) + , assert = __webpack_require__(18) , util = __webpack_require__(2) - , Buffer = __webpack_require__(57).Buffer + , Buffer = __webpack_require__(87).Buffer ; exports.httpOverHttp = httpOverHttp @@ -126915,7 +129947,7 @@ exports.debug = debug // for test /***/ }), -/* 631 */ +/* 647 */ /***/ (function(module, exports, __webpack_require__) { @@ -126927,14 +129959,14 @@ module.exports = __webpack_require__(2).deprecate; /***/ }), -/* 632 */ +/* 648 */ /***/ (function(module, exports, __webpack_require__) { // Unique ID creation requires a high quality random # generator. We feature // detect to determine the best RNG source, normalizing to a function that // returns 128-bits of randomness, since that's what's usually required -var rng = __webpack_require__(277); -var bytesToUuid = __webpack_require__(276); +var rng = __webpack_require__(329); +var bytesToUuid = __webpack_require__(328); // **`v1()` - Generate time-based UUID** // @@ -127036,11 +130068,11 @@ module.exports = v1; /***/ }), -/* 633 */ +/* 649 */ /***/ (function(module, exports, __webpack_require__) { -var rng = __webpack_require__(277); -var bytesToUuid = __webpack_require__(276); +var rng = __webpack_require__(329); +var bytesToUuid = __webpack_require__(328); function v4(options, buf, offset) { var i = buf && offset || 0; @@ -127071,11 +130103,11 @@ module.exports = v4; /***/ }), -/* 634 */ +/* 650 */ /***/ (function(module, exports, __webpack_require__) { -var parse = __webpack_require__(615); -var correct = __webpack_require__(614); +var parse = __webpack_require__(630); +var correct = __webpack_require__(629); var genericWarning = ( 'license should be ' + @@ -127161,17 +130193,17 @@ module.exports = function(argument) { /***/ }), -/* 635 */ +/* 651 */ /***/ (function(module, exports, __webpack_require__) { /* * verror.js: richer JavaScript errors */ -var mod_assert = __webpack_require__(22); +var mod_assert = __webpack_require__(18); var mod_util = __webpack_require__(2); -var mod_extsprintf = __webpack_require__(232); +var mod_extsprintf = __webpack_require__(287); /* * Public interface @@ -127324,23 +130356,166 @@ WError.prototype.cause = function we_cause(c) /***/ }), -/* 636 */ -/***/ (function(module, exports) { +/* 652 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = require("dgram"); +"use strict"; -/***/ }), -/* 637 */ -/***/ (function(module, exports) { +const lenient = __webpack_require__(653); + +module.exports = (val, opts) => { + val = String(val).trim(); + opts = Object.assign({ + lenient: false, + default: null + }, opts); + + if (opts.default !== null && typeof opts.default !== 'boolean') { + throw new TypeError(`Expected the \`default\` option to be of type \`boolean\`, got \`${typeof opts.default}\``); + } + + if (/^(?:y|yes|true|1)$/i.test(val)) { + return true; + } + + if (/^(?:n|no|false|0)$/i.test(val)) { + return false; + } + + if (opts.lenient === true) { + return lenient(val, opts); + } + + return opts.default; +}; -module.exports = require("dns"); /***/ }), -/* 638 */ +/* 653 */ /***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(283); +"use strict"; + + +const YES_MATCH_SCORE_THRESHOLD = 2; +const NO_MATCH_SCORE_THRESHOLD = 1.25; + +const yMatch = new Map([ + [5, 0.25], + [6, 0.25], + [7, 0.25], + ['t', 0.75], + ['y', 1], + ['u', 0.75], + ['g', 0.25], + ['h', 0.25], + ['k', 0.25] +]); + +const eMatch = new Map([ + [2, 0.25], + [3, 0.25], + [4, 0.25], + ['w', 0.75], + ['e', 1], + ['r', 0.75], + ['s', 0.25], + ['d', 0.25], + ['f', 0.25] +]); + +const sMatch = new Map([ + ['q', 0.25], + ['w', 0.25], + ['e', 0.25], + ['a', 0.75], + ['s', 1], + ['d', 0.75], + ['z', 0.25], + ['x', 0.25], + ['c', 0.25] +]); + +const nMatch = new Map([ + ['h', 0.25], + ['j', 0.25], + ['k', 0.25], + ['b', 0.75], + ['n', 1], + ['m', 0.75] +]); + +const oMatch = new Map([ + [9, 0.25], + [0, 0.25], + ['i', 0.75], + ['o', 1], + ['p', 0.75], + ['k', 0.25], + ['l', 0.25] +]); + +function getYesMatchScore(val) { + let score = 0; + const y = val[0]; + const e = val[1]; + const s = val[2]; + + if (yMatch.has(y)) { + score += yMatch.get(y); + } + + if (eMatch.has(e)) { + score += eMatch.get(e); + } + + if (sMatch.has(s)) { + score += sMatch.get(s); + } + + return score; +} + +function getNoMatchScore(val) { + let score = 0; + const n = val[0]; + const o = val[1]; + + if (nMatch.has(n)) { + score += nMatch.get(n); + } + + if (oMatch.has(o)) { + score += oMatch.get(o); + } + + return score; +} + +module.exports = (val, opts) => { + if (getYesMatchScore(val) >= YES_MATCH_SCORE_THRESHOLD) { + return true; + } + + if (getNoMatchScore(val) >= NO_MATCH_SCORE_THRESHOLD) { + return false; + } + + return opts.default; +}; + + +/***/ }), +/* 654 */ +/***/ (function(module, exports) { + +module.exports = require("dgram"); +/***/ }), +/* 655 */ +/***/ (function(module, exports) { + +module.exports = require("dns"); /***/ }) /******/ ]); \ No newline at end of file diff --git a/lib/workers/branch/yarn.js b/lib/workers/branch/yarn.js index b9f3ef310bbf1f046fa2e74b688df05d135e7049..3a7b6a093fb9522efe517aa010d77d01ba43e88d 100644 --- a/lib/workers/branch/yarn.js +++ b/lib/workers/branch/yarn.js @@ -6,7 +6,7 @@ module.exports = { generateLockFile, }; -const yarnVersion = '0.27.5'; +const yarnVersion = '1.0.1'; async function generateLockFile(tmpDir, logger) { logger.debug('Generating new yarn.lock file');