snyk
Version:
snyk library and cli utility
1,724 lines (1,403 loc) • 268 kB
JavaScript
exports.id = 674;
exports.ids = [674];
exports.modules = {
/***/ 18971:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.execute = void 0;
const child_process_1 = __webpack_require__(32081);
// Executes a subprocess.
// Resolves successfully on exit code 0 with all the info
// available
async function execute(command, args, options) {
// WARN: Snyk CLI uses an internal proxy configuration that interferes
// with network requests made by subprocesses. In order to bypass this
// we reset the relevant environment variables to their defaults that
// the CLI has cached.
const env = Object.assign({}, process.env);
if (typeof process.env.SNYK_SYSTEM_HTTP_PROXY !== 'undefined') {
env.HTTP_PROXY = process.env.SNYK_SYSTEM_HTTP_PROXY;
}
if (typeof process.env.SNYK_SYSTEM_HTTPS_PROXY !== 'undefined') {
env.HTTPS_PROXY = process.env.SNYK_SYSTEM_HTTPS_PROXY;
}
if (typeof process.env.SNYK_SYSTEM_NO_PROXY !== 'undefined') {
env.NO_PROXY = process.env.SNYK_SYSTEM_NO_PROXY;
}
const spawnOptions = {
env,
shell: false,
detached: true, // do not send signals to child processes
};
if (options && options.cwd) {
spawnOptions.cwd = options.cwd;
}
const fullCommand = `${command} ${args.join(' ')}`.trim();
const startTime = Date.now();
let processId;
try {
const worker = (0, child_process_1.spawn)(command, args, spawnOptions);
processId = worker.pid;
return await new Promise((resolve, reject) => {
let stderr = '';
let stdout = '';
worker.stdout.on('data', (data) => {
stdout += data;
});
worker.stderr.on('data', (data) => {
stderr += data;
});
worker.on('error', (e) => {
reject({
stderr,
stdout,
error: e,
duration: Date.now() - startTime,
command: fullCommand,
});
});
worker.on('exit', (code) => {
if (code && code > 0) {
resolve({
stderr,
stdout,
duration: Date.now() - startTime,
command: fullCommand,
exitCode: code,
});
}
else {
resolve({
stderr,
stdout,
duration: Date.now() - startTime,
command: fullCommand,
exitCode: code,
});
}
});
});
}
finally {
if (processId) {
// Additional anti-zombie protection.
// Process here should be already stopped.
try {
process.kill(processId, 'SIGKILL');
}
catch (e) {
// Process already stopped.
}
}
}
}
exports.execute = execute;
//# sourceMappingURL=child-process.js.map
/***/ }),
/***/ 74262:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.execute = void 0;
var child_process_1 = __webpack_require__(18971);
Object.defineProperty(exports, "execute", ({ enumerable: true, get: function () { return child_process_1.execute; } }));
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 21591:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isPipenvInstalled = exports.extractPipenvVersion = void 0;
const child_process_1 = __webpack_require__(74262);
const debugLib = __webpack_require__(15158);
const debug = debugLib('snyk-fix:python:Pipfile');
function extractPipenvVersion(stdout) {
/* stdout example:
* pipenv, version 2018.11.26\n
*/
let version = null;
const re = new RegExp(/^pipenv,\sversion\s([0-9.]+)/, 'g');
const match = re.exec(stdout);
if (match) {
version = match[1];
}
return version;
}
exports.extractPipenvVersion = extractPipenvVersion;
async function isPipenvInstalled() {
let res;
try {
res = await (0, child_process_1.execute)('pipenv', ['--version'], {});
}
catch (e) {
debug('Execute failed with', e);
res = e;
}
if (res.exitCode !== 0) {
throw res.error;
}
return { version: extractPipenvVersion(res.stdout) };
}
exports.isPipenvInstalled = isPipenvInstalled;
//# sourceMappingURL=check-pip-env-installed.js.map
/***/ }),
/***/ 91989:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pipenvInstall = exports.isPipenvSupportedVersion = exports.isPipenvInstalled = void 0;
var check_pip_env_installed_1 = __webpack_require__(21591);
Object.defineProperty(exports, "isPipenvInstalled", ({ enumerable: true, get: function () { return check_pip_env_installed_1.isPipenvInstalled; } }));
var is_pipenv_supported_version_1 = __webpack_require__(97149);
Object.defineProperty(exports, "isPipenvSupportedVersion", ({ enumerable: true, get: function () { return is_pipenv_supported_version_1.isPipenvSupportedVersion; } }));
var pipenv_install_1 = __webpack_require__(96194);
Object.defineProperty(exports, "pipenvInstall", ({ enumerable: true, get: function () { return pipenv_install_1.pipenvInstall; } }));
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 97149:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isPipenvSupportedVersion = void 0;
function isPipenvSupportedVersion(version) {
// See all versions: https://pipenv.pypa.io/en/latest/changelog/
// Update SUPPORTED.md when this is updated
const SUPPORTED_PIPENV_VERSIONS = [
'2022.10.12',
'2022.9.21',
'2022.8.31',
'2022.7.24',
'2022.6.7',
'2022.5.2',
'2022.4.21',
'2021.11.23',
'2020.11.4',
'2020.8.13',
'2020.6.2',
'2020.5.28',
'2018.11.26',
'2018.11.14',
'2018.10.13',
'2018.10.9',
'2018.7.1',
'2018.6.25',
];
let supported = false;
if (SUPPORTED_PIPENV_VERSIONS.includes(version)) {
supported = true;
}
return {
supported,
versions: SUPPORTED_PIPENV_VERSIONS,
};
}
exports.isPipenvSupportedVersion = isPipenvSupportedVersion;
//# sourceMappingURL=is-pipenv-supported-version.js.map
/***/ }),
/***/ 96194:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.pipenvInstall = void 0;
const bottleneck_1 = __webpack_require__(35861);
const debugLib = __webpack_require__(15158);
const child_process_1 = __webpack_require__(74262);
const debug = debugLib('snyk-fix:python:Pipfile');
const limiter = new bottleneck_1.default({
maxConcurrent: 4,
});
// https://pipenv.pypa.io/en/latest/advanced/#changing-default-python-versions
function getPythonArgs(config) {
const args = [];
if (config.python) {
args.push('--python', config.python); // Performs the installation in a virtualenv using the provided Python interpreter.
}
if (process.env.PIPENV_SKIP_LOCK) {
args.push('--skip-lock');
}
return args;
}
async function runPipenvInstall(projectPath, requirements, config) {
const args = ['install', ...requirements];
const pythonArg = getPythonArgs(config);
if (pythonArg) {
args.push(...pythonArg);
}
let res;
try {
res = await (0, child_process_1.execute)('pipenv', args, {
cwd: projectPath,
});
}
catch (e) {
debug('Execute failed with', e);
res = e;
}
return res;
}
exports.pipenvInstall = limiter.wrap(runPipenvInstall);
//# sourceMappingURL=pipenv-install.js.map
/***/ }),
/***/ 42925:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isPoetryInstalled = exports.extractPoetryVersion = void 0;
const debugLib = __webpack_require__(15158);
const child_process_1 = __webpack_require__(74262);
const debug = debugLib('snyk-fix:poetry');
function extractPoetryVersion(stdout) {
/* stdout example:
* Poetry version 1.1.4
*/
let version = null;
const re = new RegExp(/^Poetry\sversion\s([0-9.]+)/, 'g');
const match = re.exec(stdout);
if (match) {
version = match[1];
}
return version;
}
exports.extractPoetryVersion = extractPoetryVersion;
async function isPoetryInstalled() {
let res;
try {
res = await (0, child_process_1.execute)('poetry', ['--version'], {});
}
catch (e) {
debug('Execute failed with', e);
res = e;
}
if (res.exitCode !== 0) {
throw res.error;
}
return { version: extractPoetryVersion(res.stdout) };
}
exports.isPoetryInstalled = isPoetryInstalled;
//# sourceMappingURL=check-poetry-is-installed.js.map
/***/ }),
/***/ 69671:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.poetryAdd = exports.isPoetrySupportedVersion = exports.isPoetryInstalled = void 0;
var check_poetry_is_installed_1 = __webpack_require__(42925);
Object.defineProperty(exports, "isPoetryInstalled", ({ enumerable: true, get: function () { return check_poetry_is_installed_1.isPoetryInstalled; } }));
var is_poetry_supported_version_1 = __webpack_require__(29257);
Object.defineProperty(exports, "isPoetrySupportedVersion", ({ enumerable: true, get: function () { return is_poetry_supported_version_1.isPoetrySupportedVersion; } }));
var poetry_add_1 = __webpack_require__(10055);
Object.defineProperty(exports, "poetryAdd", ({ enumerable: true, get: function () { return poetry_add_1.poetryAdd; } }));
//# sourceMappingURL=index.js.map
/***/ }),
/***/ 29257:
/***/ ((__unused_webpack_module, exports) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isPoetrySupportedVersion = void 0;
function isPoetrySupportedVersion(version) {
// See all versions: https://github.com/python-poetry/poetry/releases
// Update SUPPORTED.md when this is updated
// Not all versions listed below as not all are tested but most likely
// they are supported
const SUPPORTED_POETRY_VERSIONS = [
'1.1.9',
'1.1.8',
'1.1.7',
'1.1.6',
'1.1.5',
'1.1.4',
'1.0.9',
'1.0.8',
'1.0.7',
];
let supported = false;
if (SUPPORTED_POETRY_VERSIONS.includes(version)) {
supported = true;
}
return {
supported,
versions: SUPPORTED_POETRY_VERSIONS,
};
}
exports.isPoetrySupportedVersion = isPoetrySupportedVersion;
//# sourceMappingURL=is-poetry-supported-version.js.map
/***/ }),
/***/ 10055:
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
"use strict";
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.poetryAdd = void 0;
const bottleneck_1 = __webpack_require__(35861);
const debugLib = __webpack_require__(15158);
const child_process_1 = __webpack_require__(74262);
const debug = debugLib('snyk-fix:poetry');
const limiter = new bottleneck_1.default({
maxConcurrent: 4,
});
async function runPoetryAdd(projectPath, dependencyUpdates, config) {
const args = ['add', ...dependencyUpdates];
let res;
if (config.dev) {
args.push('--dev');
}
if (config.python) {
try {
// tell poetry to use the given interpreter
// https://python-poetry.org/docs/managing-environments/
await (0, child_process_1.execute)('poetry', ['env', 'use', config.python], {
cwd: projectPath,
});
}
catch (e) {
debug(`'poetry use env ${config.python}' failed with`, e);
}
}
try {
res = await (0, child_process_1.execute)('poetry', args, {
cwd: projectPath,
});
}
catch (e) {
debug('Execute failed with', e);
res = e;
}
if (config.python) {
try {
// set it back to system python
await (0, child_process_1.execute)('poetry', ['env', 'use', 'system'], {
cwd: projectPath,
});
}
catch (e) {
debug(`'poetry use env system' failed with`, e);
}
}
return res;
}
exports.poetryAdd = limiter.wrap(runPoetryAdd);
//# sourceMappingURL=poetry-add.js.map
/***/ }),
/***/ 9526:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
var Batcher, Events, parser;
parser = __webpack_require__(88092);
Events = __webpack_require__(33800);
Batcher = function () {
class Batcher {
constructor(options = {}) {
this.options = options;
parser.load(this.options, this.defaults, this);
this.Events = new Events(this);
this._arr = [];
this._resetPromise();
this._lastFlush = Date.now();
}
_resetPromise() {
return this._promise = new this.Promise((res, rej) => {
return this._resolve = res;
});
}
_flush() {
clearTimeout(this._timeout);
this._lastFlush = Date.now();
this._resolve();
this.Events.trigger("batch", this._arr);
this._arr = [];
return this._resetPromise();
}
add(data) {
var ret;
this._arr.push(data);
ret = this._promise;
if (this._arr.length === this.maxSize) {
this._flush();
} else if (this.maxTime != null && this._arr.length === 1) {
this._timeout = setTimeout(() => {
return this._flush();
}, this.maxTime);
}
return ret;
}
}
;
Batcher.prototype.defaults = {
maxTime: null,
maxSize: null,
Promise: Promise
};
return Batcher;
}.call(void 0);
module.exports = Batcher;
/***/ }),
/***/ 19529:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var Bottleneck,
DEFAULT_PRIORITY,
Events,
Job,
LocalDatastore,
NUM_PRIORITIES,
Queues,
RedisDatastore,
States,
Sync,
parser,
splice = [].splice;
NUM_PRIORITIES = 10;
DEFAULT_PRIORITY = 5;
parser = __webpack_require__(88092);
Queues = __webpack_require__(21186);
Job = __webpack_require__(21262);
LocalDatastore = __webpack_require__(27705);
RedisDatastore = __webpack_require__(36220);
Events = __webpack_require__(33800);
States = __webpack_require__(65376);
Sync = __webpack_require__(64915);
Bottleneck = function () {
class Bottleneck {
constructor(options = {}, ...invalid) {
var storeInstanceOptions, storeOptions;
this._addToQueue = this._addToQueue.bind(this);
this._validateOptions(options, invalid);
parser.load(options, this.instanceDefaults, this);
this._queues = new Queues(NUM_PRIORITIES);
this._scheduled = {};
this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : []));
this._limiter = null;
this.Events = new Events(this);
this._submitLock = new Sync("submit", this.Promise);
this._registerLock = new Sync("register", this.Promise);
storeOptions = parser.load(options, this.storeDefaults, {});
this._store = function () {
if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) {
storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {});
return new RedisDatastore(this, storeOptions, storeInstanceOptions);
} else if (this.datastore === "local") {
storeInstanceOptions = parser.load(options, this.localStoreDefaults, {});
return new LocalDatastore(this, storeOptions, storeInstanceOptions);
} else {
throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`);
}
}.call(this);
this._queues.on("leftzero", () => {
var ref;
return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0;
});
this._queues.on("zero", () => {
var ref;
return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0;
});
}
_validateOptions(options, invalid) {
if (!(options != null && typeof options === "object" && invalid.length === 0)) {
throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.");
}
}
ready() {
return this._store.ready;
}
clients() {
return this._store.clients;
}
channel() {
return `b_${this.id}`;
}
channel_client() {
return `b_${this.id}_${this._store.clientId}`;
}
publish(message) {
return this._store.__publish__(message);
}
disconnect(flush = true) {
return this._store.__disconnect__(flush);
}
chain(_limiter) {
this._limiter = _limiter;
return this;
}
queued(priority) {
return this._queues.queued(priority);
}
clusterQueued() {
return this._store.__queued__();
}
empty() {
return this.queued() === 0 && this._submitLock.isEmpty();
}
running() {
return this._store.__running__();
}
done() {
return this._store.__done__();
}
jobStatus(id) {
return this._states.jobStatus(id);
}
jobs(status) {
return this._states.statusJobs(status);
}
counts() {
return this._states.statusCounts();
}
_randomIndex() {
return Math.random().toString(36).slice(2);
}
check(weight = 1) {
return this._store.__check__(weight);
}
_clearGlobalState(index) {
if (this._scheduled[index] != null) {
clearTimeout(this._scheduled[index].expiration);
delete this._scheduled[index];
return true;
} else {
return false;
}
}
_free(index, job, options, eventInfo) {
var _this = this;
return _asyncToGenerator(function* () {
var e, running;
try {
var _ref = yield _this._store.__free__(index, options.weight);
running = _ref.running;
_this.Events.trigger("debug", `Freed ${options.id}`, eventInfo);
if (running === 0 && _this.empty()) {
return _this.Events.trigger("idle");
}
} catch (error1) {
e = error1;
return _this.Events.trigger("error", e);
}
})();
}
_run(index, job, wait) {
var clearGlobalState, free, run;
job.doRun();
clearGlobalState = this._clearGlobalState.bind(this, index);
run = this._run.bind(this, index, job);
free = this._free.bind(this, index, job);
return this._scheduled[index] = {
timeout: setTimeout(() => {
return job.doExecute(this._limiter, clearGlobalState, run, free);
}, wait),
expiration: job.options.expiration != null ? setTimeout(function () {
return job.doExpire(clearGlobalState, run, free);
}, wait + job.options.expiration) : void 0,
job: job
};
}
_drainOne(capacity) {
return this._registerLock.schedule(() => {
var args, index, next, options, queue;
if (this.queued() === 0) {
return this.Promise.resolve(null);
}
queue = this._queues.getFirst();
var _next2 = next = queue.first();
options = _next2.options;
args = _next2.args;
if (capacity != null && options.weight > capacity) {
return this.Promise.resolve(null);
}
this.Events.trigger("debug", `Draining ${options.id}`, {
args,
options
});
index = this._randomIndex();
return this._store.__register__(index, options.weight, options.expiration).then(({
success,
wait,
reservoir
}) => {
var empty;
this.Events.trigger("debug", `Drained ${options.id}`, {
success,
args,
options
});
if (success) {
queue.shift();
empty = this.empty();
if (empty) {
this.Events.trigger("empty");
}
if (reservoir === 0) {
this.Events.trigger("depleted", empty);
}
this._run(index, next, wait);
return this.Promise.resolve(options.weight);
} else {
return this.Promise.resolve(null);
}
});
});
}
_drainAll(capacity, total = 0) {
return this._drainOne(capacity).then(drained => {
var newCapacity;
if (drained != null) {
newCapacity = capacity != null ? capacity - drained : capacity;
return this._drainAll(newCapacity, total + drained);
} else {
return this.Promise.resolve(total);
}
}).catch(e => {
return this.Events.trigger("error", e);
});
}
_dropAllQueued(message) {
return this._queues.shiftAll(function (job) {
return job.doDrop({
message
});
});
}
stop(options = {}) {
var done, waitForExecuting;
options = parser.load(options, this.stopDefaults);
waitForExecuting = at => {
var finished;
finished = () => {
var counts;
counts = this._states.counts;
return counts[0] + counts[1] + counts[2] + counts[3] === at;
};
return new this.Promise((resolve, reject) => {
if (finished()) {
return resolve();
} else {
return this.on("done", () => {
if (finished()) {
this.removeAllListeners("done");
return resolve();
}
});
}
});
};
done = options.dropWaitingJobs ? (this._run = function (index, next) {
return next.doDrop({
message: options.dropErrorMessage
});
}, this._drainOne = () => {
return this.Promise.resolve(null);
}, this._registerLock.schedule(() => {
return this._submitLock.schedule(() => {
var k, ref, v;
ref = this._scheduled;
for (k in ref) {
v = ref[k];
if (this.jobStatus(v.job.options.id) === "RUNNING") {
clearTimeout(v.timeout);
clearTimeout(v.expiration);
v.job.doDrop({
message: options.dropErrorMessage
});
}
}
this._dropAllQueued(options.dropErrorMessage);
return waitForExecuting(0);
});
})) : this.schedule({
priority: NUM_PRIORITIES - 1,
weight: 0
}, () => {
return waitForExecuting(1);
});
this._receive = function (job) {
return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage));
};
this.stop = () => {
return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called"));
};
return done;
}
_addToQueue(job) {
var _this2 = this;
return _asyncToGenerator(function* () {
var args, blocked, error, options, reachedHWM, shifted, strategy;
args = job.args;
options = job.options;
try {
var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight);
reachedHWM = _ref2.reachedHWM;
blocked = _ref2.blocked;
strategy = _ref2.strategy;
} catch (error1) {
error = error1;
_this2.Events.trigger("debug", `Could not queue ${options.id}`, {
args,
options,
error
});
job.doDrop({
error
});
return false;
}
if (blocked) {
job.doDrop();
return true;
} else if (reachedHWM) {
shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;
if (shifted != null) {
shifted.doDrop();
}
if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) {
if (shifted == null) {
job.doDrop();
}
return reachedHWM;
}
}
job.doQueue(reachedHWM, blocked);
_this2._queues.push(job);
yield _this2._drainAll();
return reachedHWM;
})();
}
_receive(job) {
if (this._states.jobStatus(job.options.id) != null) {
job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`));
return false;
} else {
job.doReceive();
return this._submitLock.schedule(this._addToQueue, job);
}
}
submit(...args) {
var cb, fn, job, options, ref, ref1, task;
if (typeof args[0] === "function") {
var _ref3, _ref4, _splice$call, _splice$call2;
ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call);
options = parser.load({}, this.jobDefaults);
} else {
var _ref5, _ref6, _splice$call3, _splice$call4;
ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3);
options = parser.load(options, this.jobDefaults);
}
task = (...args) => {
return new this.Promise(function (resolve, reject) {
return fn(...args, function (...args) {
return (args[0] != null ? reject : resolve)(args);
});
});
};
job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
job.promise.then(function (args) {
return typeof cb === "function" ? cb(...args) : void 0;
}).catch(function (args) {
if (Array.isArray(args)) {
return typeof cb === "function" ? cb(...args) : void 0;
} else {
return typeof cb === "function" ? cb(args) : void 0;
}
});
return this._receive(job);
}
schedule(...args) {
var job, options, task;
if (typeof args[0] === "function") {
var _args = args;
var _args2 = _toArray(_args);
task = _args2[0];
args = _args2.slice(1);
options = {};
} else {
var _args3 = args;
var _args4 = _toArray(_args3);
options = _args4[0];
task = _args4[1];
args = _args4.slice(2);
}
job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);
this._receive(job);
return job.promise;
}
wrap(fn) {
var schedule, wrapped;
schedule = this.schedule.bind(this);
wrapped = function wrapped(...args) {
return schedule(fn.bind(this), ...args);
};
wrapped.withOptions = function (options, ...args) {
return schedule(options, fn, ...args);
};
return wrapped;
}
updateSettings(options = {}) {
var _this3 = this;
return _asyncToGenerator(function* () {
yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults));
parser.overwrite(options, _this3.instanceDefaults, _this3);
return _this3;
})();
}
currentReservoir() {
return this._store.__currentReservoir__();
}
incrementReservoir(incr = 0) {
return this._store.__incrementReservoir__(incr);
}
}
;
Bottleneck.default = Bottleneck;
Bottleneck.Events = Events;
Bottleneck.version = Bottleneck.prototype.version = __webpack_require__(82636)/* .version */ .i;
Bottleneck.strategy = Bottleneck.prototype.strategy = {
LEAK: 1,
OVERFLOW: 2,
OVERFLOW_PRIORITY: 4,
BLOCK: 3
};
Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __webpack_require__(34006);
Bottleneck.Group = Bottleneck.prototype.Group = __webpack_require__(99158);
Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __webpack_require__(66427);
Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __webpack_require__(9442);
Bottleneck.Batcher = Bottleneck.prototype.Batcher = __webpack_require__(9526);
Bottleneck.prototype.jobDefaults = {
priority: DEFAULT_PRIORITY,
weight: 1,
expiration: null,
id: "<no-id>"
};
Bottleneck.prototype.storeDefaults = {
maxConcurrent: null,
minTime: 0,
highWater: null,
strategy: Bottleneck.prototype.strategy.LEAK,
penalty: null,
reservoir: null,
reservoirRefreshInterval: null,
reservoirRefreshAmount: null,
reservoirIncreaseInterval: null,
reservoirIncreaseAmount: null,
reservoirIncreaseMaximum: null
};
Bottleneck.prototype.localStoreDefaults = {
Promise: Promise,
timeout: null,
heartbeatInterval: 250
};
Bottleneck.prototype.redisStoreDefaults = {
Promise: Promise,
timeout: null,
heartbeatInterval: 5000,
clientTimeout: 10000,
Redis: null,
clientOptions: {},
clusterNodes: null,
clearDatastore: false,
connection: null
};
Bottleneck.prototype.instanceDefaults = {
datastore: "local",
connection: null,
id: "<no-id>",
rejectOnDrop: true,
trackDoneStatus: false,
Promise: Promise
};
Bottleneck.prototype.stopDefaults = {
enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.",
dropWaitingJobs: true,
dropErrorMessage: "This limiter has been stopped."
};
return Bottleneck;
}.call(void 0);
module.exports = Bottleneck;
/***/ }),
/***/ 34006:
/***/ ((module) => {
"use strict";
var BottleneckError;
BottleneckError = class BottleneckError extends Error {};
module.exports = BottleneckError;
/***/ }),
/***/ 70938:
/***/ ((module) => {
"use strict";
var DLList;
DLList = class DLList {
constructor(incr, decr) {
this.incr = incr;
this.decr = decr;
this._first = null;
this._last = null;
this.length = 0;
}
push(value) {
var node;
this.length++;
if (typeof this.incr === "function") {
this.incr();
}
node = {
value,
prev: this._last,
next: null
};
if (this._last != null) {
this._last.next = node;
this._last = node;
} else {
this._first = this._last = node;
}
return void 0;
}
shift() {
var value;
if (this._first == null) {
return;
} else {
this.length--;
if (typeof this.decr === "function") {
this.decr();
}
}
value = this._first.value;
if ((this._first = this._first.next) != null) {
this._first.prev = null;
} else {
this._last = null;
}
return value;
}
first() {
if (this._first != null) {
return this._first.value;
}
}
getArray() {
var node, ref, results;
node = this._first;
results = [];
while (node != null) {
results.push((ref = node, node = node.next, ref.value));
}
return results;
}
forEachShift(cb) {
var node;
node = this.shift();
while (node != null) {
cb(node), node = this.shift();
}
return void 0;
}
debug() {
var node, ref, ref1, ref2, results;
node = this._first;
results = [];
while (node != null) {
results.push((ref = node, node = node.next, {
value: ref.value,
prev: (ref1 = ref.prev) != null ? ref1.value : void 0,
next: (ref2 = ref.next) != null ? ref2.value : void 0
}));
}
return results;
}
};
module.exports = DLList;
/***/ }),
/***/ 33800:
/***/ ((module) => {
"use strict";
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var Events;
Events = class Events {
constructor(instance) {
this.instance = instance;
this._events = {};
if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) {
throw new Error("An Emitter already exists for this object");
}
this.instance.on = (name, cb) => {
return this._addListener(name, "many", cb);
};
this.instance.once = (name, cb) => {
return this._addListener(name, "once", cb);
};
this.instance.removeAllListeners = (name = null) => {
if (name != null) {
return delete this._events[name];
} else {
return this._events = {};
}
};
}
_addListener(name, status, cb) {
var base;
if ((base = this._events)[name] == null) {
base[name] = [];
}
this._events[name].push({
cb,
status
});
return this.instance;
}
listenerCount(name) {
if (this._events[name] != null) {
return this._events[name].length;
} else {
return 0;
}
}
trigger(name, ...args) {
var _this = this;
return _asyncToGenerator(function* () {
var e, promises;
try {
if (name !== "debug") {
_this.trigger("debug", `Event triggered: ${name}`, args);
}
if (_this._events[name] == null) {
return;
}
_this._events[name] = _this._events[name].filter(function (listener) {
return listener.status !== "none";
});
promises = _this._events[name].map(
/*#__PURE__*/
function () {
var _ref = _asyncToGenerator(function* (listener) {
var e, returned;
if (listener.status === "none") {
return;
}
if (listener.status === "once") {
listener.status = "none";
}
try {
returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0;
if (typeof (returned != null ? returned.then : void 0) === "function") {
return yield returned;
} else {
return returned;
}
} catch (error) {
e = error;
if (true) {
_this.trigger("error", e);
}
return null;
}
});
return function (_x) {
return _ref.apply(this, arguments);
};
}());
return (yield Promise.all(promises)).find(function (x) {
return x != null;
});
} catch (error) {
e = error;
if (true) {
_this.trigger("error", e);
}
return null;
}
})();
}
};
module.exports = Events;
/***/ }),
/***/ 99158:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var Events, Group, IORedisConnection, RedisConnection, Scripts, parser;
parser = __webpack_require__(88092);
Events = __webpack_require__(33800);
RedisConnection = __webpack_require__(66427);
IORedisConnection = __webpack_require__(9442);
Scripts = __webpack_require__(40812);
Group = function () {
class Group {
constructor(limiterOptions = {}) {
this.deleteKey = this.deleteKey.bind(this);
this.limiterOptions = limiterOptions;
parser.load(this.limiterOptions, this.defaults, this);
this.Events = new Events(this);
this.instances = {};
this.Bottleneck = __webpack_require__(19529);
this._startAutoCleanup();
this.sharedConnection = this.connection != null;
if (this.connection == null) {
if (this.limiterOptions.datastore === "redis") {
this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, {
Events: this.Events
}));
} else if (this.limiterOptions.datastore === "ioredis") {
this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, {
Events: this.Events
}));
}
}
}
key(key = "") {
var ref;
return (ref = this.instances[key]) != null ? ref : (() => {
var limiter;
limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, {
id: `${this.id}-${key}`,
timeout: this.timeout,
connection: this.connection
}));
this.Events.trigger("created", limiter, key);
return limiter;
})();
}
deleteKey(key = "") {
var _this = this;
return _asyncToGenerator(function* () {
var deleted, instance;
instance = _this.instances[key];
if (_this.connection) {
deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]);
}
if (instance != null) {
delete _this.instances[key];
yield instance.disconnect();
}
return instance != null || deleted > 0;
})();
}
limiters() {
var k, ref, results, v;
ref = this.instances;
results = [];
for (k in ref) {
v = ref[k];
results.push({
key: k,
limiter: v
});
}
return results;
}
keys() {
return Object.keys(this.instances);
}
clusterKeys() {
var _this2 = this;
return _asyncToGenerator(function* () {
var cursor, end, found, i, k, keys, len, next, start;
if (_this2.connection == null) {
return _this2.Promise.resolve(_this2.keys());
}
keys = [];
cursor = null;
start = `b_${_this2.id}-`.length;
end = "_settings".length;
while (cursor !== 0) {
var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]);
var _ref2 = _slicedToArray(_ref, 2);
next = _ref2[0];
found = _ref2[1];
cursor = ~~next;
for (i = 0, len = found.length; i < len; i++) {
k = found[i];
keys.push(k.slice(start, -end));
}
}
return keys;
})();
}
_startAutoCleanup() {
var _this3 = this;
var base;
clearInterval(this.interval);
return typeof (base = this.interval = setInterval(
/*#__PURE__*/
_asyncToGenerator(function* () {
var e, k, ref, results, time, v;
time = Date.now();
ref = _this3.instances;
results = [];
for (k in ref) {
v = ref[k];
try {
if (yield v._store.__groupCheck__(time)) {
results.push(_this3.deleteKey(k));
} else {
results.push(void 0);
}
} catch (error) {
e = error;
results.push(v.Events.trigger("error", e));
}
}
return results;
}), this.timeout / 2)).unref === "function" ? base.unref() : void 0;
}
updateSettings(options = {}) {
parser.overwrite(options, this.defaults, this);
parser.overwrite(options, options, this.limiterOptions);
if (options.timeout != null) {
return this._startAutoCleanup();
}
}
disconnect(flush = true) {
var ref;
if (!this.sharedConnection) {
return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;
}
}
}
;
Group.prototype.defaults = {
timeout: 1000 * 60 * 5,
connection: null,
Promise: Promise,
id: "group-key"
};
return Group;
}.call(void 0);
module.exports = Group;
/***/ }),
/***/ 9442:
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {
"use strict";
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var Events, IORedisConnection, Scripts, parser;
parser = __webpack_require__(88092);
Events = __webpack_require__(33800);
Scripts = __webpack_require__(40812);
IORedisConnection = function () {
class IORedisConnection {
constructor(options = {}) {
parser.load(options, this.defaults, this);
if (this.Redis == null) {
this.Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module. To override this behavior: pass the ioredis module to Bottleneck as the 'Redis' option.
}
if (this.Events == null) {
this.Events = new Events(this);
}
this.terminated = false;
if (this.clusterNodes != null) {
this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions);
this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions);
} else if (this.client != null && this.client.duplicate == null) {
this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options);
} else {
if (this.client == null) {
this.client = new this.Redis(this.clientOptions);
}
this.subscriber = this.client.duplicate();
}
this.limiters = {};
this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => {
this._loadScripts();
return {
client: this.client,
subscriber: this.subscriber
};
});
}
_setup(client, sub) {
client.setMaxListeners(0);
return new this.Promise((resolve, reject) => {
client.on("error", e => {
return this.Events.trigger("error", e);
});
if (sub) {
client.on("message", (channel, message) => {
var ref;
return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0;
});
}
if (client.status === "ready") {
return resolve();
} else {
return client.once("ready", resolve);
}
});
}
_loadScripts() {
return Scripts.names.forEach(name => {
return this.client.defineCommand(name, {
lua: Scripts.payload(name)
});
});
}
__runCommand__(cmd) {
var _this = this;
return _asyncToGenerator(function* () {
var _, deleted;
yield _this.ready;
var _ref = yield _this.client.pipeline([cmd]).exec();
var _ref2 = _slicedToArray(_ref, 1);
var _ref2$ = _slicedToArray(_ref2[0], 2);
_ = _ref2$[0];
deleted = _ref2$[1];
return deleted;
})();
}
__addLimiter__(instance) {
return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => {
return new this.Promise((resolve, reject) => {
return this.subscriber.subscribe(channel, () => {
this.limiters[channel] = instance;
return resolve();
});
});
}));
}
__removeLimiter__(instance) {
var _this2 = this;
return [instance.channel(), instance.channel_client()].forEach(
/*#__PURE__*/
function () {
var _ref3 = _asyncToGenerator(function* (channel) {
if (!_this2.terminated) {
yield _this2.subscriber.unsubscribe(channel);
}
return delete _this2.limiters[channel];
});
return function (_x) {
return _ref3.apply(this, arguments);
};
}());
}
__scriptArgs__(name, id, args, cb) {
var keys;
keys = Scripts.keys(name, id);
return [keys.length].concat(keys, args, cb);
}
__scriptFn__(name) {
return this.client[name].bind(this.client);
}
disconnect(flush = true) {
var i, k, len, ref;
ref = Object.keys(this.limiters);
for (i = 0, len = ref.length; i < len; i++) {
k = ref[i];
clearInterval(this.limiters[k]._store.heartbeat);
}
this.limiters